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
79442
DQCoin
transfer
contract DQCoin is ERC20 { using SafeMath for uint256; address public owner; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; string public name = "DaQianCoin"; string public constant symbol = "DQC"; uint public constant decimals = 18; bool public stopped; modifier stoppable { assert(!stopped); _; } uint256 public totalSupply = 24000000000*(10**18); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event LOCK(address indexed _owner, uint256 _value); mapping (address => uint256) public lockAddress; modifier lock(address _add){ require(_add != address(0)); uint256 releaseTime = lockAddress[_add]; if(releaseTime > 0){ require(block.timestamp >= releaseTime); _; }else{ _; } } modifier onlyOwner() { require(msg.sender == owner); _; } function DQCoin() public { owner = msg.sender; balances[msg.sender] = totalSupply; } function stop() onlyOwner public { stopped = true; } function start() onlyOwner public { stopped = false; } function lockTime(address _to,uint256 _value) onlyOwner public { if(_value > block.timestamp){ lockAddress[_to] = _value; emit LOCK(_to, _value); } } function lockOf(address _owner) constant public returns (uint256) { return lockAddress[_owner]; } function transferOwnership(address _newOwner) onlyOwner public { if (_newOwner != address(0)) { owner = _newOwner; } } function () public payable { address myAddress = this; emit Transfer(msg.sender, myAddress, msg.value); } function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } function transfer(address _to, uint256 _amount) stoppable lock(msg.sender) public returns (bool success) {<FILL_FUNCTION_BODY> } function transferFrom(address _from, uint256 _amount) stoppable lock(_from) public returns (bool success) { require(_amount <= balances[_from]); require(_amount <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[msg.sender] = balances[msg.sender].add(_amount); emit Transfer(_from, msg.sender, _amount); return true; } function approve(address _spender, uint256 _value) stoppable lock(_spender) public returns (bool success) { if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; } allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256) { return allowed[_owner][_spender]; } function withdraw() onlyOwner public { address myAddress = this; uint256 etherBalance = myAddress.balance; owner.transfer(etherBalance); } function kill() onlyOwner public { selfdestruct(msg.sender); } function setName(string _name) onlyOwner public { name = _name; } }
contract DQCoin is ERC20 { using SafeMath for uint256; address public owner; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; string public name = "DaQianCoin"; string public constant symbol = "DQC"; uint public constant decimals = 18; bool public stopped; modifier stoppable { assert(!stopped); _; } uint256 public totalSupply = 24000000000*(10**18); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event LOCK(address indexed _owner, uint256 _value); mapping (address => uint256) public lockAddress; modifier lock(address _add){ require(_add != address(0)); uint256 releaseTime = lockAddress[_add]; if(releaseTime > 0){ require(block.timestamp >= releaseTime); _; }else{ _; } } modifier onlyOwner() { require(msg.sender == owner); _; } function DQCoin() public { owner = msg.sender; balances[msg.sender] = totalSupply; } function stop() onlyOwner public { stopped = true; } function start() onlyOwner public { stopped = false; } function lockTime(address _to,uint256 _value) onlyOwner public { if(_value > block.timestamp){ lockAddress[_to] = _value; emit LOCK(_to, _value); } } function lockOf(address _owner) constant public returns (uint256) { return lockAddress[_owner]; } function transferOwnership(address _newOwner) onlyOwner public { if (_newOwner != address(0)) { owner = _newOwner; } } function () public payable { address myAddress = this; emit Transfer(msg.sender, myAddress, msg.value); } function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } <FILL_FUNCTION> function transferFrom(address _from, uint256 _amount) stoppable lock(_from) public returns (bool success) { require(_amount <= balances[_from]); require(_amount <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[msg.sender] = balances[msg.sender].add(_amount); emit Transfer(_from, msg.sender, _amount); return true; } function approve(address _spender, uint256 _value) stoppable lock(_spender) public returns (bool success) { if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; } allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256) { return allowed[_owner][_spender]; } function withdraw() onlyOwner public { address myAddress = this; uint256 etherBalance = myAddress.balance; owner.transfer(etherBalance); } function kill() onlyOwner public { selfdestruct(msg.sender); } function setName(string _name) onlyOwner public { name = _name; } }
require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true;
function transfer(address _to, uint256 _amount) stoppable lock(msg.sender) public returns (bool success)
function transfer(address _to, uint256 _amount) stoppable lock(msg.sender) public returns (bool success)
21344
ANKR
approveAndCall
contract ANKR is StandardToken { function () { //if ether is sent to this address, send it back. throw; } /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme. // // CHANGE THESE VALUES FOR YOUR TOKEN // //make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token function ANKR( ) { balances[msg.sender] = 186000000000000000000000000; // Give the creator all initial tokens (100000 for example) totalSupply = 186000000000000000000000000; // Update total supply (100000 for example) name = "ANKR Network"; // Set the name for display purposes decimals = 18; // Amount of decimals for display purposes symbol = "ANKR"; // Set the symbol for display purposes } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {<FILL_FUNCTION_BODY> } }
contract ANKR is StandardToken { function () { //if ether is sent to this address, send it back. throw; } /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme. // // CHANGE THESE VALUES FOR YOUR TOKEN // //make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token function ANKR( ) { balances[msg.sender] = 186000000000000000000000000; // Give the creator all initial tokens (100000 for example) totalSupply = 186000000000000000000000000; // Update total supply (100000 for example) name = "ANKR Network"; // Set the name for display purposes decimals = 18; // Amount of decimals for display purposes symbol = "ANKR"; // Set the symbol for display purposes } <FILL_FUNCTION> }
allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true;
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success)
/* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success)
22263
Owned
acceptOwnership
contract Owned { address public owner; address public newOwner; bool public shouldBurn = false; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function activateBurn(bool burnState) public onlyOwner { shouldBurn = burnState; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public {<FILL_FUNCTION_BODY> } }
contract Owned { address public owner; address public newOwner; bool public shouldBurn = false; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function activateBurn(bool burnState) public onlyOwner { shouldBurn = burnState; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } <FILL_FUNCTION> }
require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0);
function acceptOwnership() public
function acceptOwnership() public
62482
ShanHuCoin
transfer
contract ShanHuCoin { /* Public variables of the token */ string public standard = 'ShanHuCoin 0.1'; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ function ShanHuCoin() { balanceOf[msg.sender] = 11000000 * 1000000000000000000; // Give the creator all initial tokens totalSupply = 11000000 * 1000000000000000000; // Update total supply name = "ShanHuCoin"; // Set the name for display purposes symbol = "SHC"; // Set the symbol for display purposes decimals = 18; // Amount of decimals for display purposes } /* Send coins */ function transfer(address _to, uint256 _value) {<FILL_FUNCTION_BODY> } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /* Approve and then communicate the approved contract in a single tx */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } function burn(uint256 _value) returns (bool success) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) returns (bool success) { if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(_from, _value); return true; } }
contract ShanHuCoin { /* Public variables of the token */ string public standard = 'ShanHuCoin 0.1'; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ function ShanHuCoin() { balanceOf[msg.sender] = 11000000 * 1000000000000000000; // Give the creator all initial tokens totalSupply = 11000000 * 1000000000000000000; // Update total supply name = "ShanHuCoin"; // Set the name for display purposes symbol = "SHC"; // Set the symbol for display purposes decimals = 18; // Amount of decimals for display purposes } <FILL_FUNCTION> /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /* Approve and then communicate the approved contract in a single tx */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } function burn(uint256 _value) returns (bool success) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) returns (bool success) { if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(_from, _value); return true; } }
if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows balanceOf[msg.sender] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
function transfer(address _to, uint256 _value)
/* Send coins */ function transfer(address _to, uint256 _value)
67061
PuppyGotchi
null
contract PuppyGotchi is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private bots; mapping (address => uint) private cooldown; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "PuppyGotchi"; string private constant _symbol = "PUPP"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () {<FILL_FUNCTION_BODY> } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 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 = 30000000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
contract PuppyGotchi is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private bots; mapping (address => uint) private cooldown; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "PuppyGotchi"; string private constant _symbol = "PUPP"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } <FILL_FUNCTION> function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 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 = 30000000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
_feeAddrWallet1 = payable(0xD02E54bAFDe706b159c1826eFE3a1Da9F438847d); _feeAddrWallet2 = payable(0xD02E54bAFDe706b159c1826eFE3a1Da9F438847d); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xD02E54bAFDe706b159c1826eFE3a1Da9F438847d), _msgSender(), _tTotal);
constructor ()
constructor ()
69526
GSNRecipient
_msgSender
contract GSNRecipient is IRelayRecipient, Context { address private _relayHub = 0xD216153c06E857cD7f72665E0aF1d7D82172F494; uint256 constant private RELAYED_CALL_ACCEPTED = 0; uint256 constant private RELAYED_CALL_REJECTED = 11; uint256 constant internal POST_RELAYED_CALL_MAX_GAS = 100000; event RelayHubChanged(address indexed oldRelayHub, address indexed newRelayHub); function getHubAddr() public view returns (address) { return _relayHub; } function _upgradeRelayHub(address newRelayHub) internal { address currentRelayHub = _relayHub; require(newRelayHub != address(0), "GSNRecipient: new RelayHub is the zero address"); require(newRelayHub != currentRelayHub, "GSNRecipient: new RelayHub is the current one"); emit RelayHubChanged(currentRelayHub, newRelayHub); _relayHub = newRelayHub; } function relayHubVersion() public view returns (string memory) { this; return "1.0.0"; } function _withdrawDeposits(uint256 amount, address payable payee) internal { IRelayHub(_relayHub).withdraw(amount, payee); } function _msgSender() internal view returns (address payable) {<FILL_FUNCTION_BODY> } function _msgData() internal view returns (bytes memory) { if (msg.sender != _relayHub) { return msg.data; } else { return _getRelayedCallData(); } } function preRelayedCall(bytes calldata context) external returns (bytes32) { require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub"); return _preRelayedCall(context); } function _preRelayedCall(bytes memory context) internal returns (bytes32); function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external { require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub"); _postRelayedCall(context, success, actualCharge, preRetVal); } function _postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) internal; function _approveRelayedCall() internal pure returns (uint256, bytes memory) { return _approveRelayedCall(""); } function _approveRelayedCall(bytes memory context) internal pure returns (uint256, bytes memory) { return (RELAYED_CALL_ACCEPTED, context); } function _rejectRelayedCall(uint256 errorCode) internal pure returns (uint256, bytes memory) { return (RELAYED_CALL_REJECTED + errorCode, ""); } function _computeCharge(uint256 gas, uint256 gasPrice, uint256 serviceFee) internal pure returns (uint256) { return (gas * gasPrice * (100 + serviceFee)) / 100; } function _getRelayedCallSender() private pure returns (address payable result) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { result := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } function _getRelayedCallData() private pure returns (bytes memory) { uint256 actualDataLength = msg.data.length - 20; bytes memory actualData = new bytes(actualDataLength); for (uint256 i = 0; i < actualDataLength; ++i) { actualData[i] = msg.data[i]; } return actualData; } }
contract GSNRecipient is IRelayRecipient, Context { address private _relayHub = 0xD216153c06E857cD7f72665E0aF1d7D82172F494; uint256 constant private RELAYED_CALL_ACCEPTED = 0; uint256 constant private RELAYED_CALL_REJECTED = 11; uint256 constant internal POST_RELAYED_CALL_MAX_GAS = 100000; event RelayHubChanged(address indexed oldRelayHub, address indexed newRelayHub); function getHubAddr() public view returns (address) { return _relayHub; } function _upgradeRelayHub(address newRelayHub) internal { address currentRelayHub = _relayHub; require(newRelayHub != address(0), "GSNRecipient: new RelayHub is the zero address"); require(newRelayHub != currentRelayHub, "GSNRecipient: new RelayHub is the current one"); emit RelayHubChanged(currentRelayHub, newRelayHub); _relayHub = newRelayHub; } function relayHubVersion() public view returns (string memory) { this; return "1.0.0"; } function _withdrawDeposits(uint256 amount, address payable payee) internal { IRelayHub(_relayHub).withdraw(amount, payee); } <FILL_FUNCTION> function _msgData() internal view returns (bytes memory) { if (msg.sender != _relayHub) { return msg.data; } else { return _getRelayedCallData(); } } function preRelayedCall(bytes calldata context) external returns (bytes32) { require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub"); return _preRelayedCall(context); } function _preRelayedCall(bytes memory context) internal returns (bytes32); function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external { require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub"); _postRelayedCall(context, success, actualCharge, preRetVal); } function _postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) internal; function _approveRelayedCall() internal pure returns (uint256, bytes memory) { return _approveRelayedCall(""); } function _approveRelayedCall(bytes memory context) internal pure returns (uint256, bytes memory) { return (RELAYED_CALL_ACCEPTED, context); } function _rejectRelayedCall(uint256 errorCode) internal pure returns (uint256, bytes memory) { return (RELAYED_CALL_REJECTED + errorCode, ""); } function _computeCharge(uint256 gas, uint256 gasPrice, uint256 serviceFee) internal pure returns (uint256) { return (gas * gasPrice * (100 + serviceFee)) / 100; } function _getRelayedCallSender() private pure returns (address payable result) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { result := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } function _getRelayedCallData() private pure returns (bytes memory) { uint256 actualDataLength = msg.data.length - 20; bytes memory actualData = new bytes(actualDataLength); for (uint256 i = 0; i < actualDataLength; ++i) { actualData[i] = msg.data[i]; } return actualData; } }
if (msg.sender != _relayHub) { return msg.sender; } else { return _getRelayedCallSender(); }
function _msgSender() internal view returns (address payable)
function _msgSender() internal view returns (address payable)
82441
DogeARMY
_getTValues
contract DogeARMY 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 => User) private cooldown; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1e14 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private constant _name = unicode"DogeARMY"; string private constant _symbol = unicode"DogeARMY"; uint8 private constant _decimals = 9; uint256 private _taxFee = 1; uint256 private _teamFee = 6; uint256 private _feeRate = 7; uint256 private _feeMultiplier = 1000; uint256 private _launchTime; uint256 private _previousTaxFee = _taxFee; uint256 private _previousteamFee = _teamFee; uint256 private _maxBuyAmount; address payable private _FeeAddress; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private _cooldownEnabled = true; bool private inSwap = false; uint256 private buyLimitEnd; struct User { uint256 buy; uint256 sell; bool exists; } event MaxBuyAmountUpdated(uint _maxBuyAmount); event CooldownEnabledUpdated(bool _cooldown); event FeeMultiplierUpdated(uint _multiplier); event FeeRateUpdated(uint _rate); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable FeeAddress) { _FeeAddress = FeeAddress; _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[FeeAddress] = 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 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; _previousTaxFee = _taxFee; _previousteamFee = _teamFee; _taxFee = 0; _teamFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _teamFee = _previousteamFee; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) { if(_cooldownEnabled) { if(!cooldown[msg.sender].exists) { cooldown[msg.sender] = User(0,0,true); } } // buy if(from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to]) { require(tradingOpen, "Trading not yet enabled."); _teamFee = 6; if(_cooldownEnabled) { if(buyLimitEnd > block.timestamp) { require(amount <= _maxBuyAmount); require(cooldown[to].buy < block.timestamp, "Your buy cooldown has not expired."); cooldown[to].buy = block.timestamp + (45 seconds); } } if(_cooldownEnabled) { cooldown[to].sell = block.timestamp + (15 seconds); } } uint256 contractTokenBalance = balanceOf(address(this)); // sell if(!inSwap && from != uniswapV2Pair && tradingOpen) { _teamFee = 10; if(_cooldownEnabled) { require(cooldown[from].sell < block.timestamp, "Your sell cooldown has not expired."); } if(contractTokenBalance > 0) { if(contractTokenBalance > balanceOf(uniswapV2Pair).mul(_feeRate).div(100)) { contractTokenBalance = balanceOf(uniswapV2Pair).mul(_feeRate).div(100); } swapTokensForEth(contractTokenBalance); } uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _FeeAddress.transfer(amount); } 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 _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) {<FILL_FUNCTION_BODY> } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if(rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } 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 _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 addLiquidity() 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); _maxBuyAmount = 300000000000 * 10**9; _launchTime = block.timestamp; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function openTrading() public onlyOwner { tradingOpen = true; buyLimitEnd = block.timestamp + (120 seconds); } function manualswap() external { require(_msgSender() == _FeeAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _FeeAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } // fallback in case contract is not releasing tokens fast enough function setFeeRate(uint256 rate) external { require(_msgSender() == _FeeAddress); require(rate < 51, "Rate can't exceed 50%"); _feeRate = rate; emit FeeRateUpdated(_feeRate); } function setCooldownEnabled(bool onoff) external onlyOwner() { _cooldownEnabled = onoff; emit CooldownEnabledUpdated(_cooldownEnabled); } function thisBalance() public view returns (uint) { return balanceOf(address(this)); } function cooldownEnabled() public view returns (bool) { return _cooldownEnabled; } function timeToBuy(address buyer) public view returns (uint) { return block.timestamp - cooldown[buyer].buy; } function timeToSell(address buyer) public view returns (uint) { return block.timestamp - cooldown[buyer].sell; } function amountInPool() public view returns (uint) { return balanceOf(uniswapV2Pair); } }
contract DogeARMY 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 => User) private cooldown; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1e14 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private constant _name = unicode"DogeARMY"; string private constant _symbol = unicode"DogeARMY"; uint8 private constant _decimals = 9; uint256 private _taxFee = 1; uint256 private _teamFee = 6; uint256 private _feeRate = 7; uint256 private _feeMultiplier = 1000; uint256 private _launchTime; uint256 private _previousTaxFee = _taxFee; uint256 private _previousteamFee = _teamFee; uint256 private _maxBuyAmount; address payable private _FeeAddress; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private _cooldownEnabled = true; bool private inSwap = false; uint256 private buyLimitEnd; struct User { uint256 buy; uint256 sell; bool exists; } event MaxBuyAmountUpdated(uint _maxBuyAmount); event CooldownEnabledUpdated(bool _cooldown); event FeeMultiplierUpdated(uint _multiplier); event FeeRateUpdated(uint _rate); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable FeeAddress) { _FeeAddress = FeeAddress; _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[FeeAddress] = 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 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; _previousTaxFee = _taxFee; _previousteamFee = _teamFee; _taxFee = 0; _teamFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _teamFee = _previousteamFee; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) { if(_cooldownEnabled) { if(!cooldown[msg.sender].exists) { cooldown[msg.sender] = User(0,0,true); } } // buy if(from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to]) { require(tradingOpen, "Trading not yet enabled."); _teamFee = 6; if(_cooldownEnabled) { if(buyLimitEnd > block.timestamp) { require(amount <= _maxBuyAmount); require(cooldown[to].buy < block.timestamp, "Your buy cooldown has not expired."); cooldown[to].buy = block.timestamp + (45 seconds); } } if(_cooldownEnabled) { cooldown[to].sell = block.timestamp + (15 seconds); } } uint256 contractTokenBalance = balanceOf(address(this)); // sell if(!inSwap && from != uniswapV2Pair && tradingOpen) { _teamFee = 10; if(_cooldownEnabled) { require(cooldown[from].sell < block.timestamp, "Your sell cooldown has not expired."); } if(contractTokenBalance > 0) { if(contractTokenBalance > balanceOf(uniswapV2Pair).mul(_feeRate).div(100)) { contractTokenBalance = balanceOf(uniswapV2Pair).mul(_feeRate).div(100); } swapTokensForEth(contractTokenBalance); } uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _FeeAddress.transfer(amount); } 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 _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); } <FILL_FUNCTION> function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if(rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } 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 _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 addLiquidity() 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); _maxBuyAmount = 300000000000 * 10**9; _launchTime = block.timestamp; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function openTrading() public onlyOwner { tradingOpen = true; buyLimitEnd = block.timestamp + (120 seconds); } function manualswap() external { require(_msgSender() == _FeeAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _FeeAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } // fallback in case contract is not releasing tokens fast enough function setFeeRate(uint256 rate) external { require(_msgSender() == _FeeAddress); require(rate < 51, "Rate can't exceed 50%"); _feeRate = rate; emit FeeRateUpdated(_feeRate); } function setCooldownEnabled(bool onoff) external onlyOwner() { _cooldownEnabled = onoff; emit CooldownEnabledUpdated(_cooldownEnabled); } function thisBalance() public view returns (uint) { return balanceOf(address(this)); } function cooldownEnabled() public view returns (bool) { return _cooldownEnabled; } function timeToBuy(address buyer) public view returns (uint) { return block.timestamp - cooldown[buyer].buy; } function timeToSell(address buyer) public view returns (uint) { return block.timestamp - cooldown[buyer].sell; } function amountInPool() public view returns (uint) { return balanceOf(uniswapV2Pair); } }
uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam);
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256)
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256)
29190
NzinCoin
null
contract NzinCoin is ERC20Mintable, ERC20Burnable, ERC20Detailed { constructor (address owner) public ERC20Detailed("Nzin Coin", "NZC", 18) {<FILL_FUNCTION_BODY> } }
contract NzinCoin is ERC20Mintable, ERC20Burnable, ERC20Detailed { <FILL_FUNCTION> }
_mint(owner, 1000000000 * (10 ** uint256(decimals()))); _addMinter(owner);
constructor (address owner) public ERC20Detailed("Nzin Coin", "NZC", 18)
constructor (address owner) public ERC20Detailed("Nzin Coin", "NZC", 18)
15390
FlashloanV1
executeOperation
contract FlashloanV1 is FlashLoanReceiverBaseV1 { constructor() FlashLoanReceiverBaseV1(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8) public{ master = payable(msg.sender); } address public uniswap = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public sushiswap = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(uniswap); IUniswapV2Router02 _sushiswapRouter = IUniswapV2Router02(sushiswap); event FlashLoanEmitted( address a, address b, uint256 repayAmount ); address public loantoken = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public tradetoken; address payable public master; uint8 public direction; function flashloan(uint256 _amount, address _tradetoken, uint8 _direction) public onlyOwner { bytes memory data = ""; uint amount = _amount * 1000000000000000000; tradetoken = _tradetoken; direction = _direction; ILendingPoolV1 lendingPool = ILendingPoolV1(addressesProvider.getLendingPool()); lendingPool.flashLoan(address(this), loantoken, amount, data); } function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params ) external override {<FILL_FUNCTION_BODY> } function sendViaTransfer(address payable _to, uint256 amount) public payable { // This function is no longer recommended for sending Ether. _to.transfer(amount); } }
contract FlashloanV1 is FlashLoanReceiverBaseV1 { constructor() FlashLoanReceiverBaseV1(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8) public{ master = payable(msg.sender); } address public uniswap = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public sushiswap = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(uniswap); IUniswapV2Router02 _sushiswapRouter = IUniswapV2Router02(sushiswap); event FlashLoanEmitted( address a, address b, uint256 repayAmount ); address public loantoken = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public tradetoken; address payable public master; uint8 public direction; function flashloan(uint256 _amount, address _tradetoken, uint8 _direction) public onlyOwner { bytes memory data = ""; uint amount = _amount * 1000000000000000000; tradetoken = _tradetoken; direction = _direction; ILendingPoolV1 lendingPool = ILendingPoolV1(addressesProvider.getLendingPool()); lendingPool.flashLoan(address(this), loantoken, amount, data); } <FILL_FUNCTION> function sendViaTransfer(address payable _to, uint256 amount) public payable { // This function is no longer recommended for sending Ether. _to.transfer(amount); } }
require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance, was the flashLoan successful?"); // // Your logic goes here. // !! Ensure that *this contract* has enough of `_reserve` funds to payback the `_fee` !! // if (direction == 1){ address[] memory path = new address[](2); uint256 amountIna = address(this).balance; path[0] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; path[1] = tradetoken; _uniswapV2Router.swapExactETHForTokens{value: amountIna}(0, path, address(this), block.timestamp+100); uint256 amountInweth = IERC20(tradetoken).balanceOf(address(this)); IERC20(tradetoken).approve(sushiswap, amountInweth); path[0] = tradetoken; path[1] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; _sushiswapRouter.swapExactTokensForETH(amountInweth, 0, path, address(this), block.timestamp + 100); } if (direction == 2){ address[] memory path = new address[](2); uint256 amountIna = address(this).balance; path[0] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; path[1] = tradetoken; _sushiswapRouter.swapExactETHForTokens{value: amountIna}(0, path, address(this), block.timestamp + 100); uint256 amountInweth = IERC20(tradetoken).balanceOf(address(this)); IERC20(tradetoken).approve(uniswap, amountInweth); path[0] = tradetoken; path[1] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; _uniswapV2Router.swapExactTokensForETH(amountInweth, 0, path, address(this), block.timestamp + 100); } uint totalDebt = _amount.add(_fee); transferFundsBackToPoolInternal(_reserve, totalDebt); sendViaTransfer(master , address(this).balance);
function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params ) external override
function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params ) external override
82596
SkillCoinTest
bulkTransfer
contract SkillCoinTest is ERC223, Ownable { using SafeMath for uint256; string public name = "SKILLCOINtest"; string public symbol = "TEST"; uint8 public decimals = 18; uint256 public totalSupply = 30e9 * 1e18; address public projectMemberAddress = 0x1Ea27b073Bb648fae5a8ec81E3460146BE8D0763; address public developmentAddress = 0xabC0196253cd173c448A50edc991E041F49d5ee6; address public operatingAddress = 0xD399ca463154F410Db104FC976129De7d1e78126; address public initialSupplyAddress = 0x3a411e42c6ab79aDCCf10946646A6A6a458f6cB2; mapping(address => uint256) public balanceOf; mapping(address => mapping (address => uint256)) public allowance; mapping (address => bool) public frozenAccount; mapping (address => uint256) public unlockUnixTime; event FrozenFunds(address indexed target, bool frozen); event LockedFunds(address indexed target, uint256 locked); event Burn(address indexed from, uint256 amount); /** * @dev Constructor is called only once and can not be called again */ function SkillCoinTest() public { owner = msg.sender; balanceOf[msg.sender] = totalSupply.mul(25).div(100); balanceOf[projectMemberAddress] = totalSupply.mul(10).div(100); balanceOf[developmentAddress] = totalSupply.mul(30).div(100); balanceOf[operatingAddress] = totalSupply.mul(10).div(100); balanceOf[initialSupplyAddress] = totalSupply.mul(25).div(100); } function name() public view returns (string _name) { return name; } function symbol() public view returns (string _symbol) { return symbol; } function decimals() public view returns (uint8 _decimals) { return decimals; } function totalSupply() public view returns (uint256 _totalSupply) { return totalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOf[_owner]; } /** * @dev Prevent targets from sending or receiving tokens * @param targets Addresses to be frozen * @param isFrozen either to freeze it or not */ function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public { require(targets.length > 0); for (uint j = 0; j < targets.length; j++) { require(targets[j] != 0x0); frozenAccount[targets[j]] = isFrozen; FrozenFunds(targets[j], isFrozen); } } /** * @dev Prevent targets from sending or receiving tokens by setting Unix times * @param targets Addresses to be locked funds * @param unixTimes Unix times when locking up will be finished */ function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public { require(targets.length > 0 && targets.length == unixTimes.length); for(uint j = 0; j < targets.length; j++){ require(unlockUnixTime[targets[j]] < unixTimes[j]); unlockUnixTime[targets[j]] = unixTimes[j]; LockedFunds(targets[j], unixTimes[j]); } } /** * @dev Function that is called when a user or another contract wants to transfer funds */ function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } else { return transferToAddress(_to, _value, _data); } } function transfer(address _to, uint _value, bytes _data) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } /** * @dev Standard function transfer similar to ERC20 transfer with no _data * Added due to backwards compatibility reasons */ function transfer(address _to, uint _value) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } // assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private view 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 that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } // function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * Added due to backwards compatibility with ERC20 * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_to != address(0) && _value > 0 && balanceOf[_from] >= _value && allowance[_from][msg.sender] >= _value && frozenAccount[_from] == false && frozenAccount[_to] == false && now > unlockUnixTime[_from] && now > unlockUnixTime[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Allows _spender to spend no more than _value tokens in your behalf * Added due to backwards compatibility with ERC20 * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender * Added due to backwards compatibility with ERC20 * @param _owner address The address which owns the funds * @param _spender address The address which will spend the funds */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowance[_owner][_spender]; } /** * @dev Burns a specific amount of tokens. * @param _from The address that will burn the tokens. * @param _unitAmount The amount of token to be burned. */ function burn(address _from, uint256 _unitAmount) onlyOwner public { require(_unitAmount > 0 && balanceOf[_from] >= _unitAmount); balanceOf[_from] = balanceOf[_from].sub(_unitAmount); totalSupply = totalSupply.sub(_unitAmount); Burn(_from, _unitAmount); } /** * @dev Function to distribute tokens to the list of addresses by the provided amount */ function bulkTransfer(address[] addresses, uint256 amount) public returns (bool) {<FILL_FUNCTION_BODY> } function bulkTransfer(address[] addresses, uint256[] amounts) public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); uint256 totalAmount = 0; for(uint j = 0; j < addresses.length; j++){ require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e18); totalAmount = totalAmount.add(amounts[j]); } require(balanceOf[msg.sender] >= totalAmount); for (j = 0; j < addresses.length; j++) { balanceOf[msg.sender] = balanceOf[msg.sender].sub(amounts[j]); balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]); Transfer(msg.sender, addresses[j], amounts[j]); } return true; } }
contract SkillCoinTest is ERC223, Ownable { using SafeMath for uint256; string public name = "SKILLCOINtest"; string public symbol = "TEST"; uint8 public decimals = 18; uint256 public totalSupply = 30e9 * 1e18; address public projectMemberAddress = 0x1Ea27b073Bb648fae5a8ec81E3460146BE8D0763; address public developmentAddress = 0xabC0196253cd173c448A50edc991E041F49d5ee6; address public operatingAddress = 0xD399ca463154F410Db104FC976129De7d1e78126; address public initialSupplyAddress = 0x3a411e42c6ab79aDCCf10946646A6A6a458f6cB2; mapping(address => uint256) public balanceOf; mapping(address => mapping (address => uint256)) public allowance; mapping (address => bool) public frozenAccount; mapping (address => uint256) public unlockUnixTime; event FrozenFunds(address indexed target, bool frozen); event LockedFunds(address indexed target, uint256 locked); event Burn(address indexed from, uint256 amount); /** * @dev Constructor is called only once and can not be called again */ function SkillCoinTest() public { owner = msg.sender; balanceOf[msg.sender] = totalSupply.mul(25).div(100); balanceOf[projectMemberAddress] = totalSupply.mul(10).div(100); balanceOf[developmentAddress] = totalSupply.mul(30).div(100); balanceOf[operatingAddress] = totalSupply.mul(10).div(100); balanceOf[initialSupplyAddress] = totalSupply.mul(25).div(100); } function name() public view returns (string _name) { return name; } function symbol() public view returns (string _symbol) { return symbol; } function decimals() public view returns (uint8 _decimals) { return decimals; } function totalSupply() public view returns (uint256 _totalSupply) { return totalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOf[_owner]; } /** * @dev Prevent targets from sending or receiving tokens * @param targets Addresses to be frozen * @param isFrozen either to freeze it or not */ function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public { require(targets.length > 0); for (uint j = 0; j < targets.length; j++) { require(targets[j] != 0x0); frozenAccount[targets[j]] = isFrozen; FrozenFunds(targets[j], isFrozen); } } /** * @dev Prevent targets from sending or receiving tokens by setting Unix times * @param targets Addresses to be locked funds * @param unixTimes Unix times when locking up will be finished */ function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public { require(targets.length > 0 && targets.length == unixTimes.length); for(uint j = 0; j < targets.length; j++){ require(unlockUnixTime[targets[j]] < unixTimes[j]); unlockUnixTime[targets[j]] = unixTimes[j]; LockedFunds(targets[j], unixTimes[j]); } } /** * @dev Function that is called when a user or another contract wants to transfer funds */ function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } else { return transferToAddress(_to, _value, _data); } } function transfer(address _to, uint _value, bytes _data) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } /** * @dev Standard function transfer similar to ERC20 transfer with no _data * Added due to backwards compatibility reasons */ function transfer(address _to, uint _value) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } // assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private view 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 that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } // function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * Added due to backwards compatibility with ERC20 * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_to != address(0) && _value > 0 && balanceOf[_from] >= _value && allowance[_from][msg.sender] >= _value && frozenAccount[_from] == false && frozenAccount[_to] == false && now > unlockUnixTime[_from] && now > unlockUnixTime[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Allows _spender to spend no more than _value tokens in your behalf * Added due to backwards compatibility with ERC20 * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender * Added due to backwards compatibility with ERC20 * @param _owner address The address which owns the funds * @param _spender address The address which will spend the funds */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowance[_owner][_spender]; } /** * @dev Burns a specific amount of tokens. * @param _from The address that will burn the tokens. * @param _unitAmount The amount of token to be burned. */ function burn(address _from, uint256 _unitAmount) onlyOwner public { require(_unitAmount > 0 && balanceOf[_from] >= _unitAmount); balanceOf[_from] = balanceOf[_from].sub(_unitAmount); totalSupply = totalSupply.sub(_unitAmount); Burn(_from, _unitAmount); } <FILL_FUNCTION> function bulkTransfer(address[] addresses, uint256[] amounts) public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); uint256 totalAmount = 0; for(uint j = 0; j < addresses.length; j++){ require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e18); totalAmount = totalAmount.add(amounts[j]); } require(balanceOf[msg.sender] >= totalAmount); for (j = 0; j < addresses.length; j++) { balanceOf[msg.sender] = balanceOf[msg.sender].sub(amounts[j]); balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]); Transfer(msg.sender, addresses[j], amounts[j]); } return true; } }
require(amount > 0 && addresses.length > 0 && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); amount = amount.mul(1e18); uint256 totalAmount = amount.mul(addresses.length); require(balanceOf[msg.sender] >= totalAmount); for (uint j = 0; j < addresses.length; j++) { require(addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount); balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount); Transfer(msg.sender, addresses[j], amount); } return true;
function bulkTransfer(address[] addresses, uint256 amount) public returns (bool)
/** * @dev Function to distribute tokens to the list of addresses by the provided amount */ function bulkTransfer(address[] addresses, uint256 amount) public returns (bool)
70656
VCOIN
approve
contract VCOIN is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function VCOIN() public { symbol = "VN"; name = "VCOIN"; decimals = 18; _totalSupply = 1000000000000000000000000000; balances[0x17318B8a5B46a33aCfBcEC44044d4e3940F8EB07] = _totalSupply; Transfer(address(0), 0x17318B8a5B46a33aCfBcEC44044d4e3940F8EB07, _totalSupply); } /** constructor() public { distribution["Sale"]=distribution_detail(500000000 * 10 ** 18 , 500000000 * 10 ** 18 , 0 , release_type.Direct); distribution["Reserve"]=distribution_detail(300000000 * 10 ** 18 , 300000000 * 10 ** 18 , 0 , release_type.Direct); distribution["Team"]=distribution_detail(100000000 * 10 ** 18 , 100000000 * 10 ** 18 , 0 , release_type.Direct); distribution["Marketing"]=distribution_detail(50000000 * 10 ** 18 , 50000000 * 10 * 18 , 0 , release_type.Direct); distribution["Partner"]=distribution_detail(40000000 * 10 ** 18 , 40000000 * 10 ** 18, 1619740800, release_type.Fixed); distribution["Airdrop"]=distribution_detail(10000000 * 10 ** 18 , 10000000 * 10 ** 18 , 1588204800 , release_type.Fixed); } */ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract VCOIN is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function VCOIN() public { symbol = "VN"; name = "VCOIN"; decimals = 18; _totalSupply = 1000000000000000000000000000; balances[0x17318B8a5B46a33aCfBcEC44044d4e3940F8EB07] = _totalSupply; Transfer(address(0), 0x17318B8a5B46a33aCfBcEC44044d4e3940F8EB07, _totalSupply); } /** constructor() public { distribution["Sale"]=distribution_detail(500000000 * 10 ** 18 , 500000000 * 10 ** 18 , 0 , release_type.Direct); distribution["Reserve"]=distribution_detail(300000000 * 10 ** 18 , 300000000 * 10 ** 18 , 0 , release_type.Direct); distribution["Team"]=distribution_detail(100000000 * 10 ** 18 , 100000000 * 10 ** 18 , 0 , release_type.Direct); distribution["Marketing"]=distribution_detail(50000000 * 10 ** 18 , 50000000 * 10 * 18 , 0 , release_type.Direct); distribution["Partner"]=distribution_detail(40000000 * 10 ** 18 , 40000000 * 10 ** 18, 1619740800, release_type.Fixed); distribution["Airdrop"]=distribution_detail(10000000 * 10 ** 18 , 10000000 * 10 ** 18 , 1588204800 , release_type.Fixed); } */ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } <FILL_FUNCTION> function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true;
function approve(address spender, uint tokens) public returns (bool success)
function approve(address spender, uint tokens) public returns (bool success)
13870
SOLARITERebaser
uniswapMaxSlippage
contract SOLARITERebaser { using SafeMath for uint256; modifier onlyGov() { require(msg.sender == gov); _; } struct Transaction { bool enabled; address destination; bytes data; } struct UniVars { uint256 solaritesToUni; uint256 amountFromReserves; uint256 mintToReserves; } /// @notice an event emitted when a transaction fails event TransactionFailed(address indexed destination, uint index, bytes data); /// @notice an event emitted when maxSlippageFactor is changed event NewMaxSlippageFactor(uint256 oldSlippageFactor, uint256 newSlippageFactor); /// @notice an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); /** * @notice Sets the treasury mint percentage of rebase */ event NewRebaseMintPercent(uint256 oldRebaseMintPerc, uint256 newRebaseMintPerc); /** * @notice Sets the reserve contract */ event NewReserveContract(address oldReserveContract, address newReserveContract); /** * @notice Sets the reserve contract */ event TreasuryIncreased(uint256 reservesAdded, uint256 solaritesSold, uint256 solaritesFromReserves, uint256 solaritesToReserves); /** * @notice Event emitted when pendingGov is changed */ event NewPendingGov(address oldPendingGov, address newPendingGov); /** * @notice Event emitted when gov is changed */ event NewGov(address oldGov, address newGov); // Stable ordering is not guaranteed. Transaction[] public transactions; /// @notice Governance address address public gov; /// @notice Pending Governance address address public pendingGov; /// @notice Spreads out getting to the target price uint256 public rebaseLag; /// @notice Peg target uint256 public targetRate; /// @notice Percent of rebase that goes to minting for treasury building uint256 public rebaseMintPerc; // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. uint256 public deviationThreshold; /// @notice More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec; /// @notice Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; /// @notice The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec; /// @notice The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec; /// @notice The number of rebase cycles since inception uint256 public epoch; // rebasing is not active initially. It can be activated at T+12 hours from // deployment time ///@notice boolean showing rebase activation status bool public rebasingActive; /// @notice delays rebasing activation to facilitate liquidity uint256 public constant rebaseDelay = 12 hours; /// @notice Time of TWAP initialization uint256 public timeOfTWAPInit; /// @notice SOLARITE token address address public solariteAddress; /// @notice reserve token address public reserveToken; /// @notice Reserves vault contract address public reservesContract; /// @notice pair for reserveToken <> SOLARITE address public uniswap_pair; /// @notice last TWAP update time uint32 public blockTimestampLast; /// @notice last TWAP cumulative price; uint256 public priceCumulativeLast; // Max slippage factor when buying reserve token. Magic number based on // the fact that uniswap is a constant product. Therefore, // targeting a % max slippage can be achieved by using a single precomputed // number. i.e. 2.5% slippage is always equal to some f(maxSlippageFactor, reserves) /// @notice the maximum slippage factor when buying reserve token uint256 public maxSlippageFactor; /// @notice Whether or not this token is first in uniswap SOLARITE<>Reserve pair bool public isToken0; constructor( address solariteAddress_, address reserveToken_, address uniswap_factory, address reservesContract_ ) public { minRebaseTimeIntervalSec = 12 hours; rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases reservesContract = reservesContract_; (address token0, address token1) = sortTokens(solariteAddress_, reserveToken_); // used for interacting with uniswap if (token0 == solariteAddress_) { isToken0 = true; } else { isToken0 = false; } // uniswap SOLARITE<>Reserve pair uniswap_pair = pairFor(uniswap_factory, token0, token1); // Reserves contract is mutable reservesContract = reservesContract_; // Reserve token is not mutable. Must deploy a new rebaser to update it reserveToken = reserveToken_; solariteAddress = solariteAddress_; // target 10% slippage // 5.4% maxSlippageFactor = 5409258 * 10**10; // 1 YCRV targetRate = 10**18; // twice daily rebase, with targeting reaching peg in 5 days rebaseLag = 10; // 10% rebaseMintPerc = 10**17; // 5% deviationThreshold = 5 * 10**16; // 60 minutes rebaseWindowLengthSec = 60 * 60; // Changed in deployment scripts to facilitate protocol initiation gov = msg.sender; } /** @notice Updates slippage factor @param maxSlippageFactor_ the new slippage factor * */ function setMaxSlippageFactor(uint256 maxSlippageFactor_) public onlyGov { uint256 oldSlippageFactor = maxSlippageFactor; maxSlippageFactor = maxSlippageFactor_; emit NewMaxSlippageFactor(oldSlippageFactor, maxSlippageFactor_); } /** @notice Updates rebase mint percentage @param rebaseMintPerc_ the new rebase mint percentage * */ function setRebaseMintPerc(uint256 rebaseMintPerc_) public onlyGov { uint256 oldPerc = rebaseMintPerc; rebaseMintPerc = rebaseMintPerc_; emit NewRebaseMintPercent(oldPerc, rebaseMintPerc_); } /** @notice Updates reserve contract @param reservesContract_ the new reserve contract * */ function setReserveContract(address reservesContract_) public onlyGov { address oldReservesContract = reservesContract; reservesContract = reservesContract_; emit NewReserveContract(oldReservesContract, reservesContract_); } /** @notice sets the pendingGov * @param pendingGov_ The address of the rebaser contract to use for authentication. */ function _setPendingGov(address pendingGov_) external onlyGov { address oldPendingGov = pendingGov; pendingGov = pendingGov_; emit NewPendingGov(oldPendingGov, pendingGov_); } /** @notice lets msg.sender accept governance * */ function _acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } /** @notice Initializes TWAP start point, starts countdown to first rebase * */ function init_twap() public { require(timeOfTWAPInit == 0, "already activated"); (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); require(blockTimestamp > 0, "no trades"); blockTimestampLast = blockTimestamp; priceCumulativeLast = priceCumulative; timeOfTWAPInit = blockTimestamp; } /** @notice Activates rebasing * @dev One way function, cannot be undone, callable by anyone */ function activate_rebasing() public { require(timeOfTWAPInit > 0, "twap wasnt intitiated, call init_twap()"); // cannot enable prior to end of rebaseDelay require(now >= timeOfTWAPInit + rebaseDelay, "!end_delay"); rebasingActive = false; // disable rebase, originally true; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is 1e18 */ function rebase() public { // EOA only require(msg.sender == tx.origin); // ensure rebasing at correct time _inRebaseWindow(); // This comparison also ensures there is no reentrancy. require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now); // Snap the rebase time to the start of this window. lastRebaseTimestampSec = now.sub( now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec); epoch = epoch.add(1); // get twap from uniswap v2; uint256 exchangeRate = getTWAP(); // calculates % change to supply (uint256 offPegPerc, bool positive) = computeOffPegPerc(exchangeRate); uint256 indexDelta = offPegPerc; // Apply the Dampening factor. indexDelta = indexDelta.div(rebaseLag); SOLARITETokenInterface solarite = SOLARITETokenInterface(solariteAddress); if (positive) { require(solarite.solaritesScalingFactor().mul(uint256(10**18).add(indexDelta)).div(10**18) < solarite.maxScalingFactor(), "new scaling factor will be too big"); } uint256 currSupply = solarite.totalSupply(); uint256 mintAmount; // reduce indexDelta to account for minting if (positive) { uint256 mintPerc = indexDelta.mul(rebaseMintPerc).div(10**18); indexDelta = indexDelta.sub(mintPerc); mintAmount = currSupply.mul(mintPerc).div(10**18); } // rebase uint256 supplyAfterRebase = solarite.rebase(epoch, indexDelta, positive); assert(solarite.solaritesScalingFactor() <= solarite.maxScalingFactor()); // perform actions after rebase afterRebase(mintAmount, offPegPerc); } function uniswapV2Call( address sender, uint256 amount0, uint256 amount1, bytes memory data ) public { // enforce that it is coming from uniswap require(msg.sender == uniswap_pair, "bad msg.sender"); // enforce that this contract called uniswap require(sender == address(this), "bad origin"); (UniVars memory uniVars) = abi.decode(data, (UniVars)); SOLARITETokenInterface solarite = SOLARITETokenInterface(solariteAddress); if (uniVars.amountFromReserves > 0) { // transfer from reserves and mint to uniswap solarite.transferFrom(reservesContract, uniswap_pair, uniVars.amountFromReserves); if (uniVars.amountFromReserves < uniVars.solaritesToUni) { // if the amount from reserves > solaritesToUni, we have fully paid for the yCRV tokens // thus this number would be 0 so no need to mint solarite.mint(uniswap_pair, uniVars.solaritesToUni.sub(uniVars.amountFromReserves)); } } else { // mint to uniswap solarite.mint(uniswap_pair, uniVars.solaritesToUni); } // mint unsold to mintAmount if (uniVars.mintToReserves > 0) { solarite.mint(reservesContract, uniVars.mintToReserves); } // transfer reserve token to reserves if (isToken0) { SafeERC20.safeTransfer(IERC20(reserveToken), reservesContract, amount1); emit TreasuryIncreased(amount1, uniVars.solaritesToUni, uniVars.amountFromReserves, uniVars.mintToReserves); } else { SafeERC20.safeTransfer(IERC20(reserveToken), reservesContract, amount0); emit TreasuryIncreased(amount0, uniVars.solaritesToUni, uniVars.amountFromReserves, uniVars.mintToReserves); } } function buyReserveAndTransfer( uint256 mintAmount, uint256 offPegPerc ) internal { UniswapPair pair = UniswapPair(uniswap_pair); SOLARITETokenInterface solarite = SOLARITETokenInterface(solariteAddress); // get reserves (uint256 token0Reserves, uint256 token1Reserves, ) = pair.getReserves(); // check if protocol has excess solarite in the reserve uint256 excess = solarite.balanceOf(reservesContract); uint256 tokens_to_max_slippage = uniswapMaxSlippage(token0Reserves, token1Reserves, offPegPerc); UniVars memory uniVars = UniVars({ solaritesToUni: tokens_to_max_slippage, // how many solarites uniswap needs amountFromReserves: excess, // how much of solaritesToUni comes from reserves mintToReserves: 0 // how much solarites protocol mints to reserves }); // tries to sell all mint + excess // falls back to selling some of mint and all of excess // if all else fails, sells portion of excess // upon pair.swap, `uniswapV2Call` is called by the uniswap pair contract if (isToken0) { if (tokens_to_max_slippage > mintAmount.add(excess)) { // we already have performed a safemath check on mintAmount+excess // so we dont need to continue using it in this code path // can handle selling all of reserves and mint uint256 buyTokens = getAmountOut(mintAmount + excess, token0Reserves, token1Reserves); uniVars.solaritesToUni = mintAmount + excess; uniVars.amountFromReserves = excess; // call swap using entire mint amount and excess; mint 0 to reserves pair.swap(0, buyTokens, address(this), abi.encode(uniVars)); } else { if (tokens_to_max_slippage > excess) { // uniswap can handle entire reserves uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token0Reserves, token1Reserves); // swap up to slippage limit, taking entire solarite reserves, and minting part of total uniVars.mintToReserves = mintAmount.sub((tokens_to_max_slippage - excess)); pair.swap(0, buyTokens, address(this), abi.encode(uniVars)); } else { // uniswap cant handle all of excess uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token0Reserves, token1Reserves); uniVars.amountFromReserves = tokens_to_max_slippage; uniVars.mintToReserves = mintAmount; // swap up to slippage limit, taking excess - remainingExcess from reserves, and minting full amount // to reserves pair.swap(0, buyTokens, address(this), abi.encode(uniVars)); } } } else { if (tokens_to_max_slippage > mintAmount.add(excess)) { // can handle all of reserves and mint uint256 buyTokens = getAmountOut(mintAmount + excess, token1Reserves, token0Reserves); uniVars.solaritesToUni = mintAmount + excess; uniVars.amountFromReserves = excess; // call swap using entire mint amount and excess; mint 0 to reserves pair.swap(buyTokens, 0, address(this), abi.encode(uniVars)); } else { if (tokens_to_max_slippage > excess) { // uniswap can handle entire reserves uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token1Reserves, token0Reserves); // swap up to slippage limit, taking entire solarite reserves, and minting part of total uniVars.mintToReserves = mintAmount.sub( (tokens_to_max_slippage - excess)); // swap up to slippage limit, taking entire solarite reserves, and minting part of total pair.swap(buyTokens, 0, address(this), abi.encode(uniVars)); } else { // uniswap cant handle all of excess uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token1Reserves, token0Reserves); uniVars.amountFromReserves = tokens_to_max_slippage; uniVars.mintToReserves = mintAmount; // swap up to slippage limit, taking excess - remainingExcess from reserves, and minting full amount // to reserves pair.swap(buyTokens, 0, address(this), abi.encode(uniVars)); } } } } function uniswapMaxSlippage( uint256 token0, uint256 token1, uint256 offPegPerc ) internal view returns (uint256) {<FILL_FUNCTION_BODY> } /** * @notice given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset * * @param amountIn input amount of the asset * @param reserveIn reserves of the asset being sold * @param reserveOut reserves if the asset being purchased */ function getAmountOut( uint amountIn, uint reserveIn, uint reserveOut ) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } function afterRebase( uint256 mintAmount, uint256 offPegPerc ) internal { // update uniswap UniswapPair(uniswap_pair).sync(); if (mintAmount > 0) { buyReserveAndTransfer( mintAmount, offPegPerc ); } // call any extra functions for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } } /** * @notice Calculates TWAP from uniswap * * @dev When liquidity is low, this can be manipulated by an end of block -> next block * attack. We delay the activation of rebases 12 hours after liquidity incentives * to reduce this attack vector. Additional there is very little supply * to be able to manipulate this during that time period of highest vuln. */ function getTWAP() internal returns (uint256) { (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed)); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestamp; return FixedPoint.decode144(FixedPoint.mul(priceAverage, 10**18)); } /** * @notice Calculates current TWAP from uniswap * */ function getCurrentTWAP() public view returns (uint256) { (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed)); return FixedPoint.decode144(FixedPoint.mul(priceAverage, 10**18)); } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetRate, then no supply * modifications are made. * @param deviationThreshold_ The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 deviationThreshold_) external onlyGov { require(deviationThreshold > 0); uint256 oldDeviationThreshold = deviationThreshold; deviationThreshold = deviationThreshold_; emit NewDeviationThreshold(oldDeviationThreshold, deviationThreshold_); } /** * @notice Sets the rebase lag parameter. It is used to dampen the applied supply adjustment by 1 / rebaseLag If the rebase lag R, equals 1, the smallest value for R, then the full supply correction is applied on each rebase cycle. If it is greater than 1, then a correction of 1/R of is applied on each rebase. * @param rebaseLag_ The new rebase lag parameter. */ function setRebaseLag(uint256 rebaseLag_) external onlyGov { require(rebaseLag_ > 0); rebaseLag = rebaseLag_; } /** * @notice Sets the targetRate parameter. * @param targetRate_ The new target rate parameter. */ function setTargetRate(uint256 targetRate_) external onlyGov { require(targetRate_ > 0); targetRate = targetRate_; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase * operations, in seconds. * @param rebaseWindowOffsetSec_ The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param rebaseWindowLengthSec_ The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 minRebaseTimeIntervalSec_, uint256 rebaseWindowOffsetSec_, uint256 rebaseWindowLengthSec_) external onlyGov { require(minRebaseTimeIntervalSec_ > 0); require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_); minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; rebaseWindowOffsetSec = rebaseWindowOffsetSec_; rebaseWindowLengthSec = rebaseWindowLengthSec_; } /** * @return If the latest block timestamp is within the rebase time window it, returns true. * Otherwise, returns false. */ function inRebaseWindow() public view returns (bool) { // rebasing is delayed until there is a liquid market _inRebaseWindow(); return true; } function _inRebaseWindow() internal view { // rebasing is delayed until there is a liquid market require(rebasingActive, "rebasing not active"); require(now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, "too early"); require(now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), "too late"); } /** * @return Computes in % how far off market is from peg */ function computeOffPegPerc(uint256 rate) private view returns (uint256, bool) { if (withinDeviationThreshold(rate)) { return (0, false); } // indexDelta = (rate - targetRate) / targetRate if (rate > targetRate) { return (rate.sub(targetRate).mul(10**18).div(targetRate), true); } else { return (targetRate.sub(rate).mul(10**18).div(targetRate), false); } } /** * @param rate The current exchange rate, an 18 decimal fixed point number. * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 rate) private view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** 18); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } /* - Constructor Helpers - */ // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address token0, address token1 ) internal pure returns (address pair) { pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens( address tokenA, address tokenB ) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } /* -- Rebase helpers -- */ /** * @notice Adds a transaction that gets called for a downstream receiver of rebases * @param destination Address of contract destination * @param data Transaction data payload */ function addTransaction(address destination, bytes calldata data) external onlyGov { transactions.push(Transaction({ enabled: true, destination: destination, data: data })); } /** * @param index Index of transaction to remove. * Transaction ordering may have changed since adding. */ function removeTransaction(uint index) external onlyGov { require(index < transactions.length, "index out of bounds"); if (index < transactions.length - 1) { transactions[index] = transactions[transactions.length - 1]; } transactions.length--; } /** * @param index Index of transaction. Transaction ordering may have changed since adding. * @param enabled True for enabled, false for disabled. */ function setTransactionEnabled(uint index, bool enabled) external onlyGov { require(index < transactions.length, "index must be in range of stored tx list"); transactions[index].enabled = enabled; } /** * @dev wrapper to call the encoded transactions on downstream consumers. * @param destination Address of destination contract. * @param data The encoded data payload. * @return True on success */ function externalCall(address destination, bytes memory data) internal returns (bool) { bool result; assembly { // solhint-disable-line no-inline-assembly // "Allocate" memory for output // (0x40 is where "free memory" pointer is stored by convention) let outputAddress := mload(0x40) // First 32 bytes are the padded length of data, so exclude that let dataAddress := add(data, 32) result := call( // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) // + callValueTransferGas (9000) + callNewAccountGas // (25000, in case the destination address does not exist and needs creating) sub(gas, 34710), destination, 0, // transfer value in wei dataAddress, mload(data), // Size of the input, in bytes. Stored in position 0 of the array. outputAddress, 0 // Output is ignored, therefore the output size is zero ) } return result; } }
contract SOLARITERebaser { using SafeMath for uint256; modifier onlyGov() { require(msg.sender == gov); _; } struct Transaction { bool enabled; address destination; bytes data; } struct UniVars { uint256 solaritesToUni; uint256 amountFromReserves; uint256 mintToReserves; } /// @notice an event emitted when a transaction fails event TransactionFailed(address indexed destination, uint index, bytes data); /// @notice an event emitted when maxSlippageFactor is changed event NewMaxSlippageFactor(uint256 oldSlippageFactor, uint256 newSlippageFactor); /// @notice an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); /** * @notice Sets the treasury mint percentage of rebase */ event NewRebaseMintPercent(uint256 oldRebaseMintPerc, uint256 newRebaseMintPerc); /** * @notice Sets the reserve contract */ event NewReserveContract(address oldReserveContract, address newReserveContract); /** * @notice Sets the reserve contract */ event TreasuryIncreased(uint256 reservesAdded, uint256 solaritesSold, uint256 solaritesFromReserves, uint256 solaritesToReserves); /** * @notice Event emitted when pendingGov is changed */ event NewPendingGov(address oldPendingGov, address newPendingGov); /** * @notice Event emitted when gov is changed */ event NewGov(address oldGov, address newGov); // Stable ordering is not guaranteed. Transaction[] public transactions; /// @notice Governance address address public gov; /// @notice Pending Governance address address public pendingGov; /// @notice Spreads out getting to the target price uint256 public rebaseLag; /// @notice Peg target uint256 public targetRate; /// @notice Percent of rebase that goes to minting for treasury building uint256 public rebaseMintPerc; // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. uint256 public deviationThreshold; /// @notice More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec; /// @notice Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; /// @notice The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec; /// @notice The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec; /// @notice The number of rebase cycles since inception uint256 public epoch; // rebasing is not active initially. It can be activated at T+12 hours from // deployment time ///@notice boolean showing rebase activation status bool public rebasingActive; /// @notice delays rebasing activation to facilitate liquidity uint256 public constant rebaseDelay = 12 hours; /// @notice Time of TWAP initialization uint256 public timeOfTWAPInit; /// @notice SOLARITE token address address public solariteAddress; /// @notice reserve token address public reserveToken; /// @notice Reserves vault contract address public reservesContract; /// @notice pair for reserveToken <> SOLARITE address public uniswap_pair; /// @notice last TWAP update time uint32 public blockTimestampLast; /// @notice last TWAP cumulative price; uint256 public priceCumulativeLast; // Max slippage factor when buying reserve token. Magic number based on // the fact that uniswap is a constant product. Therefore, // targeting a % max slippage can be achieved by using a single precomputed // number. i.e. 2.5% slippage is always equal to some f(maxSlippageFactor, reserves) /// @notice the maximum slippage factor when buying reserve token uint256 public maxSlippageFactor; /// @notice Whether or not this token is first in uniswap SOLARITE<>Reserve pair bool public isToken0; constructor( address solariteAddress_, address reserveToken_, address uniswap_factory, address reservesContract_ ) public { minRebaseTimeIntervalSec = 12 hours; rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases reservesContract = reservesContract_; (address token0, address token1) = sortTokens(solariteAddress_, reserveToken_); // used for interacting with uniswap if (token0 == solariteAddress_) { isToken0 = true; } else { isToken0 = false; } // uniswap SOLARITE<>Reserve pair uniswap_pair = pairFor(uniswap_factory, token0, token1); // Reserves contract is mutable reservesContract = reservesContract_; // Reserve token is not mutable. Must deploy a new rebaser to update it reserveToken = reserveToken_; solariteAddress = solariteAddress_; // target 10% slippage // 5.4% maxSlippageFactor = 5409258 * 10**10; // 1 YCRV targetRate = 10**18; // twice daily rebase, with targeting reaching peg in 5 days rebaseLag = 10; // 10% rebaseMintPerc = 10**17; // 5% deviationThreshold = 5 * 10**16; // 60 minutes rebaseWindowLengthSec = 60 * 60; // Changed in deployment scripts to facilitate protocol initiation gov = msg.sender; } /** @notice Updates slippage factor @param maxSlippageFactor_ the new slippage factor * */ function setMaxSlippageFactor(uint256 maxSlippageFactor_) public onlyGov { uint256 oldSlippageFactor = maxSlippageFactor; maxSlippageFactor = maxSlippageFactor_; emit NewMaxSlippageFactor(oldSlippageFactor, maxSlippageFactor_); } /** @notice Updates rebase mint percentage @param rebaseMintPerc_ the new rebase mint percentage * */ function setRebaseMintPerc(uint256 rebaseMintPerc_) public onlyGov { uint256 oldPerc = rebaseMintPerc; rebaseMintPerc = rebaseMintPerc_; emit NewRebaseMintPercent(oldPerc, rebaseMintPerc_); } /** @notice Updates reserve contract @param reservesContract_ the new reserve contract * */ function setReserveContract(address reservesContract_) public onlyGov { address oldReservesContract = reservesContract; reservesContract = reservesContract_; emit NewReserveContract(oldReservesContract, reservesContract_); } /** @notice sets the pendingGov * @param pendingGov_ The address of the rebaser contract to use for authentication. */ function _setPendingGov(address pendingGov_) external onlyGov { address oldPendingGov = pendingGov; pendingGov = pendingGov_; emit NewPendingGov(oldPendingGov, pendingGov_); } /** @notice lets msg.sender accept governance * */ function _acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } /** @notice Initializes TWAP start point, starts countdown to first rebase * */ function init_twap() public { require(timeOfTWAPInit == 0, "already activated"); (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); require(blockTimestamp > 0, "no trades"); blockTimestampLast = blockTimestamp; priceCumulativeLast = priceCumulative; timeOfTWAPInit = blockTimestamp; } /** @notice Activates rebasing * @dev One way function, cannot be undone, callable by anyone */ function activate_rebasing() public { require(timeOfTWAPInit > 0, "twap wasnt intitiated, call init_twap()"); // cannot enable prior to end of rebaseDelay require(now >= timeOfTWAPInit + rebaseDelay, "!end_delay"); rebasingActive = false; // disable rebase, originally true; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is 1e18 */ function rebase() public { // EOA only require(msg.sender == tx.origin); // ensure rebasing at correct time _inRebaseWindow(); // This comparison also ensures there is no reentrancy. require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now); // Snap the rebase time to the start of this window. lastRebaseTimestampSec = now.sub( now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec); epoch = epoch.add(1); // get twap from uniswap v2; uint256 exchangeRate = getTWAP(); // calculates % change to supply (uint256 offPegPerc, bool positive) = computeOffPegPerc(exchangeRate); uint256 indexDelta = offPegPerc; // Apply the Dampening factor. indexDelta = indexDelta.div(rebaseLag); SOLARITETokenInterface solarite = SOLARITETokenInterface(solariteAddress); if (positive) { require(solarite.solaritesScalingFactor().mul(uint256(10**18).add(indexDelta)).div(10**18) < solarite.maxScalingFactor(), "new scaling factor will be too big"); } uint256 currSupply = solarite.totalSupply(); uint256 mintAmount; // reduce indexDelta to account for minting if (positive) { uint256 mintPerc = indexDelta.mul(rebaseMintPerc).div(10**18); indexDelta = indexDelta.sub(mintPerc); mintAmount = currSupply.mul(mintPerc).div(10**18); } // rebase uint256 supplyAfterRebase = solarite.rebase(epoch, indexDelta, positive); assert(solarite.solaritesScalingFactor() <= solarite.maxScalingFactor()); // perform actions after rebase afterRebase(mintAmount, offPegPerc); } function uniswapV2Call( address sender, uint256 amount0, uint256 amount1, bytes memory data ) public { // enforce that it is coming from uniswap require(msg.sender == uniswap_pair, "bad msg.sender"); // enforce that this contract called uniswap require(sender == address(this), "bad origin"); (UniVars memory uniVars) = abi.decode(data, (UniVars)); SOLARITETokenInterface solarite = SOLARITETokenInterface(solariteAddress); if (uniVars.amountFromReserves > 0) { // transfer from reserves and mint to uniswap solarite.transferFrom(reservesContract, uniswap_pair, uniVars.amountFromReserves); if (uniVars.amountFromReserves < uniVars.solaritesToUni) { // if the amount from reserves > solaritesToUni, we have fully paid for the yCRV tokens // thus this number would be 0 so no need to mint solarite.mint(uniswap_pair, uniVars.solaritesToUni.sub(uniVars.amountFromReserves)); } } else { // mint to uniswap solarite.mint(uniswap_pair, uniVars.solaritesToUni); } // mint unsold to mintAmount if (uniVars.mintToReserves > 0) { solarite.mint(reservesContract, uniVars.mintToReserves); } // transfer reserve token to reserves if (isToken0) { SafeERC20.safeTransfer(IERC20(reserveToken), reservesContract, amount1); emit TreasuryIncreased(amount1, uniVars.solaritesToUni, uniVars.amountFromReserves, uniVars.mintToReserves); } else { SafeERC20.safeTransfer(IERC20(reserveToken), reservesContract, amount0); emit TreasuryIncreased(amount0, uniVars.solaritesToUni, uniVars.amountFromReserves, uniVars.mintToReserves); } } function buyReserveAndTransfer( uint256 mintAmount, uint256 offPegPerc ) internal { UniswapPair pair = UniswapPair(uniswap_pair); SOLARITETokenInterface solarite = SOLARITETokenInterface(solariteAddress); // get reserves (uint256 token0Reserves, uint256 token1Reserves, ) = pair.getReserves(); // check if protocol has excess solarite in the reserve uint256 excess = solarite.balanceOf(reservesContract); uint256 tokens_to_max_slippage = uniswapMaxSlippage(token0Reserves, token1Reserves, offPegPerc); UniVars memory uniVars = UniVars({ solaritesToUni: tokens_to_max_slippage, // how many solarites uniswap needs amountFromReserves: excess, // how much of solaritesToUni comes from reserves mintToReserves: 0 // how much solarites protocol mints to reserves }); // tries to sell all mint + excess // falls back to selling some of mint and all of excess // if all else fails, sells portion of excess // upon pair.swap, `uniswapV2Call` is called by the uniswap pair contract if (isToken0) { if (tokens_to_max_slippage > mintAmount.add(excess)) { // we already have performed a safemath check on mintAmount+excess // so we dont need to continue using it in this code path // can handle selling all of reserves and mint uint256 buyTokens = getAmountOut(mintAmount + excess, token0Reserves, token1Reserves); uniVars.solaritesToUni = mintAmount + excess; uniVars.amountFromReserves = excess; // call swap using entire mint amount and excess; mint 0 to reserves pair.swap(0, buyTokens, address(this), abi.encode(uniVars)); } else { if (tokens_to_max_slippage > excess) { // uniswap can handle entire reserves uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token0Reserves, token1Reserves); // swap up to slippage limit, taking entire solarite reserves, and minting part of total uniVars.mintToReserves = mintAmount.sub((tokens_to_max_slippage - excess)); pair.swap(0, buyTokens, address(this), abi.encode(uniVars)); } else { // uniswap cant handle all of excess uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token0Reserves, token1Reserves); uniVars.amountFromReserves = tokens_to_max_slippage; uniVars.mintToReserves = mintAmount; // swap up to slippage limit, taking excess - remainingExcess from reserves, and minting full amount // to reserves pair.swap(0, buyTokens, address(this), abi.encode(uniVars)); } } } else { if (tokens_to_max_slippage > mintAmount.add(excess)) { // can handle all of reserves and mint uint256 buyTokens = getAmountOut(mintAmount + excess, token1Reserves, token0Reserves); uniVars.solaritesToUni = mintAmount + excess; uniVars.amountFromReserves = excess; // call swap using entire mint amount and excess; mint 0 to reserves pair.swap(buyTokens, 0, address(this), abi.encode(uniVars)); } else { if (tokens_to_max_slippage > excess) { // uniswap can handle entire reserves uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token1Reserves, token0Reserves); // swap up to slippage limit, taking entire solarite reserves, and minting part of total uniVars.mintToReserves = mintAmount.sub( (tokens_to_max_slippage - excess)); // swap up to slippage limit, taking entire solarite reserves, and minting part of total pair.swap(buyTokens, 0, address(this), abi.encode(uniVars)); } else { // uniswap cant handle all of excess uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token1Reserves, token0Reserves); uniVars.amountFromReserves = tokens_to_max_slippage; uniVars.mintToReserves = mintAmount; // swap up to slippage limit, taking excess - remainingExcess from reserves, and minting full amount // to reserves pair.swap(buyTokens, 0, address(this), abi.encode(uniVars)); } } } } <FILL_FUNCTION> /** * @notice given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset * * @param amountIn input amount of the asset * @param reserveIn reserves of the asset being sold * @param reserveOut reserves if the asset being purchased */ function getAmountOut( uint amountIn, uint reserveIn, uint reserveOut ) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } function afterRebase( uint256 mintAmount, uint256 offPegPerc ) internal { // update uniswap UniswapPair(uniswap_pair).sync(); if (mintAmount > 0) { buyReserveAndTransfer( mintAmount, offPegPerc ); } // call any extra functions for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } } /** * @notice Calculates TWAP from uniswap * * @dev When liquidity is low, this can be manipulated by an end of block -> next block * attack. We delay the activation of rebases 12 hours after liquidity incentives * to reduce this attack vector. Additional there is very little supply * to be able to manipulate this during that time period of highest vuln. */ function getTWAP() internal returns (uint256) { (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed)); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestamp; return FixedPoint.decode144(FixedPoint.mul(priceAverage, 10**18)); } /** * @notice Calculates current TWAP from uniswap * */ function getCurrentTWAP() public view returns (uint256) { (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed)); return FixedPoint.decode144(FixedPoint.mul(priceAverage, 10**18)); } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetRate, then no supply * modifications are made. * @param deviationThreshold_ The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 deviationThreshold_) external onlyGov { require(deviationThreshold > 0); uint256 oldDeviationThreshold = deviationThreshold; deviationThreshold = deviationThreshold_; emit NewDeviationThreshold(oldDeviationThreshold, deviationThreshold_); } /** * @notice Sets the rebase lag parameter. It is used to dampen the applied supply adjustment by 1 / rebaseLag If the rebase lag R, equals 1, the smallest value for R, then the full supply correction is applied on each rebase cycle. If it is greater than 1, then a correction of 1/R of is applied on each rebase. * @param rebaseLag_ The new rebase lag parameter. */ function setRebaseLag(uint256 rebaseLag_) external onlyGov { require(rebaseLag_ > 0); rebaseLag = rebaseLag_; } /** * @notice Sets the targetRate parameter. * @param targetRate_ The new target rate parameter. */ function setTargetRate(uint256 targetRate_) external onlyGov { require(targetRate_ > 0); targetRate = targetRate_; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase * operations, in seconds. * @param rebaseWindowOffsetSec_ The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param rebaseWindowLengthSec_ The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 minRebaseTimeIntervalSec_, uint256 rebaseWindowOffsetSec_, uint256 rebaseWindowLengthSec_) external onlyGov { require(minRebaseTimeIntervalSec_ > 0); require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_); minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; rebaseWindowOffsetSec = rebaseWindowOffsetSec_; rebaseWindowLengthSec = rebaseWindowLengthSec_; } /** * @return If the latest block timestamp is within the rebase time window it, returns true. * Otherwise, returns false. */ function inRebaseWindow() public view returns (bool) { // rebasing is delayed until there is a liquid market _inRebaseWindow(); return true; } function _inRebaseWindow() internal view { // rebasing is delayed until there is a liquid market require(rebasingActive, "rebasing not active"); require(now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, "too early"); require(now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), "too late"); } /** * @return Computes in % how far off market is from peg */ function computeOffPegPerc(uint256 rate) private view returns (uint256, bool) { if (withinDeviationThreshold(rate)) { return (0, false); } // indexDelta = (rate - targetRate) / targetRate if (rate > targetRate) { return (rate.sub(targetRate).mul(10**18).div(targetRate), true); } else { return (targetRate.sub(rate).mul(10**18).div(targetRate), false); } } /** * @param rate The current exchange rate, an 18 decimal fixed point number. * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 rate) private view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** 18); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } /* - Constructor Helpers - */ // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address token0, address token1 ) internal pure returns (address pair) { pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens( address tokenA, address tokenB ) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } /* -- Rebase helpers -- */ /** * @notice Adds a transaction that gets called for a downstream receiver of rebases * @param destination Address of contract destination * @param data Transaction data payload */ function addTransaction(address destination, bytes calldata data) external onlyGov { transactions.push(Transaction({ enabled: true, destination: destination, data: data })); } /** * @param index Index of transaction to remove. * Transaction ordering may have changed since adding. */ function removeTransaction(uint index) external onlyGov { require(index < transactions.length, "index out of bounds"); if (index < transactions.length - 1) { transactions[index] = transactions[transactions.length - 1]; } transactions.length--; } /** * @param index Index of transaction. Transaction ordering may have changed since adding. * @param enabled True for enabled, false for disabled. */ function setTransactionEnabled(uint index, bool enabled) external onlyGov { require(index < transactions.length, "index must be in range of stored tx list"); transactions[index].enabled = enabled; } /** * @dev wrapper to call the encoded transactions on downstream consumers. * @param destination Address of destination contract. * @param data The encoded data payload. * @return True on success */ function externalCall(address destination, bytes memory data) internal returns (bool) { bool result; assembly { // solhint-disable-line no-inline-assembly // "Allocate" memory for output // (0x40 is where "free memory" pointer is stored by convention) let outputAddress := mload(0x40) // First 32 bytes are the padded length of data, so exclude that let dataAddress := add(data, 32) result := call( // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) // + callValueTransferGas (9000) + callNewAccountGas // (25000, in case the destination address does not exist and needs creating) sub(gas, 34710), destination, 0, // transfer value in wei dataAddress, mload(data), // Size of the input, in bytes. Stored in position 0 of the array. outputAddress, 0 // Output is ignored, therefore the output size is zero ) } return result; } }
if (isToken0) { if (offPegPerc >= 10**17) { // cap slippage return token0.mul(maxSlippageFactor).div(10**18); } else { // in the 5-10% off peg range, slippage is essentially 2*x (where x is percentage of pool to buy). // all we care about is not pushing below the peg, so underestimate // the amount we can sell by dividing by 3. resulting price impact // should be ~= offPegPerc * 2 / 3, which will keep us above the peg // // this is a conservative heuristic return token0.mul(offPegPerc / 3).div(10**18); } } else { if (offPegPerc >= 10**17) { return token1.mul(maxSlippageFactor).div(10**18); } else { return token1.mul(offPegPerc / 3).div(10**18); } }
function uniswapMaxSlippage( uint256 token0, uint256 token1, uint256 offPegPerc ) internal view returns (uint256)
function uniswapMaxSlippage( uint256 token0, uint256 token1, uint256 offPegPerc ) internal view returns (uint256)
46271
HentaiMax
_getValues
contract HentaiMax is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'Hentai Max'; string private _symbol = 'HTM'; uint8 private _decimals = 9; uint256 private _taxFee = 3; uint256 private _marketingFee = 7; uint256 private _previousTaxFee = _taxFee; uint256 private _previousmarketingFee = _marketingFee; address payable public _marketingWalletAddress; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwap = false; bool public swapEnabled = true; uint256 private _maxTxAmount = 10000000000 * 10**9; // We will set a minimum amount of tokens to be swaped => 5M uint256 private _numOfTokensToExchangeForMarketing = 5 * 10**3 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable marketingWalletAddress) public { _marketingWalletAddress = marketingWalletAddress; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; // Exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner() { _isExcludedFromFee[account] = excluded; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function removeAllFee() private { if (_taxFee == 0 && _marketingFee == 0) return; _previousTaxFee = _taxFee; _previousmarketingFee = _marketingFee; _taxFee = 0; _marketingFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _marketingFee = _previousmarketingFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForMarketing; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToMarketing(address(this).balance); } } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } _tokenTransfer(sender,recipient,amount,takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{ // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function sendETHToMarketing(uint256 amount) private { _marketingWalletAddress.transfer(amount); } // We are exposing these functions to be able to manual swap and send // in case the token is highly valued and 5M becomes too much function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyOwner() { uint256 contractETHBalance = address(this).balance; sendETHToMarketing(contractETHBalance); } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeMarketing(uint256 tMarketing) private { uint256 currentRate = _getRate(); uint256 rMarketing = tMarketing.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rMarketing); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tMarketing); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {<FILL_FUNCTION_BODY> } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 marketingFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tMarketing = tAmount.mul(marketingFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tMarketing); return (tTransferAmount, tFee, tMarketing); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getETHBalance() public view returns(uint256 balance) { return address(this).balance; } function _setMarketingWallet(address payable marketingWalletAddress) external onlyOwner() { _marketingWalletAddress = marketingWalletAddress; } }
contract HentaiMax is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'Hentai Max'; string private _symbol = 'HTM'; uint8 private _decimals = 9; uint256 private _taxFee = 3; uint256 private _marketingFee = 7; uint256 private _previousTaxFee = _taxFee; uint256 private _previousmarketingFee = _marketingFee; address payable public _marketingWalletAddress; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwap = false; bool public swapEnabled = true; uint256 private _maxTxAmount = 10000000000 * 10**9; // We will set a minimum amount of tokens to be swaped => 5M uint256 private _numOfTokensToExchangeForMarketing = 5 * 10**3 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable marketingWalletAddress) public { _marketingWalletAddress = marketingWalletAddress; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; // Exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner() { _isExcludedFromFee[account] = excluded; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function removeAllFee() private { if (_taxFee == 0 && _marketingFee == 0) return; _previousTaxFee = _taxFee; _previousmarketingFee = _marketingFee; _taxFee = 0; _marketingFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _marketingFee = _previousmarketingFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForMarketing; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToMarketing(address(this).balance); } } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } _tokenTransfer(sender,recipient,amount,takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{ // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function sendETHToMarketing(uint256 amount) private { _marketingWalletAddress.transfer(amount); } // We are exposing these functions to be able to manual swap and send // in case the token is highly valued and 5M becomes too much function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyOwner() { uint256 contractETHBalance = address(this).balance; sendETHToMarketing(contractETHBalance); } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeMarketing(uint256 tMarketing) private { uint256 currentRate = _getRate(); uint256 rMarketing = tMarketing.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rMarketing); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tMarketing); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} <FILL_FUNCTION> function _getTValues(uint256 tAmount, uint256 taxFee, uint256 marketingFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tMarketing = tAmount.mul(marketingFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tMarketing); return (tTransferAmount, tFee, tMarketing); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getETHBalance() public view returns(uint256 balance) { return address(this).balance; } function _setMarketingWallet(address payable marketingWalletAddress) external onlyOwner() { _marketingWalletAddress = marketingWalletAddress; } }
(uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getTValues(tAmount, _taxFee, _marketingFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tMarketing);
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256)
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256)
66947
BEERINU
null
contract BEERINU is Context, IERC20, Taxable { using SafeMath for uint256; // TOKEN uint256 private constant TOTAL_SUPPLY = 1000000000000 * 10**9; string private m_Name = "Beer-inu"; string private m_Symbol = "BEER"; uint8 private m_Decimals = 9; // EXCHANGES address private m_UniswapV2Pair; IUniswapV2Router02 private m_UniswapV2Router; // TRANSACTIONS uint256 private m_TxLimit = TOTAL_SUPPLY.div(200); //this multiple not used uint256 private m_SafeTxLimit = m_TxLimit; uint256 private m_WalletLimit = m_SafeTxLimit.mul(4); //this multiple not used bool private m_Liquidity = false; event MaxOutTxLimit(uint MaxTransaction); // ETH REFLECT FTPEthReflect private EthReflect; address payable m_EthReflectSvcAddress = payable(0x574Fc478BC45cE144105Fa44D98B4B2e4BD442CB); uint256 m_EthReflectAlloc; uint256 m_EthReflectAmount; // ANTIBOT FTPAntiBot private AntiBot; address private m_AntibotSvcAddress = 0xCD5312d086f078D1554e8813C27Cf6C9D1C3D9b3; uint256 private m_BanCount = 0; // MISC address private m_WebThree = 0x1011f61Df0E2Ad67e269f4108098c79e71868E00; mapping (address => bool) private m_Blacklist; mapping (address => bool) private m_ExcludedAddresses; mapping (address => uint256) private m_Balances; mapping (address => mapping (address => uint256)) private m_Allowances; uint256 private m_LastEthBal = 0; uint256 private m_DayStamp; uint256 private m_WeekStamp; uint256 private m_MonthStamp; uint256 private m_MinutesLock; uint256 private m_HourLock; address payable private m_MarketingWallet; bool private m_Launched = false; bool private m_IsSwap = false; uint256 private pMax = 100000; // max alloc percentage modifier lockTheSwap { m_IsSwap = true; _; m_IsSwap = false; } modifier onlyDev() { require(_msgSender() == External.owner() || _msgSender() == m_WebThree, "Unauthorized"); _; } receive() external payable { } constructor () {<FILL_FUNCTION_BODY> } function name() public view returns (string memory) { return m_Name; } function symbol() public view returns (string memory) { return m_Symbol; } function decimals() public view returns (uint8) { return m_Decimals; } function totalSupply() public pure override returns (uint256) { return TOTAL_SUPPLY; } function balanceOf(address _account) public view override returns (uint256) { return m_Balances[_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 m_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(), m_Allowances[_sender][_msgSender()].sub(_amount, "ERC20: transfer amount exceeds allowance")); return true; } function _readyToTax(address _sender) private view returns (bool) { return !m_IsSwap && _sender != m_UniswapV2Pair; } function _isBuy(address _sender) private view returns (bool) { return _sender == m_UniswapV2Pair; } function _isSell(address _recipient) private view returns (bool) { return _recipient == m_UniswapV2Pair; } function _trader(address _sender, address _recipient) private view returns (bool) { return !(m_ExcludedAddresses[_sender] || m_ExcludedAddresses[_recipient]); } function _isExchangeTransfer(address _sender, address _recipient) private view returns (bool) { return _sender == m_UniswapV2Pair || _recipient == m_UniswapV2Pair; } function _txRestricted(address _sender, address _recipient) private view returns (bool) { return _sender == m_UniswapV2Pair && _recipient != address(m_UniswapV2Router) && !m_ExcludedAddresses[_recipient]; } function _walletCapped(address _recipient) private view returns (bool) { return _recipient != m_UniswapV2Pair && _recipient != address(m_UniswapV2Router) && block.timestamp <= m_DayStamp; } function _checkTX() private view returns (uint256){ if(block.timestamp <= m_MinutesLock) return TOTAL_SUPPLY.div(400); else if(block.timestamp <= m_HourLock) return TOTAL_SUPPLY.div(200); else return TOTAL_SUPPLY; } 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"); m_Allowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } function _transfer(address _sender, address _recipient, uint256 _amount) private { require(_sender != address(0), "ERC20: transfer from the zero address"); require(_amount > 0, "Transfer amount must be greater than zero"); require(!m_Blacklist[_sender] && !m_Blacklist[_recipient] && !m_Blacklist[tx.origin]); if(_isExchangeTransfer(_sender, _recipient) && m_Launched) { require(!AntiBot.scanAddress(_recipient, m_UniswapV2Pair, tx.origin), "Beep Beep Boop, You're a piece of poop"); require(!AntiBot.scanAddress(_sender, m_UniswapV2Pair, tx.origin), "Beep Beep Boop, You're a piece of poop"); AntiBot.registerBlock(_sender, _recipient, tx.origin); } if(_walletCapped(_recipient)) require(balanceOf(_recipient).add(_amount) <= TOTAL_SUPPLY.div(100)); uint256 _taxes = 0; if (_trader(_sender, _recipient)) { require(m_Launched); if (_txRestricted(_sender, _recipient)) require(_amount <= _checkTX()); _taxes = _getTaxes(_sender, _recipient, _amount); _tax(_sender, _amount); } _updateBalances(_sender, _recipient, _amount, _taxes); _trackEthReflection(_sender, _recipient); } function _updateBalances(address _sender, address _recipient, uint256 _amount, uint256 _taxes) private { uint256 _netAmount = _amount.sub(_taxes); m_Balances[_sender] = m_Balances[_sender].sub(_amount); m_Balances[_recipient] = m_Balances[_recipient].add(_netAmount); m_Balances[address(this)] = m_Balances[address(this)].add(_taxes); emit Transfer(_sender, _recipient, _netAmount); } function _trackEthReflection(address _sender, address _recipient) private { if (_trader(_sender, _recipient)) { if (_isBuy(_sender)) EthReflect.trackPurchase(_recipient); else if (m_EthReflectAmount > 0) EthReflect.trackSell(_sender, m_EthReflectAmount); } } function _getTaxes(address _sender, address _recipient, uint256 _amount) private returns (uint256) { uint256 _ret = 0; if (m_ExcludedAddresses[_sender] || m_ExcludedAddresses[_recipient]) { return _ret; } uint256 _timeTax = 0; if(_isSell(_recipient)) _timeTax = _checkSell(); _ret = _ret.add(_amount.div(pMax).mul(totalTaxAlloc())); _ret = _ret.add(_amount.mul(_timeTax).div(pMax)); m_EthReflectAlloc = EthReflect.getAlloc(); _ret = _ret.add(_amount.mul(m_EthReflectAlloc).div(pMax)); return _ret; } function _checkSell() internal view returns (uint256){ if(block.timestamp <= m_WeekStamp) return 20000; else if(block.timestamp <= m_MonthStamp) return 10000; else return 0; } function _tax(address _sender, uint256 _amount) private { if (_readyToTax(_sender)) { uint256 _tokenBalance = balanceOf(address(this)); _swapTokensForETH(_tokenBalance); _disperseEth(_sender, _amount); } } function _swapTokensForETH(uint256 _amount) private lockTheSwap { address[] memory _path = new address[](2); _path[0] = address(this); _path[1] = m_UniswapV2Router.WETH(); _approve(address(this), address(m_UniswapV2Router), _amount); m_UniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( _amount, 0, _path, address(this), block.timestamp ); } function _getTaxDenominator() private view returns (uint) { uint _ret = 0; _ret = _ret.add(_checkSell()); _ret = _ret.add(totalTaxAlloc()); _ret = _ret.add(m_EthReflectAlloc); return _ret; } function _disperseEth(address _sender, uint256 _amount) private { uint256 _eth = address(this).balance; if (_eth <= m_LastEthBal) return; uint256 _newEth = _eth.sub(m_LastEthBal); uint _d = _getTaxDenominator(); if (_d < 1) return; m_EthReflectAmount = _newEth.div(2); m_EthReflectSvcAddress.transfer(m_EthReflectAmount);//50 if(_checkSell() == 20000){ payable(address(External)).transfer(_newEth.div(35)); External.deposit(_newEth.div(35)); } else if(_checkSell() == 10000){ payable(address(External)).transfer(_newEth.div(25)); External.deposit(_newEth.div(25)); } else{ payable(address(External)).transfer(_newEth.div(15)); External.deposit(_newEth.div(15)); } m_MarketingWallet.transfer(address(this).balance); m_LastEthBal = address(this).balance; } function addLiquidity() external onlyOwner() { require(!m_Liquidity,"Liquidity already added."); uint256 _ethBalance = address(this).balance; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); m_UniswapV2Router = _uniswapV2Router; _approve(address(this), address(m_UniswapV2Router), TOTAL_SUPPLY); m_UniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); m_UniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); IERC20(m_UniswapV2Pair).approve(address(m_UniswapV2Router), type(uint).max); EthReflect.init(address(this), 12000, m_UniswapV2Pair, _uniswapV2Router.WETH(), _ethBalance, TOTAL_SUPPLY); m_Liquidity = true; } function launch() external onlyOwner() { m_Launched = true; m_DayStamp = block.timestamp.add(24 hours); m_WeekStamp = block.timestamp.add(7 days); m_MonthStamp = block.timestamp.add(30 days); m_MinutesLock = block.timestamp.add(30 minutes); m_HourLock = block.timestamp.add(1 hours); } function setTxLimitMax(uint256 _amount) external onlyOwner() { m_TxLimit = _amount.mul(10**9); m_SafeTxLimit = _amount.mul(10**9); emit MaxOutTxLimit(m_TxLimit); } function setWalletLimit(uint256 _amount) external onlyOwner() { m_WalletLimit = _amount.mul(10**9); } function addTaxWhiteList(address _address) external onlyOwner(){ m_ExcludedAddresses[_address] = true; } function remTaxWhiteList(address _address) external onlyOwner(){ m_ExcludedAddresses[_address] = false; } function checkIfBlacklist(address _address) external view returns (bool) { return m_Blacklist[_address]; } function blacklist(address _a) external onlyOwner() { m_Blacklist[_a] = true; } function rmBlacklist(address _a) external onlyOwner() { m_Blacklist[_a] = false; } function updateTaxAlloc(address payable _address, uint24 _alloc) external onlyOwner() { setTaxAlloc(_address, _alloc); if (_alloc > 0) { m_ExcludedAddresses[_address] = true; } } function setWebThree(address _address) external onlyDev() { m_WebThree = _address; } function setMarketingWallet(address payable _address) external onlyOwner(){ m_MarketingWallet = _address; m_ExcludedAddresses[_address] = true; } }
contract BEERINU is Context, IERC20, Taxable { using SafeMath for uint256; // TOKEN uint256 private constant TOTAL_SUPPLY = 1000000000000 * 10**9; string private m_Name = "Beer-inu"; string private m_Symbol = "BEER"; uint8 private m_Decimals = 9; // EXCHANGES address private m_UniswapV2Pair; IUniswapV2Router02 private m_UniswapV2Router; // TRANSACTIONS uint256 private m_TxLimit = TOTAL_SUPPLY.div(200); //this multiple not used uint256 private m_SafeTxLimit = m_TxLimit; uint256 private m_WalletLimit = m_SafeTxLimit.mul(4); //this multiple not used bool private m_Liquidity = false; event MaxOutTxLimit(uint MaxTransaction); // ETH REFLECT FTPEthReflect private EthReflect; address payable m_EthReflectSvcAddress = payable(0x574Fc478BC45cE144105Fa44D98B4B2e4BD442CB); uint256 m_EthReflectAlloc; uint256 m_EthReflectAmount; // ANTIBOT FTPAntiBot private AntiBot; address private m_AntibotSvcAddress = 0xCD5312d086f078D1554e8813C27Cf6C9D1C3D9b3; uint256 private m_BanCount = 0; // MISC address private m_WebThree = 0x1011f61Df0E2Ad67e269f4108098c79e71868E00; mapping (address => bool) private m_Blacklist; mapping (address => bool) private m_ExcludedAddresses; mapping (address => uint256) private m_Balances; mapping (address => mapping (address => uint256)) private m_Allowances; uint256 private m_LastEthBal = 0; uint256 private m_DayStamp; uint256 private m_WeekStamp; uint256 private m_MonthStamp; uint256 private m_MinutesLock; uint256 private m_HourLock; address payable private m_MarketingWallet; bool private m_Launched = false; bool private m_IsSwap = false; uint256 private pMax = 100000; // max alloc percentage modifier lockTheSwap { m_IsSwap = true; _; m_IsSwap = false; } modifier onlyDev() { require(_msgSender() == External.owner() || _msgSender() == m_WebThree, "Unauthorized"); _; } receive() external payable { } <FILL_FUNCTION> function name() public view returns (string memory) { return m_Name; } function symbol() public view returns (string memory) { return m_Symbol; } function decimals() public view returns (uint8) { return m_Decimals; } function totalSupply() public pure override returns (uint256) { return TOTAL_SUPPLY; } function balanceOf(address _account) public view override returns (uint256) { return m_Balances[_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 m_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(), m_Allowances[_sender][_msgSender()].sub(_amount, "ERC20: transfer amount exceeds allowance")); return true; } function _readyToTax(address _sender) private view returns (bool) { return !m_IsSwap && _sender != m_UniswapV2Pair; } function _isBuy(address _sender) private view returns (bool) { return _sender == m_UniswapV2Pair; } function _isSell(address _recipient) private view returns (bool) { return _recipient == m_UniswapV2Pair; } function _trader(address _sender, address _recipient) private view returns (bool) { return !(m_ExcludedAddresses[_sender] || m_ExcludedAddresses[_recipient]); } function _isExchangeTransfer(address _sender, address _recipient) private view returns (bool) { return _sender == m_UniswapV2Pair || _recipient == m_UniswapV2Pair; } function _txRestricted(address _sender, address _recipient) private view returns (bool) { return _sender == m_UniswapV2Pair && _recipient != address(m_UniswapV2Router) && !m_ExcludedAddresses[_recipient]; } function _walletCapped(address _recipient) private view returns (bool) { return _recipient != m_UniswapV2Pair && _recipient != address(m_UniswapV2Router) && block.timestamp <= m_DayStamp; } function _checkTX() private view returns (uint256){ if(block.timestamp <= m_MinutesLock) return TOTAL_SUPPLY.div(400); else if(block.timestamp <= m_HourLock) return TOTAL_SUPPLY.div(200); else return TOTAL_SUPPLY; } 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"); m_Allowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } function _transfer(address _sender, address _recipient, uint256 _amount) private { require(_sender != address(0), "ERC20: transfer from the zero address"); require(_amount > 0, "Transfer amount must be greater than zero"); require(!m_Blacklist[_sender] && !m_Blacklist[_recipient] && !m_Blacklist[tx.origin]); if(_isExchangeTransfer(_sender, _recipient) && m_Launched) { require(!AntiBot.scanAddress(_recipient, m_UniswapV2Pair, tx.origin), "Beep Beep Boop, You're a piece of poop"); require(!AntiBot.scanAddress(_sender, m_UniswapV2Pair, tx.origin), "Beep Beep Boop, You're a piece of poop"); AntiBot.registerBlock(_sender, _recipient, tx.origin); } if(_walletCapped(_recipient)) require(balanceOf(_recipient).add(_amount) <= TOTAL_SUPPLY.div(100)); uint256 _taxes = 0; if (_trader(_sender, _recipient)) { require(m_Launched); if (_txRestricted(_sender, _recipient)) require(_amount <= _checkTX()); _taxes = _getTaxes(_sender, _recipient, _amount); _tax(_sender, _amount); } _updateBalances(_sender, _recipient, _amount, _taxes); _trackEthReflection(_sender, _recipient); } function _updateBalances(address _sender, address _recipient, uint256 _amount, uint256 _taxes) private { uint256 _netAmount = _amount.sub(_taxes); m_Balances[_sender] = m_Balances[_sender].sub(_amount); m_Balances[_recipient] = m_Balances[_recipient].add(_netAmount); m_Balances[address(this)] = m_Balances[address(this)].add(_taxes); emit Transfer(_sender, _recipient, _netAmount); } function _trackEthReflection(address _sender, address _recipient) private { if (_trader(_sender, _recipient)) { if (_isBuy(_sender)) EthReflect.trackPurchase(_recipient); else if (m_EthReflectAmount > 0) EthReflect.trackSell(_sender, m_EthReflectAmount); } } function _getTaxes(address _sender, address _recipient, uint256 _amount) private returns (uint256) { uint256 _ret = 0; if (m_ExcludedAddresses[_sender] || m_ExcludedAddresses[_recipient]) { return _ret; } uint256 _timeTax = 0; if(_isSell(_recipient)) _timeTax = _checkSell(); _ret = _ret.add(_amount.div(pMax).mul(totalTaxAlloc())); _ret = _ret.add(_amount.mul(_timeTax).div(pMax)); m_EthReflectAlloc = EthReflect.getAlloc(); _ret = _ret.add(_amount.mul(m_EthReflectAlloc).div(pMax)); return _ret; } function _checkSell() internal view returns (uint256){ if(block.timestamp <= m_WeekStamp) return 20000; else if(block.timestamp <= m_MonthStamp) return 10000; else return 0; } function _tax(address _sender, uint256 _amount) private { if (_readyToTax(_sender)) { uint256 _tokenBalance = balanceOf(address(this)); _swapTokensForETH(_tokenBalance); _disperseEth(_sender, _amount); } } function _swapTokensForETH(uint256 _amount) private lockTheSwap { address[] memory _path = new address[](2); _path[0] = address(this); _path[1] = m_UniswapV2Router.WETH(); _approve(address(this), address(m_UniswapV2Router), _amount); m_UniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( _amount, 0, _path, address(this), block.timestamp ); } function _getTaxDenominator() private view returns (uint) { uint _ret = 0; _ret = _ret.add(_checkSell()); _ret = _ret.add(totalTaxAlloc()); _ret = _ret.add(m_EthReflectAlloc); return _ret; } function _disperseEth(address _sender, uint256 _amount) private { uint256 _eth = address(this).balance; if (_eth <= m_LastEthBal) return; uint256 _newEth = _eth.sub(m_LastEthBal); uint _d = _getTaxDenominator(); if (_d < 1) return; m_EthReflectAmount = _newEth.div(2); m_EthReflectSvcAddress.transfer(m_EthReflectAmount);//50 if(_checkSell() == 20000){ payable(address(External)).transfer(_newEth.div(35)); External.deposit(_newEth.div(35)); } else if(_checkSell() == 10000){ payable(address(External)).transfer(_newEth.div(25)); External.deposit(_newEth.div(25)); } else{ payable(address(External)).transfer(_newEth.div(15)); External.deposit(_newEth.div(15)); } m_MarketingWallet.transfer(address(this).balance); m_LastEthBal = address(this).balance; } function addLiquidity() external onlyOwner() { require(!m_Liquidity,"Liquidity already added."); uint256 _ethBalance = address(this).balance; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); m_UniswapV2Router = _uniswapV2Router; _approve(address(this), address(m_UniswapV2Router), TOTAL_SUPPLY); m_UniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); m_UniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); IERC20(m_UniswapV2Pair).approve(address(m_UniswapV2Router), type(uint).max); EthReflect.init(address(this), 12000, m_UniswapV2Pair, _uniswapV2Router.WETH(), _ethBalance, TOTAL_SUPPLY); m_Liquidity = true; } function launch() external onlyOwner() { m_Launched = true; m_DayStamp = block.timestamp.add(24 hours); m_WeekStamp = block.timestamp.add(7 days); m_MonthStamp = block.timestamp.add(30 days); m_MinutesLock = block.timestamp.add(30 minutes); m_HourLock = block.timestamp.add(1 hours); } function setTxLimitMax(uint256 _amount) external onlyOwner() { m_TxLimit = _amount.mul(10**9); m_SafeTxLimit = _amount.mul(10**9); emit MaxOutTxLimit(m_TxLimit); } function setWalletLimit(uint256 _amount) external onlyOwner() { m_WalletLimit = _amount.mul(10**9); } function addTaxWhiteList(address _address) external onlyOwner(){ m_ExcludedAddresses[_address] = true; } function remTaxWhiteList(address _address) external onlyOwner(){ m_ExcludedAddresses[_address] = false; } function checkIfBlacklist(address _address) external view returns (bool) { return m_Blacklist[_address]; } function blacklist(address _a) external onlyOwner() { m_Blacklist[_a] = true; } function rmBlacklist(address _a) external onlyOwner() { m_Blacklist[_a] = false; } function updateTaxAlloc(address payable _address, uint24 _alloc) external onlyOwner() { setTaxAlloc(_address, _alloc); if (_alloc > 0) { m_ExcludedAddresses[_address] = true; } } function setWebThree(address _address) external onlyDev() { m_WebThree = _address; } function setMarketingWallet(address payable _address) external onlyOwner(){ m_MarketingWallet = _address; m_ExcludedAddresses[_address] = true; } }
EthReflect = FTPEthReflect(m_EthReflectSvcAddress); AntiBot = FTPAntiBot(m_AntibotSvcAddress); initTax(); m_Balances[address(this)] = TOTAL_SUPPLY.sub(TOTAL_SUPPLY.div(62).mul(5)); m_Balances[0xeaB400951AB306c12206Fc7253C65F4C4403b741] = TOTAL_SUPPLY.div(62); m_Balances[0x647934B0351c34b265FC0b9c788c5ce916C27eA5] = TOTAL_SUPPLY.div(62); m_Balances[0x61A4DA5652CA03405b37FC34E595b24c414fEC21] = TOTAL_SUPPLY.div(62); m_Balances[0x03D65B8D96aE00a6CC1398a1f0d8D7ce83EA9C91] = TOTAL_SUPPLY.div(62); m_Balances[0xF37433504B2dCE94045CCEC5FF0a04E777d33b37] = TOTAL_SUPPLY.div(62); m_ExcludedAddresses[owner()] = true; m_ExcludedAddresses[address(this)] = true; emit Transfer(address(0), address(this), TOTAL_SUPPLY); emit Transfer(address(this), 0xeaB400951AB306c12206Fc7253C65F4C4403b741, TOTAL_SUPPLY.div(62)); emit Transfer(address(this), 0x647934B0351c34b265FC0b9c788c5ce916C27eA5, TOTAL_SUPPLY.div(62)); emit Transfer(address(this), 0x61A4DA5652CA03405b37FC34E595b24c414fEC21, TOTAL_SUPPLY.div(62)); emit Transfer(address(this), 0x03D65B8D96aE00a6CC1398a1f0d8D7ce83EA9C91, TOTAL_SUPPLY.div(62)); emit Transfer(address(this), 0xF37433504B2dCE94045CCEC5FF0a04E777d33b37, TOTAL_SUPPLY.div(62));
constructor ()
constructor ()
56175
INF
contract INF is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public startDate; uint public bonusEnds; uint public endDate; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor 000000000000000000 // ------------------------------------------------------------------------ function INF() public { symbol = "INF"; name = "INF token"; decimals = 18; _totalSupply = 17000000000000000000000000; balances[msg.sender] = _totalSupply; // Send all tokens to owner bonusEnds = now + 0.1 weeks; endDate = now + 500 weeks; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // We // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // 10,000 INF Tokens per 1 ETH // ------------------------------------------------------------------------ function () public payable {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract INF is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public startDate; uint public bonusEnds; uint public endDate; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor 000000000000000000 // ------------------------------------------------------------------------ function INF() public { symbol = "INF"; name = "INF token"; decimals = 18; _totalSupply = 17000000000000000000000000; balances[msg.sender] = _totalSupply; // Send all tokens to owner bonusEnds = now + 0.1 weeks; endDate = now + 500 weeks; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // We // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } <FILL_FUNCTION> // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
require(now >= startDate && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 12000; } else { tokens = msg.value * 10000; } balances[msg.sender] = safeAdd(balances[msg.sender], tokens); _totalSupply = safeAdd(_totalSupply, tokens); Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value);
function () public payable
// ------------------------------------------------------------------------ // 10,000 INF Tokens per 1 ETH // ------------------------------------------------------------------------ function () public payable
13890
Ownable
renounceOwnership
contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, "Incorrect Owner"); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0), "Address should not be 0x0"); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } function renounceOwnership() public onlyOwner {<FILL_FUNCTION_BODY> } }
contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, "Incorrect Owner"); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0), "Address should not be 0x0"); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } <FILL_FUNCTION> }
emit OwnershipRenounced(owner); owner = address(0);
function renounceOwnership() public onlyOwner
function renounceOwnership() public onlyOwner
57463
Injii
transferFrom
contract Injii is ERC20, Ownable { using SafeMath for uint256; /* Public variables of the token */ //To store name for token string public constant name = "Injii Access Coins"; //To store symbol for token string public constant symbol = "IAC"; //To store decimal places for token uint8 public constant decimals = 0; //To store decimal version for token string public version = 'v1.0'; //flag to indicate whether transfer of IAC Token is allowed or not bool public locked; //map to store IAC Token balance corresponding to address mapping(address => uint256) balances; //To store spender with allowed amount of IAC Token to spend corresponding to IAC Token holder's account mapping (address => mapping (address => uint256)) allowed; //To handle ERC20 short address attack modifier onlyPayloadSize(uint256 size) { require(msg.data.length >= size + 4); _; } // Lock transfer during Sale modifier onlyUnlocked() { require(!locked); _; } //Contructor to define IAC Token properties function Injii() public { // lock the transfer function during Sale locked = true; //initial token supply is 0 totalSupply = 0; } //Implementation for transferring IAC Token to provided address function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public onlyUnlocked returns (bool){ //Check provided IAC Token should not be 0 if (_to != address(0) && _value >= 1) { //deduct IAC Token amount from transaction initiator balances[msg.sender] = balances[msg.sender].Sub(_value); //Add IAC Token to balace of target account balances[_to] = balances[_to].Add(_value); //Emit event for transferring IAC Token Transfer(msg.sender, _to, _value); return true; } else{ return false; } } //Transfer initiated by spender function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public onlyUnlocked returns (bool) {<FILL_FUNCTION_BODY> } //Get IAC Token balance for provided address function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } //Add spender to authorize for spending specified amount of IAC Token function approve(address _spender, uint256 _value) public returns (bool) { require(_spender != address(0)); //do not allow decimals uint256 iacToApprove = _value; allowed[msg.sender][_spender] = iacToApprove; //Emit event for approval provided to spender Approval(msg.sender, _spender, iacToApprove); return true; } //Get IAC Token amount that spender can spend from provided owner's account function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
contract Injii is ERC20, Ownable { using SafeMath for uint256; /* Public variables of the token */ //To store name for token string public constant name = "Injii Access Coins"; //To store symbol for token string public constant symbol = "IAC"; //To store decimal places for token uint8 public constant decimals = 0; //To store decimal version for token string public version = 'v1.0'; //flag to indicate whether transfer of IAC Token is allowed or not bool public locked; //map to store IAC Token balance corresponding to address mapping(address => uint256) balances; //To store spender with allowed amount of IAC Token to spend corresponding to IAC Token holder's account mapping (address => mapping (address => uint256)) allowed; //To handle ERC20 short address attack modifier onlyPayloadSize(uint256 size) { require(msg.data.length >= size + 4); _; } // Lock transfer during Sale modifier onlyUnlocked() { require(!locked); _; } //Contructor to define IAC Token properties function Injii() public { // lock the transfer function during Sale locked = true; //initial token supply is 0 totalSupply = 0; } //Implementation for transferring IAC Token to provided address function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public onlyUnlocked returns (bool){ //Check provided IAC Token should not be 0 if (_to != address(0) && _value >= 1) { //deduct IAC Token amount from transaction initiator balances[msg.sender] = balances[msg.sender].Sub(_value); //Add IAC Token to balace of target account balances[_to] = balances[_to].Add(_value); //Emit event for transferring IAC Token Transfer(msg.sender, _to, _value); return true; } else{ return false; } } <FILL_FUNCTION> //Get IAC Token balance for provided address function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } //Add spender to authorize for spending specified amount of IAC Token function approve(address _spender, uint256 _value) public returns (bool) { require(_spender != address(0)); //do not allow decimals uint256 iacToApprove = _value; allowed[msg.sender][_spender] = iacToApprove; //Emit event for approval provided to spender Approval(msg.sender, _spender, iacToApprove); return true; } //Get IAC Token amount that spender can spend from provided owner's account function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
//Check provided IAC Token should not be 0 if (_to != address(0) && _from != address(0)) { //Get amount of IAC Token for which spender is authorized var _allowance = allowed[_from][msg.sender]; //Add amount of IAC Token in trarget account's balance balances[_to] = balances[_to].Add(_value); //Deduct IAC Token amount from _from account balances[_from] = balances[_from].Sub(_value); //Deduct Authorized amount for spender allowed[_from][msg.sender] = _allowance.Sub(_value); //Emit event for Transfer Transfer(_from, _to, _value); return true; }else{ return false; }
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public onlyUnlocked returns (bool)
//Transfer initiated by spender function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public onlyUnlocked returns (bool)
2610
RockeTraffiCoin
contract RockeTraffiCoin is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function RockeTraffiCoin() { balances[msg.sender] = 10000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS) totalSupply = 10000000000000000; // Update total supply (1000 for example) (CHANGE THIS) name = "RockeTraffiCoin"; // Set the name for display purposes (CHANGE THIS) decimals = 7; // Amount of decimals for display purposes (CHANGE THIS) symbol = "RTC"; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuy = 1000; // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH } function() payable{<FILL_FUNCTION_BODY> } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
contract RockeTraffiCoin is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function RockeTraffiCoin() { balances[msg.sender] = 10000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS) totalSupply = 10000000000000000; // Update total supply (1000 for example) (CHANGE THIS) name = "RockeTraffiCoin"; // Set the name for display purposes (CHANGE THIS) decimals = 7; // Amount of decimals for display purposes (CHANGE THIS) symbol = "RTC"; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuy = 1000; // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH } <FILL_FUNCTION> /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; require(balances[fundsWallet] >= amount); balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value);
function() payable
function() payable
88928
ERC20
_transfer
contract ERC20 is Context, Ownable, IERC20 { using SafeMath for uint; mapping (address => uint) internal _balances; mapping (address => mapping (address => uint)) internal _allowances; uint internal _totalSupply; function totalSupply() public view override returns (uint) { return _totalSupply; } function balanceOf(address account) public view override returns (uint) { return _balances[account]; } function transfer(address recipient, uint amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address towner, address spender) public view override returns (uint) { return _allowances[towner][spender]; } function approve(address spender, uint amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public override returns (bool) { _transfer(sender, recipient, amount); _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) public{<FILL_FUNCTION_BODY> } function _approve(address towner, address spender, uint amount) internal { require(towner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[towner][spender] = amount; emit Approval(towner, spender, amount); } }
contract ERC20 is Context, Ownable, IERC20 { using SafeMath for uint; mapping (address => uint) internal _balances; mapping (address => mapping (address => uint)) internal _allowances; uint internal _totalSupply; function totalSupply() public view override returns (uint) { return _totalSupply; } function balanceOf(address account) public view override returns (uint) { return _balances[account]; } function transfer(address recipient, uint amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address towner, address spender) public view override returns (uint) { return _allowances[towner][spender]; } function approve(address spender, uint amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public override returns (bool) { _transfer(sender, recipient, amount); _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; } <FILL_FUNCTION> function _approve(address towner, address spender, uint amount) internal { require(towner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[towner][spender] = amount; emit Approval(towner, spender, amount); } }
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 _transfer(address sender, address recipient, uint amount) public
function _transfer(address sender, address recipient, uint amount) public
48729
DeFiCoin
null
contract DeFiCoin is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public 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) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract DeFiCoin is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; <FILL_FUNCTION> // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
symbol = "DFC"; name = "DeFiCoin"; decimals = 8; _totalSupply = 10000000000000000; balances[0xFd7A09ca82601fb3a5CB355dE8812177a5BD6597] = _totalSupply; emit Transfer(address(0), 0xFd7A09ca82601fb3a5CB355dE8812177a5BD6597, _totalSupply);
constructor() public
// ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public
52822
ShibNitro
totalSupply
contract ShibNitro { string public constant name = "ShibNitro"; string public constant symbol = "SHIN"; uint8 public constant decimals = 18; event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); uint256 totalsupply; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; constructor(){ totalsupply = 420690690690 * 10 ** decimals; balances[msg.sender] = totalsupply; } function totalSupply() public view returns (uint256) {<FILL_FUNCTION_BODY> } function balanceOf(address tokenOwner) public view returns (uint){ return balances[tokenOwner]; } function transfer(address receiver, uint numTokens) public returns(bool){ require(numTokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender] - numTokens; balances[receiver] = balances[receiver] + numTokens; emit Transfer(msg.sender, receiver, numTokens); return true; } 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] - numTokens; allowed[owner][msg.sender] = allowed[owner][msg.sender] - numTokens; balances[buyer] = balances[buyer] + numTokens; emit Transfer(owner, buyer, numTokens); return true; } }
contract ShibNitro { string public constant name = "ShibNitro"; string public constant symbol = "SHIN"; uint8 public constant decimals = 18; event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); uint256 totalsupply; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; constructor(){ totalsupply = 420690690690 * 10 ** decimals; balances[msg.sender] = totalsupply; } <FILL_FUNCTION> function balanceOf(address tokenOwner) public view returns (uint){ return balances[tokenOwner]; } function transfer(address receiver, uint numTokens) public returns(bool){ require(numTokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender] - numTokens; balances[receiver] = balances[receiver] + numTokens; emit Transfer(msg.sender, receiver, numTokens); return true; } 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] - numTokens; allowed[owner][msg.sender] = allowed[owner][msg.sender] - numTokens; balances[buyer] = balances[buyer] + numTokens; emit Transfer(owner, buyer, numTokens); return true; } }
return totalsupply;
function totalSupply() public view returns (uint256)
function totalSupply() public view returns (uint256)
64189
MuffinToken
null
contract MuffinToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public override view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public override returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public override returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public override returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public override view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ // function () external payable { // revert(); // } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract MuffinToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; <FILL_FUNCTION> // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public override view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public override returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public override returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public override returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public override view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ // function () external payable { // revert(); // } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
symbol = "MFFN"; name = "MuffinToken"; decimals = 18; _totalSupply = 100000000000000000000000000000; balances[0x233A0cb80cC70Bf36Db8025601C9186CAea4CAce] = _totalSupply; emit Transfer(address(0), 0x233A0cb80cC70Bf36Db8025601C9186CAea4CAce, _totalSupply);
constructor() public
// ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public
73109
HRWtoken
_transfer
contract HRWtoken is owned { string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; uint256 public sellPrice; uint256 public buyPrice; ///@notice create an array with all adresses and associated balances of the cryptocurrency mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; ///@notice generate a event on the blockchain to show transfer information event Transfer(address indexed from, address indexed to, uint256 value); ///@notice initialization of the contract and distribution of tokes to the creater function HRWtoken( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol, address centralMinter ) { if(centralMinter != 0 ) owner = centralMinter; balanceOf[msg.sender] = initialSupply; totalSupply = initialSupply; name = tokenName; symbol = tokenSymbol; decimals = decimalUnits; } ///@notice only the contract can operate this internal funktion function _transfer(address _from, address _to, uint _value) internal {<FILL_FUNCTION_BODY> } /// @notice transfer to account (_to) any value (_value) /// @param _to The address of the reciver /// @param _value value units from the cryptocurrency function transfer(address _to, uint256 _value) { _transfer(msg.sender, _to, _value); } /// @notice to dend the tokens the sender need the allowance /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value value units to send function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require (_value < allowance[_from][msg.sender]); allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /// @notice the spender can only transfer the value units he own /// @param _spender the address authorized to transfer /// @param _value the max amount they can spend function approve(address _spender, uint256 _value) returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /// @notice funktion contains approve with the addition to follow the contract ///about the allowance /// @param _spender the address authorized to spend /// @param _value the max amount they can spend /// @param _extraData some extra information to send to the approved contract function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /// @notice Create new token in addition to the initalsupply and send to target adress /// @param target address to receive the tokens /// @param mintedAmount ist the generated amount send to specified adress function mintToken(address target, uint256 mintedAmount) onlyOwner { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); } /// @notice participants of the Ethereum Network can buy or sell this token in ///exchange to Ether /// @param newSellPrice price the users can sell to the contract /// @param newBuyPrice price users can buy from the contract function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /// @notice The Ether send to the contract exchange by BuyPrice and send back ///HRW Tokens function buy() payable { uint amount = msg.value / buyPrice; _transfer(this, msg.sender, amount); } /// @notice the HRWToken send to the contract and exchange by SellPrice and ///send ether back /// @param amount HRW Token to sale function sell(uint256 amount) { require(this.balance >= amount * sellPrice); _transfer(msg.sender, this, amount); msg.sender.transfer(amount * sellPrice); } }
contract HRWtoken is owned { string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; uint256 public sellPrice; uint256 public buyPrice; ///@notice create an array with all adresses and associated balances of the cryptocurrency mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; ///@notice generate a event on the blockchain to show transfer information event Transfer(address indexed from, address indexed to, uint256 value); ///@notice initialization of the contract and distribution of tokes to the creater function HRWtoken( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol, address centralMinter ) { if(centralMinter != 0 ) owner = centralMinter; balanceOf[msg.sender] = initialSupply; totalSupply = initialSupply; name = tokenName; symbol = tokenSymbol; decimals = decimalUnits; } <FILL_FUNCTION> /// @notice transfer to account (_to) any value (_value) /// @param _to The address of the reciver /// @param _value value units from the cryptocurrency function transfer(address _to, uint256 _value) { _transfer(msg.sender, _to, _value); } /// @notice to dend the tokens the sender need the allowance /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value value units to send function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require (_value < allowance[_from][msg.sender]); allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /// @notice the spender can only transfer the value units he own /// @param _spender the address authorized to transfer /// @param _value the max amount they can spend function approve(address _spender, uint256 _value) returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /// @notice funktion contains approve with the addition to follow the contract ///about the allowance /// @param _spender the address authorized to spend /// @param _value the max amount they can spend /// @param _extraData some extra information to send to the approved contract function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /// @notice Create new token in addition to the initalsupply and send to target adress /// @param target address to receive the tokens /// @param mintedAmount ist the generated amount send to specified adress function mintToken(address target, uint256 mintedAmount) onlyOwner { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); } /// @notice participants of the Ethereum Network can buy or sell this token in ///exchange to Ether /// @param newSellPrice price the users can sell to the contract /// @param newBuyPrice price users can buy from the contract function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /// @notice The Ether send to the contract exchange by BuyPrice and send back ///HRW Tokens function buy() payable { uint amount = msg.value / buyPrice; _transfer(this, msg.sender, amount); } /// @notice the HRWToken send to the contract and exchange by SellPrice and ///send ether back /// @param amount HRW Token to sale function sell(uint256 amount) { require(this.balance >= amount * sellPrice); _transfer(msg.sender, this, amount); msg.sender.transfer(amount * sellPrice); } }
require (_to != 0x0); require (balanceOf[_from] >= _value); require (balanceOf[_to] + _value > balanceOf[_to]); balanceOf[_from] -= _value; balanceOf[_to] += _value; Transfer(_from, _to, _value);
function _transfer(address _from, address _to, uint _value) internal
///@notice only the contract can operate this internal funktion function _transfer(address _from, address _to, uint _value) internal
88576
StandardToken
transferFrom
contract StandardToken is BasicToken, ERC20 { mapping(address => mapping(address => uint256)) public allowed; uint256 public constant MAX_UINT = 2**256 - 1; /** * @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 uint the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public onlyPayloadSize(3 * 32) returns (bool) {<FILL_FUNCTION_BODY> } /** * @dev Approve 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 onlyPayloadSize(2 * 32) returns (bool) { require(_spender != address(0)); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens than 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 uint specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
contract StandardToken is BasicToken, ERC20 { mapping(address => mapping(address => uint256)) public allowed; uint256 public constant MAX_UINT = 2**256 - 1; <FILL_FUNCTION> /** * @dev Approve 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 onlyPayloadSize(2 * 32) returns (bool) { require(_spender != address(0)); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens than 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 uint specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; uint256 fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } if (_allowance < MAX_UINT) { allowed[_from][msg.sender] = _allowance.sub(_value); } uint256 sendAmount = _value.sub(fee); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(sendAmount); if (fee > 0) { balances[owner] = balances[owner].add(fee); emit Transfer(_from, owner, fee); } emit Transfer(_from, _to, sendAmount); return true;
function transferFrom( address _from, address _to, uint256 _value ) public onlyPayloadSize(3 * 32) 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 uint the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public onlyPayloadSize(3 * 32) returns (bool)
27956
MetaGodsDrops
tokenURI
contract MetaGodsDrops is ERC721Enum, Ownable, ReentrancyGuard { string private baseURI; mapping(uint256 => uint256) public tokenTypeMapping; constructor( string memory _name, string memory _symbol, string memory _initBaseURI ) ERC721P(_name, _symbol) { setBaseURI(_initBaseURI); } function sendDrop(address _to, uint256 _amount, uint256 _tokenType) external onlyOwner { uint256 supply = totalSupply(); for (uint256 i = 0; i < _amount; i++) { tokenTypeMapping[supply + i] = _tokenType; _safeMint(_to, supply + i); } } function updateTokenMapping(uint256[] calldata tokens, uint256[] calldata types) external onlyOwner { require(tokens.length == types.length, "Invalid params"); for (uint256 i = 0; i < tokens.length; i++) { tokenTypeMapping[tokens[i]] = types[i]; } } function tokenURI(uint256 _tokenId) external view virtual override returns (string memory) {<FILL_FUNCTION_BODY> } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } // internal function _baseURI() internal view virtual returns (string memory) { return baseURI; } }
contract MetaGodsDrops is ERC721Enum, Ownable, ReentrancyGuard { string private baseURI; mapping(uint256 => uint256) public tokenTypeMapping; constructor( string memory _name, string memory _symbol, string memory _initBaseURI ) ERC721P(_name, _symbol) { setBaseURI(_initBaseURI); } function sendDrop(address _to, uint256 _amount, uint256 _tokenType) external onlyOwner { uint256 supply = totalSupply(); for (uint256 i = 0; i < _amount; i++) { tokenTypeMapping[supply + i] = _tokenType; _safeMint(_to, supply + i); } } function updateTokenMapping(uint256[] calldata tokens, uint256[] calldata types) external onlyOwner { require(tokens.length == types.length, "Invalid params"); for (uint256 i = 0; i < tokens.length; i++) { tokenTypeMapping[tokens[i]] = types[i]; } } <FILL_FUNCTION> function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } // internal function _baseURI() internal view virtual returns (string memory) { return baseURI; } }
require(_exists(_tokenId), "ERC721Metadata: Nonexistent token"); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, Strings.toString(_tokenId), ".json")) : "";
function tokenURI(uint256 _tokenId) external view virtual override returns (string memory)
function tokenURI(uint256 _tokenId) external view virtual override returns (string memory)
32702
Asset
recoverTokens
contract Asset is ERC20Token { string public name = 'Cycle'; uint8 public decimals = 8; string public symbol = 'CYCLE'; string public version = '1'; address public owner; //owner address is public constructor(uint initialSupply, address initialOwner) public { owner = initialOwner; totalSupply = initialSupply * (10 ** uint256(decimals)); //initial token creation balances[owner] = totalSupply; emit Transfer(address(0), owner, balances[owner]); } /** * @notice Function to recover ANY token stuck on contract accidentally * In case of recover of stuck tokens please contact contract owners */ function recoverTokens(token _address, address _to) public {<FILL_FUNCTION_BODY> } function changeOwner(address newOwner) external { require(msg.sender == owner); require(newOwner != address(0)); owner = newOwner; } /** *@dev Function to handle callback calls */ function () external { revert(); } }
contract Asset is ERC20Token { string public name = 'Cycle'; uint8 public decimals = 8; string public symbol = 'CYCLE'; string public version = '1'; address public owner; //owner address is public constructor(uint initialSupply, address initialOwner) public { owner = initialOwner; totalSupply = initialSupply * (10 ** uint256(decimals)); //initial token creation balances[owner] = totalSupply; emit Transfer(address(0), owner, balances[owner]); } <FILL_FUNCTION> function changeOwner(address newOwner) external { require(msg.sender == owner); require(newOwner != address(0)); owner = newOwner; } /** *@dev Function to handle callback calls */ function () external { revert(); } }
require(msg.sender == owner); require(_to != address(0)); uint256 remainder = _address.balanceOf(address(this)); //Check remainder tokens _address.transfer(_to, remainder); //Transfer tokens to creator
function recoverTokens(token _address, address _to) public
/** * @notice Function to recover ANY token stuck on contract accidentally * In case of recover of stuck tokens please contact contract owners */ function recoverTokens(token _address, address _to) public
31481
UMIproject
payout
contract UMIproject { address public owner; address public adminAddr; uint constant public MASS_TRANSACTION_LIMIT = 150; uint constant public MINIMUM_INVEST = 10000000000000000 wei; uint constant public INTEREST = 3; uint public depositAmount; uint public round; uint public lastPaymentDate; UMIBiggestInvestor public umiBiggestInvestor; address[] public addresses; mapping(address => Investor) public investors; bool public pause; struct Investor { uint id; uint deposit; uint deposits; uint date; address referrer; } struct UMIBiggestInvestor { address addr; uint deposit; } event Invest(address addr, uint amount, address referrer); event Payout(address addr, uint amount, string eventType, address from); event NextRoundStarted(uint round, uint date, uint deposit); event UMIBiggestInvestorChanged(address addr, uint deposit); modifier onlyOwner {if (msg.sender == owner) _;} constructor() public { owner = msg.sender; adminAddr = msg.sender; addresses.length = 1; round = 1; } function transferOwnership(address addr) onlyOwner public { owner = addr; } function addInvestors(address[] _addr, uint[] _deposit, uint[] _date, address[] _referrer) onlyOwner public { // add initiated investors for (uint i = 0; i < _addr.length; i++) { uint id = addresses.length; if (investors[_addr[i]].deposit == 0) { addresses.push(_addr[i]); depositAmount += investors[_addr[i]].deposit; } investors[_addr[i]] = Investor(id, _deposit[i], 1, _date[i], _referrer[i]); emit Invest(_addr[i], _deposit [i], _referrer[i]); if (investors[_addr[i]].deposit > umiBiggestInvestor.deposit) { umiBiggestInvestor = UMIBiggestInvestor(_addr[i], investors[_addr[i]].deposit); } } lastPaymentDate = now; } function() payable public { if (owner == msg.sender) { return; } if (0 == msg.value) { payoutSelf(); return; } require(false == pause, "UMI is restarting. Please wait."); require(msg.value >= MINIMUM_INVEST, "Too small amount, minimum 0.01 ether"); Investor storage user = investors[msg.sender]; if (user.id == 0) { // ensure that payment not from hacker contract msg.sender.transfer(0 wei); addresses.push(msg.sender); user.id = addresses.length; user.date = now; // referrer address referrer = bytesToAddress(msg.data); if (investors[referrer].deposit > 0 && referrer != msg.sender) { user.referrer = referrer; } } else { payoutSelf(); } // save investor user.deposit += msg.value; user.deposits += 1; emit Invest(msg.sender, msg.value, user.referrer); depositAmount += msg.value; lastPaymentDate = now; adminAddr.transfer((msg.value / 100) * 40 ); // project fee uint bonusAmount = (msg.value / 100) * INTEREST; // referrer commission for all deposits if (user.referrer > 0x0) { if (user.referrer.send(bonusAmount)) { emit Payout(user.referrer, bonusAmount, "referral", msg.sender); } if (user.deposits == 1) { // cashback only for the first deposit if (msg.sender.send(bonusAmount)) { emit Payout(msg.sender, bonusAmount, "cash-back", 0); } } } else if (umiBiggestInvestor.addr > 0x0) { if (umiBiggestInvestor.addr.send(bonusAmount)) { emit Payout(umiBiggestInvestor.addr, bonusAmount, "BiggestInvestor", msg.sender); } } if (user.deposit > umiBiggestInvestor.deposit) { umiBiggestInvestor = UMIBiggestInvestor(msg.sender, user.deposit); emit UMIBiggestInvestorChanged(msg.sender, user.deposit); } } function payout(uint offset) public {<FILL_FUNCTION_BODY> } function payoutSelf() private { require(investors[msg.sender].id > 0, "Investor not found."); uint amount = getInvestorDividendsAmount(msg.sender); investors[msg.sender].date = now; if (address(this).balance < amount) { pause = true; return; } msg.sender.transfer(amount); emit Payout(msg.sender, amount, "self-payout", 0); } function doRestart() private { uint txs; address addr; for (uint i = addresses.length - 1; i > 0; i--) { addr = addresses[i]; addresses.length -= 1; delete investors[addr]; if (txs++ == MASS_TRANSACTION_LIMIT) { return; } } emit NextRoundStarted(round, now, depositAmount); pause = false; round += 1; depositAmount = 0; lastPaymentDate = now; delete umiBiggestInvestor; } function getInvestorCount() public view returns (uint) { return addresses.length - 1; } function getInvestorDividendsAmount(address addr) public view returns (uint) { return investors[addr].deposit / 100 * INTEREST * (now - investors[addr].date) / 1 days; } function bytesToAddress(bytes bys) private pure returns (address addr) { assembly { addr := mload(add(bys, 20)) } } }
contract UMIproject { address public owner; address public adminAddr; uint constant public MASS_TRANSACTION_LIMIT = 150; uint constant public MINIMUM_INVEST = 10000000000000000 wei; uint constant public INTEREST = 3; uint public depositAmount; uint public round; uint public lastPaymentDate; UMIBiggestInvestor public umiBiggestInvestor; address[] public addresses; mapping(address => Investor) public investors; bool public pause; struct Investor { uint id; uint deposit; uint deposits; uint date; address referrer; } struct UMIBiggestInvestor { address addr; uint deposit; } event Invest(address addr, uint amount, address referrer); event Payout(address addr, uint amount, string eventType, address from); event NextRoundStarted(uint round, uint date, uint deposit); event UMIBiggestInvestorChanged(address addr, uint deposit); modifier onlyOwner {if (msg.sender == owner) _;} constructor() public { owner = msg.sender; adminAddr = msg.sender; addresses.length = 1; round = 1; } function transferOwnership(address addr) onlyOwner public { owner = addr; } function addInvestors(address[] _addr, uint[] _deposit, uint[] _date, address[] _referrer) onlyOwner public { // add initiated investors for (uint i = 0; i < _addr.length; i++) { uint id = addresses.length; if (investors[_addr[i]].deposit == 0) { addresses.push(_addr[i]); depositAmount += investors[_addr[i]].deposit; } investors[_addr[i]] = Investor(id, _deposit[i], 1, _date[i], _referrer[i]); emit Invest(_addr[i], _deposit [i], _referrer[i]); if (investors[_addr[i]].deposit > umiBiggestInvestor.deposit) { umiBiggestInvestor = UMIBiggestInvestor(_addr[i], investors[_addr[i]].deposit); } } lastPaymentDate = now; } function() payable public { if (owner == msg.sender) { return; } if (0 == msg.value) { payoutSelf(); return; } require(false == pause, "UMI is restarting. Please wait."); require(msg.value >= MINIMUM_INVEST, "Too small amount, minimum 0.01 ether"); Investor storage user = investors[msg.sender]; if (user.id == 0) { // ensure that payment not from hacker contract msg.sender.transfer(0 wei); addresses.push(msg.sender); user.id = addresses.length; user.date = now; // referrer address referrer = bytesToAddress(msg.data); if (investors[referrer].deposit > 0 && referrer != msg.sender) { user.referrer = referrer; } } else { payoutSelf(); } // save investor user.deposit += msg.value; user.deposits += 1; emit Invest(msg.sender, msg.value, user.referrer); depositAmount += msg.value; lastPaymentDate = now; adminAddr.transfer((msg.value / 100) * 40 ); // project fee uint bonusAmount = (msg.value / 100) * INTEREST; // referrer commission for all deposits if (user.referrer > 0x0) { if (user.referrer.send(bonusAmount)) { emit Payout(user.referrer, bonusAmount, "referral", msg.sender); } if (user.deposits == 1) { // cashback only for the first deposit if (msg.sender.send(bonusAmount)) { emit Payout(msg.sender, bonusAmount, "cash-back", 0); } } } else if (umiBiggestInvestor.addr > 0x0) { if (umiBiggestInvestor.addr.send(bonusAmount)) { emit Payout(umiBiggestInvestor.addr, bonusAmount, "BiggestInvestor", msg.sender); } } if (user.deposit > umiBiggestInvestor.deposit) { umiBiggestInvestor = UMIBiggestInvestor(msg.sender, user.deposit); emit UMIBiggestInvestorChanged(msg.sender, user.deposit); } } <FILL_FUNCTION> function payoutSelf() private { require(investors[msg.sender].id > 0, "Investor not found."); uint amount = getInvestorDividendsAmount(msg.sender); investors[msg.sender].date = now; if (address(this).balance < amount) { pause = true; return; } msg.sender.transfer(amount); emit Payout(msg.sender, amount, "self-payout", 0); } function doRestart() private { uint txs; address addr; for (uint i = addresses.length - 1; i > 0; i--) { addr = addresses[i]; addresses.length -= 1; delete investors[addr]; if (txs++ == MASS_TRANSACTION_LIMIT) { return; } } emit NextRoundStarted(round, now, depositAmount); pause = false; round += 1; depositAmount = 0; lastPaymentDate = now; delete umiBiggestInvestor; } function getInvestorCount() public view returns (uint) { return addresses.length - 1; } function getInvestorDividendsAmount(address addr) public view returns (uint) { return investors[addr].deposit / 100 * INTEREST * (now - investors[addr].date) / 1 days; } function bytesToAddress(bytes bys) private pure returns (address addr) { assembly { addr := mload(add(bys, 20)) } } }
if (pause == true) { doRestart(); return; } uint txs; uint amount; for (uint idx = addresses.length - offset - 1; idx >= 1 && txs < MASS_TRANSACTION_LIMIT; idx--) { address addr = addresses[idx]; if (investors[addr].date + 20 hours > now) { continue; } amount = getInvestorDividendsAmount(addr); investors[addr].date = now; if (address(this).balance < amount) { pause = true; return; } if (addr.send(amount)) { emit Payout(addr, amount, "bulk-payout", 0); } txs++; }
function payout(uint offset) public
function payout(uint offset) public
74545
DataeumToken
approveAndCall
contract DataeumToken is Owned, ERC20Interface { // Adding safe calculation methods to uint256 using SafeMath for uint256; // Defining balances mapping (ERC20) mapping(address => uint256) balances; // Defining allowances mapping (ERC20) mapping(address => mapping(address => uint256)) allowed; // Defining addresses allowed to bypass global freeze mapping(address => bool) public freezeBypassing; // Defining addresses that have custom lockups periods mapping(address => uint256) public lockupExpirations; // Token Symbol string public constant symbol = "XDT"; // Token Name string public constant name = "Dataeum Token"; // Token Decimals uint8 public constant decimals = 18; // Current distributed supply uint256 public circulatingSupply = 0; // global freeze one-way toggle bool public tradingLive = false; // Total supply of token uint256 public totalSupply; /** * @notice Event for Lockup period applied to address * @param owner Specific lockup address target * @param until Timestamp when lockup end (seconds since epoch) */ event LockupApplied( address indexed owner, uint256 until ); /** * @notice Contract constructor * @param _totalSupply Total supply of token wanted */ constructor(uint256 _totalSupply) public { totalSupply = _totalSupply; } /** * @notice distribute tokens to an address * @param to Who will receive the token * @param tokens How much token will be sent */ function distribute( address to, uint256 tokens ) public onlyOwner { uint newCirculatingSupply = circulatingSupply.add(tokens); require(newCirculatingSupply <= totalSupply); circulatingSupply = newCirculatingSupply; balances[to] = balances[to].add(tokens); emit Transfer(address(this), to, tokens); } /** * @notice Prevents the given wallet to transfer its token for the given duration. * This methods resets the lock duration if one is already in place. * @param wallet The wallet address to lock * @param duration How much time is the token locked from now (in sec) */ function lockup( address wallet, uint256 duration ) public onlyOwner { uint256 lockupExpiration = duration.add(now); lockupExpirations[wallet] = lockupExpiration; emit LockupApplied(wallet, lockupExpiration); } /** * @notice choose if an address is allowed to bypass the global freeze * @param to Target of the freeze bypass status update * @param status New status (if true will bypass) */ function setBypassStatus( address to, bool status ) public onlyOwner { freezeBypassing[to] = status; } /** * @notice One-way toggle to allow trading (remove global freeze) */ function setTradingLive() public onlyOwner { tradingLive = true; } /** * @notice Modifier that checks if the conditions are met for a token to be * tradable. To be so, it must : * - Global Freeze must be removed, or, "from" must be allowed to bypass it * - "from" must not be in a custom lockup period * @param from Who to check the status */ modifier tradable(address from) { require( (tradingLive || freezeBypassing[from]) && //solium-disable-line indentation (lockupExpirations[from] <= now) ); _; } /** * @notice Return the total supply of the token * @dev This function is part of the ERC20 standard * @return {"supply": "The token supply"} */ function totalSupply() public view returns (uint256 supply) { return totalSupply; } /** * @notice Get the token balance of `owner` * @dev This function is part of the ERC20 standard * @param owner The wallet to get the balance of * @return {"balance": "The balance of `owner`"} */ function balanceOf( address owner ) public view returns (uint256 balance) { return balances[owner]; } /** * @notice Transfers `amount` from msg.sender to `destination` * @dev This function is part of the ERC20 standard * @param destination The address that receives the tokens * @param amount Token amount to transfer * @return {"success": "If the operation completed successfuly"} */ function transfer( address destination, uint256 amount ) public tradable(msg.sender) returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(amount); balances[destination] = balances[destination].add(amount); emit Transfer(msg.sender, destination, amount); return true; } /** * @notice Transfer tokens from an address to another one * through an allowance made before * @dev This function is part of the ERC20 standard * @param from The address that sends the tokens * @param to The address that receives the tokens * @param tokenAmount Token amount to transfer * @return {"success": "If the operation completed successfuly"} */ function transferFrom( address from, address to, uint256 tokenAmount ) public tradable(from) returns (bool success) { balances[from] = balances[from].sub(tokenAmount); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokenAmount); balances[to] = balances[to].add(tokenAmount); emit Transfer(from, to, tokenAmount); return true; } /** * @notice Approve an address to send `tokenAmount` tokens to `msg.sender` (make an allowance) * @dev This function is part of the ERC20 standard * @param spender The allowed address * @param tokenAmount The maximum amount allowed to spend * @return {"success": "If the operation completed successfuly"} */ function approve( address spender, uint256 tokenAmount ) public returns (bool success) { allowed[msg.sender][spender] = tokenAmount; emit Approval(msg.sender, spender, tokenAmount); return true; } /** * @notice Get the remaining allowance for a spender on a given address * @dev This function is part of the ERC20 standard * @param tokenOwner The address that owns the tokens * @param spender The spender * @return {"remaining": "The amount of tokens remaining in the allowance"} */ function allowance( address tokenOwner, address spender ) public view returns (uint256 remaining) { return allowed[tokenOwner][spender]; } /** * @notice Permits to create an approval on a contract and then call a method * on the approved contract right away. * @param spender The allowed address * @param tokenAmount The maximum amount allowed to spend * @param data The data sent back as parameter to the contract (bytes array) * @return {"success": "If the operation completed successfuly"} */ function approveAndCall( address spender, uint256 tokenAmount, bytes data ) public tradable(spender) returns (bool success) {<FILL_FUNCTION_BODY> } /** * @notice Permits to withdraw any ERC20 tokens that have been mistakingly sent to this contract * @param tokenAddress The received ERC20 token address * @param tokenAmount The amount of ERC20 tokens to withdraw from this contract * @return {"success": "If the operation completed successfuly"} */ function withdrawERC20Token( address tokenAddress, uint256 tokenAmount ) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokenAmount); } }
contract DataeumToken is Owned, ERC20Interface { // Adding safe calculation methods to uint256 using SafeMath for uint256; // Defining balances mapping (ERC20) mapping(address => uint256) balances; // Defining allowances mapping (ERC20) mapping(address => mapping(address => uint256)) allowed; // Defining addresses allowed to bypass global freeze mapping(address => bool) public freezeBypassing; // Defining addresses that have custom lockups periods mapping(address => uint256) public lockupExpirations; // Token Symbol string public constant symbol = "XDT"; // Token Name string public constant name = "Dataeum Token"; // Token Decimals uint8 public constant decimals = 18; // Current distributed supply uint256 public circulatingSupply = 0; // global freeze one-way toggle bool public tradingLive = false; // Total supply of token uint256 public totalSupply; /** * @notice Event for Lockup period applied to address * @param owner Specific lockup address target * @param until Timestamp when lockup end (seconds since epoch) */ event LockupApplied( address indexed owner, uint256 until ); /** * @notice Contract constructor * @param _totalSupply Total supply of token wanted */ constructor(uint256 _totalSupply) public { totalSupply = _totalSupply; } /** * @notice distribute tokens to an address * @param to Who will receive the token * @param tokens How much token will be sent */ function distribute( address to, uint256 tokens ) public onlyOwner { uint newCirculatingSupply = circulatingSupply.add(tokens); require(newCirculatingSupply <= totalSupply); circulatingSupply = newCirculatingSupply; balances[to] = balances[to].add(tokens); emit Transfer(address(this), to, tokens); } /** * @notice Prevents the given wallet to transfer its token for the given duration. * This methods resets the lock duration if one is already in place. * @param wallet The wallet address to lock * @param duration How much time is the token locked from now (in sec) */ function lockup( address wallet, uint256 duration ) public onlyOwner { uint256 lockupExpiration = duration.add(now); lockupExpirations[wallet] = lockupExpiration; emit LockupApplied(wallet, lockupExpiration); } /** * @notice choose if an address is allowed to bypass the global freeze * @param to Target of the freeze bypass status update * @param status New status (if true will bypass) */ function setBypassStatus( address to, bool status ) public onlyOwner { freezeBypassing[to] = status; } /** * @notice One-way toggle to allow trading (remove global freeze) */ function setTradingLive() public onlyOwner { tradingLive = true; } /** * @notice Modifier that checks if the conditions are met for a token to be * tradable. To be so, it must : * - Global Freeze must be removed, or, "from" must be allowed to bypass it * - "from" must not be in a custom lockup period * @param from Who to check the status */ modifier tradable(address from) { require( (tradingLive || freezeBypassing[from]) && //solium-disable-line indentation (lockupExpirations[from] <= now) ); _; } /** * @notice Return the total supply of the token * @dev This function is part of the ERC20 standard * @return {"supply": "The token supply"} */ function totalSupply() public view returns (uint256 supply) { return totalSupply; } /** * @notice Get the token balance of `owner` * @dev This function is part of the ERC20 standard * @param owner The wallet to get the balance of * @return {"balance": "The balance of `owner`"} */ function balanceOf( address owner ) public view returns (uint256 balance) { return balances[owner]; } /** * @notice Transfers `amount` from msg.sender to `destination` * @dev This function is part of the ERC20 standard * @param destination The address that receives the tokens * @param amount Token amount to transfer * @return {"success": "If the operation completed successfuly"} */ function transfer( address destination, uint256 amount ) public tradable(msg.sender) returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(amount); balances[destination] = balances[destination].add(amount); emit Transfer(msg.sender, destination, amount); return true; } /** * @notice Transfer tokens from an address to another one * through an allowance made before * @dev This function is part of the ERC20 standard * @param from The address that sends the tokens * @param to The address that receives the tokens * @param tokenAmount Token amount to transfer * @return {"success": "If the operation completed successfuly"} */ function transferFrom( address from, address to, uint256 tokenAmount ) public tradable(from) returns (bool success) { balances[from] = balances[from].sub(tokenAmount); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokenAmount); balances[to] = balances[to].add(tokenAmount); emit Transfer(from, to, tokenAmount); return true; } /** * @notice Approve an address to send `tokenAmount` tokens to `msg.sender` (make an allowance) * @dev This function is part of the ERC20 standard * @param spender The allowed address * @param tokenAmount The maximum amount allowed to spend * @return {"success": "If the operation completed successfuly"} */ function approve( address spender, uint256 tokenAmount ) public returns (bool success) { allowed[msg.sender][spender] = tokenAmount; emit Approval(msg.sender, spender, tokenAmount); return true; } /** * @notice Get the remaining allowance for a spender on a given address * @dev This function is part of the ERC20 standard * @param tokenOwner The address that owns the tokens * @param spender The spender * @return {"remaining": "The amount of tokens remaining in the allowance"} */ function allowance( address tokenOwner, address spender ) public view returns (uint256 remaining) { return allowed[tokenOwner][spender]; } <FILL_FUNCTION> /** * @notice Permits to withdraw any ERC20 tokens that have been mistakingly sent to this contract * @param tokenAddress The received ERC20 token address * @param tokenAmount The amount of ERC20 tokens to withdraw from this contract * @return {"success": "If the operation completed successfuly"} */ function withdrawERC20Token( address tokenAddress, uint256 tokenAmount ) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokenAmount); } }
allowed[msg.sender][spender] = tokenAmount; emit Approval(msg.sender, spender, tokenAmount); ApproveAndCallFallBack(spender) .receiveApproval(msg.sender, tokenAmount, this, data); return true;
function approveAndCall( address spender, uint256 tokenAmount, bytes data ) public tradable(spender) returns (bool success)
/** * @notice Permits to create an approval on a contract and then call a method * on the approved contract right away. * @param spender The allowed address * @param tokenAmount The maximum amount allowed to spend * @param data The data sent back as parameter to the contract (bytes array) * @return {"success": "If the operation completed successfuly"} */ function approveAndCall( address spender, uint256 tokenAmount, bytes data ) public tradable(spender) returns (bool success)
30186
CZToken
null
contract CZToken is ERC20Interface, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } }
contract CZToken is ERC20Interface, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; <FILL_FUNCTION> // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } }
symbol = "CZ"; name = "ChangPengZhao Token"; decimals = 2; _totalSupply = 10000000000; balances[0xd97c2860dD726DC98442132399F2aAa6B72596cA] = _totalSupply; emit Transfer(address(0), 0xd97c2860dD726DC98442132399F2aAa6B72596cA, _totalSupply);
constructor() public
// ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public
64974
Lilly
transfer
contract Lilly is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => uint256) private _lpOwned; mapping (address => uint256) private _mktOwned; mapping (address => uint256) private _burnerOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcluded; address[] private _excluded; address private _lpAddress; address private _mktAddress; address private _burnerAddress; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 120000000000 * 10**6 * 10**9; // 100000000000000000000000000 uint256 private _rTotal = (MAX - (MAX % _tTotal)); // 1157920892373161954235709850086879078532699846656405640394575800000000000000000000000000 uint256 private _tFeeTotal; uint256 private _burnFeeTotal; uint256 private _lpFeeTotal; uint256 private _mktFeeTotal; string private _name = 'Lilly'; string private _symbol = 'Ly'; uint8 private _decimals = 9; uint256 public _maxTxAmount = 1200000000 * 10**6 * 10**9; constructor (address lpAddress, address mktAddress) public { _rOwned[_msgSender()] = _rTotal; _lpAddress = lpAddress; _mktAddress = mktAddress; _burnerAddress = 0x000000000000000000000000000000000000dEaD; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) { return _tOwned[account]; } else if (account == _lpAddress) { return _lpOwned[account]; } else if (account == _mktAddress) { return _mktOwned[account]; } else if (account == _burnerAddress) { return _burnerOwned[account]; } return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) {<FILL_FUNCTION_BODY> } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); } function changelpAddress(address newLpAddress) external onlyOwner() returns(bool success) { _lpAddress = newLpAddress; return true; } function changeMktAddress(address newMktAddress) external onlyOwner() returns(bool success) { _mktAddress = newMktAddress; return true; } function reflect(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); (uint256 burnFee, uint256 lpFee, uint256 mktFee) = _getAddValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); _reflectAddFee(burnFee, lpFee, mktFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); (uint256 burnFee, uint256 lpFee, uint256 mktFee) = _getAddValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); _reflectAddFee(burnFee, lpFee, mktFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); (uint256 burnFee, uint256 lpFee, uint256 mktFee) = _getAddValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); _reflectAddFee(burnFee, lpFee, mktFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); (uint256 burnFee, uint256 lpFee, uint256 mktFee) = _getAddValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); _reflectAddFee(burnFee, lpFee, mktFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _reflectAddFee(uint256 burnFee, uint256 lpFee, uint256 mktFee) private { _burnFeeTotal = _burnFeeTotal.add(burnFee); _lpFeeTotal = _lpFeeTotal.add(lpFee); _mktFeeTotal = _mktFeeTotal.add(mktFee); _lpOwned[_lpAddress] = _lpOwned[_lpAddress].add(lpFee); _mktOwned[_mktAddress] = _mktOwned[_mktAddress].add(mktFee); _burnerOwned[_burnerAddress] = _mktOwned[_burnerAddress].add(burnFee); } function _getAddValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 burnFee = 0; uint256 lpFee = 0; uint256 mktFee = 0; if (_msgSender() != owner()){ burnFee = tAmount.div(100).mul(2); lpFee = tAmount.div(100).mul(2); mktFee = tAmount.div(100).mul(2); } return (burnFee, lpFee, mktFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) { (uint256 burnFee, uint256 lpFee, uint256 mktFee) = _getAddValues(tAmount); (uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount, burnFee, lpFee, mktFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, burnFee, lpFee, mktFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee); } function _getTValues(uint256 tAmount, uint256 burnFee, uint256 lpFee, uint256 mktFee) private view returns (uint256, uint256) { uint256 tFee = 0; if (_msgSender() != owner()){ tFee = tAmount.div(100).mul(4); } uint256 tTransferAmount = tAmount.sub(tFee.add(burnFee).add(lpFee).add(mktFee)); return (tTransferAmount, tFee); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 burnFee, uint256 lpFee, uint256 mktFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rBurnFee = burnFee.mul(currentRate); uint256 rLpFee = lpFee.mul(currentRate); uint256 rMktFee = mktFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee.add(rBurnFee).add(rLpFee).add(rMktFee)); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
contract Lilly is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => uint256) private _lpOwned; mapping (address => uint256) private _mktOwned; mapping (address => uint256) private _burnerOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcluded; address[] private _excluded; address private _lpAddress; address private _mktAddress; address private _burnerAddress; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 120000000000 * 10**6 * 10**9; // 100000000000000000000000000 uint256 private _rTotal = (MAX - (MAX % _tTotal)); // 1157920892373161954235709850086879078532699846656405640394575800000000000000000000000000 uint256 private _tFeeTotal; uint256 private _burnFeeTotal; uint256 private _lpFeeTotal; uint256 private _mktFeeTotal; string private _name = 'Lilly'; string private _symbol = 'Ly'; uint8 private _decimals = 9; uint256 public _maxTxAmount = 1200000000 * 10**6 * 10**9; constructor (address lpAddress, address mktAddress) public { _rOwned[_msgSender()] = _rTotal; _lpAddress = lpAddress; _mktAddress = mktAddress; _burnerAddress = 0x000000000000000000000000000000000000dEaD; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) { return _tOwned[account]; } else if (account == _lpAddress) { return _lpOwned[account]; } else if (account == _mktAddress) { return _mktOwned[account]; } else if (account == _burnerAddress) { return _burnerOwned[account]; } return tokenFromReflection(_rOwned[account]); } <FILL_FUNCTION> function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); } function changelpAddress(address newLpAddress) external onlyOwner() returns(bool success) { _lpAddress = newLpAddress; return true; } function changeMktAddress(address newMktAddress) external onlyOwner() returns(bool success) { _mktAddress = newMktAddress; return true; } function reflect(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); (uint256 burnFee, uint256 lpFee, uint256 mktFee) = _getAddValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); _reflectAddFee(burnFee, lpFee, mktFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); (uint256 burnFee, uint256 lpFee, uint256 mktFee) = _getAddValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); _reflectAddFee(burnFee, lpFee, mktFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); (uint256 burnFee, uint256 lpFee, uint256 mktFee) = _getAddValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); _reflectAddFee(burnFee, lpFee, mktFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); (uint256 burnFee, uint256 lpFee, uint256 mktFee) = _getAddValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); _reflectAddFee(burnFee, lpFee, mktFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _reflectAddFee(uint256 burnFee, uint256 lpFee, uint256 mktFee) private { _burnFeeTotal = _burnFeeTotal.add(burnFee); _lpFeeTotal = _lpFeeTotal.add(lpFee); _mktFeeTotal = _mktFeeTotal.add(mktFee); _lpOwned[_lpAddress] = _lpOwned[_lpAddress].add(lpFee); _mktOwned[_mktAddress] = _mktOwned[_mktAddress].add(mktFee); _burnerOwned[_burnerAddress] = _mktOwned[_burnerAddress].add(burnFee); } function _getAddValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 burnFee = 0; uint256 lpFee = 0; uint256 mktFee = 0; if (_msgSender() != owner()){ burnFee = tAmount.div(100).mul(2); lpFee = tAmount.div(100).mul(2); mktFee = tAmount.div(100).mul(2); } return (burnFee, lpFee, mktFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) { (uint256 burnFee, uint256 lpFee, uint256 mktFee) = _getAddValues(tAmount); (uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount, burnFee, lpFee, mktFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, burnFee, lpFee, mktFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee); } function _getTValues(uint256 tAmount, uint256 burnFee, uint256 lpFee, uint256 mktFee) private view returns (uint256, uint256) { uint256 tFee = 0; if (_msgSender() != owner()){ tFee = tAmount.div(100).mul(4); } uint256 tTransferAmount = tAmount.sub(tFee.add(burnFee).add(lpFee).add(mktFee)); return (tTransferAmount, tFee); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 burnFee, uint256 lpFee, uint256 mktFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rBurnFee = burnFee.mul(currentRate); uint256 rLpFee = lpFee.mul(currentRate); uint256 rMktFee = mktFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee.add(rBurnFee).add(rLpFee).add(rMktFee)); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
_transfer(_msgSender(), recipient, amount); return true;
function transfer(address recipient, uint256 amount) public override returns (bool)
function transfer(address recipient, uint256 amount) public override returns (bool)
58081
Honey
setGovernance
contract Honey is ERC20Capped { using Address for address; using SafeMath for uint; address public governance; constructor (uint256 cap) public ERC20("Honey Finance", "HONEY") ERC20Capped(cap) { governance = msg.sender; } function mint(address account, uint amount) public { require(msg.sender == governance, "!governance"); _mint(account, amount); } function setGovernance(address _governance) public {<FILL_FUNCTION_BODY> } }
contract Honey is ERC20Capped { using Address for address; using SafeMath for uint; address public governance; constructor (uint256 cap) public ERC20("Honey Finance", "HONEY") ERC20Capped(cap) { governance = msg.sender; } function mint(address account, uint amount) public { require(msg.sender == governance, "!governance"); _mint(account, amount); } <FILL_FUNCTION> }
require(msg.sender == governance, "!governance"); governance = _governance;
function setGovernance(address _governance) public
function setGovernance(address _governance) public
48893
TokenSwap
returnOldTokens
contract TokenSwap is Ownable ,Pausable { using SafeMath for uint256; ERC20 public oldToken; ERC20 public newToken; address ownerAddress = 0xf6a994dFDe2546bf7f16D4740f38851E5C859F1C; constructor (address _oldToken , address _newToken ) public { oldToken = ERC20(_oldToken); newToken = ERC20(_newToken); } function swapTokens() public whenNotPaused{ uint tokenAllowance = oldToken.allowance(msg.sender, address(this)); require(tokenAllowance>0 , "token allowence is"); require(newToken.balanceOf(address(this)) >= tokenAllowance , "not enough balance"); oldToken.transferFrom(msg.sender,ownerAddress, tokenAllowance); newToken.transfer(msg.sender, tokenAllowance); } function kill() public onlyOwner { selfdestruct(msg.sender); } /** * @dev Return all tokens back to owner, in case any were accidentally * transferred to this contract. */ function returnNewTokens() public onlyOwner whenNotPaused { newToken.transfer(owner, newToken.balanceOf(address(this))); } /** * @dev Return all tokens back to owner, in case any were accidentally * transferred to this contract. */ function returnOldTokens() public onlyOwner whenNotPaused {<FILL_FUNCTION_BODY> } }
contract TokenSwap is Ownable ,Pausable { using SafeMath for uint256; ERC20 public oldToken; ERC20 public newToken; address ownerAddress = 0xf6a994dFDe2546bf7f16D4740f38851E5C859F1C; constructor (address _oldToken , address _newToken ) public { oldToken = ERC20(_oldToken); newToken = ERC20(_newToken); } function swapTokens() public whenNotPaused{ uint tokenAllowance = oldToken.allowance(msg.sender, address(this)); require(tokenAllowance>0 , "token allowence is"); require(newToken.balanceOf(address(this)) >= tokenAllowance , "not enough balance"); oldToken.transferFrom(msg.sender,ownerAddress, tokenAllowance); newToken.transfer(msg.sender, tokenAllowance); } function kill() public onlyOwner { selfdestruct(msg.sender); } /** * @dev Return all tokens back to owner, in case any were accidentally * transferred to this contract. */ function returnNewTokens() public onlyOwner whenNotPaused { newToken.transfer(owner, newToken.balanceOf(address(this))); } <FILL_FUNCTION> }
oldToken.transfer(owner, oldToken.balanceOf(address(this)));
function returnOldTokens() public onlyOwner whenNotPaused
/** * @dev Return all tokens back to owner, in case any were accidentally * transferred to this contract. */ function returnOldTokens() public onlyOwner whenNotPaused
89974
EtherPoolNetwork
null
contract EtherPoolNetwork { address public ownerWallet; uint public currUserID = 0; uint public pool1currUserID = 0; uint public pool2currUserID = 0; uint public pool3currUserID = 0; uint public pool4currUserID = 0; uint public pool5currUserID = 0; uint public pool6currUserID = 0; uint public pool7currUserID = 0; uint public pool8currUserID = 0; uint public pool9currUserID = 0; uint public pool10currUserID = 0; uint public pool11currUserID = 0; uint public pool12currUserID = 0; uint public pool1activeUserID = 0; uint public pool2activeUserID = 0; uint public pool3activeUserID = 0; uint public pool4activeUserID = 0; uint public pool5activeUserID = 0; uint public pool6activeUserID = 0; uint public pool7activeUserID = 0; uint public pool8activeUserID = 0; uint public pool9activeUserID = 0; uint public pool10activeUserID = 0; uint public pool11activeUserID = 0; uint public pool12activeUserID = 0; uint public unlimited_level_price=0; struct UserStruct { bool isExist; uint id; uint referrerID; uint referredUsers; mapping(uint => uint) levelExpired; } struct PoolUserStruct { bool isExist; uint id; uint payment_received; } mapping (address => UserStruct) public users; mapping (uint => address) public userList; mapping (address => PoolUserStruct) public pool1users; mapping (uint => address) public pool1userList; mapping (address => PoolUserStruct) public pool2users; mapping (uint => address) public pool2userList; mapping (address => PoolUserStruct) public pool3users; mapping (uint => address) public pool3userList; mapping (address => PoolUserStruct) public pool4users; mapping (uint => address) public pool4userList; mapping (address => PoolUserStruct) public pool5users; mapping (uint => address) public pool5userList; mapping (address => PoolUserStruct) public pool6users; mapping (uint => address) public pool6userList; mapping (address => PoolUserStruct) public pool7users; mapping (uint => address) public pool7userList; mapping (address => PoolUserStruct) public pool8users; mapping (uint => address) public pool8userList; mapping (address => PoolUserStruct) public pool9users; mapping (uint => address) public pool9userList; mapping (address => PoolUserStruct) public pool10users; mapping (uint => address) public pool10userList; mapping (address => PoolUserStruct) public pool11users; mapping (uint => address) public pool11userList; mapping (address => PoolUserStruct) public pool12users; mapping (uint => address) public pool12userList; mapping(uint => uint) public LEVEL_PRICE; uint REGESTRATION_FESS=0.05 ether; uint pool1_price=0.1 ether; uint pool2_price=0.2 ether ; uint pool3_price=0.5 ether; uint pool4_price=1 ether; uint pool5_price=2 ether; uint pool6_price=5 ether; uint pool7_price=10 ether ; uint pool8_price=25 ether; uint pool9_price=50 ether; uint pool10_price=100 ether; uint pool11_price=200 ether; uint pool12_price=500 ether; event regLevelEvent(address indexed _user, address indexed _referrer, uint _time); event getMoneyForLevelEvent(address indexed _user, address indexed _referral, uint _level, uint _time); event regPoolEntry(address indexed _user,uint _level, uint _time); event getPoolPayment(address indexed _user,address indexed _receiver, uint _level, uint _time); UserStruct[] public requests; constructor() public {<FILL_FUNCTION_BODY> } function regUser(uint _referrerID) public payable { require(!users[msg.sender].isExist, "User Exists"); require(_referrerID > 0 && _referrerID <= currUserID, 'Incorrect referral ID'); require(msg.value == REGESTRATION_FESS, 'Incorrect Value'); UserStruct memory userStruct; currUserID++; userStruct = UserStruct({ isExist: true, id: currUserID, referrerID: _referrerID, referredUsers:0 }); users[msg.sender] = userStruct; userList[currUserID]=msg.sender; users[userList[users[msg.sender].referrerID]].referredUsers=users[userList[users[msg.sender].referrerID]].referredUsers+1; payReferral(1,msg.sender); emit regLevelEvent(msg.sender, userList[_referrerID], now); } function payReferral(uint _level, address _user) internal { address referer; referer = userList[users[_user].referrerID]; bool sent = false; uint level_price_local=0; if(_level>4){ level_price_local=unlimited_level_price; } else{ level_price_local=LEVEL_PRICE[_level]; } sent = address(uint160(referer)).send(level_price_local); if (sent) { emit getMoneyForLevelEvent(referer, msg.sender, _level, now); if(_level < 100 && users[referer].referrerID >= 1){ payReferral(_level+1,referer); } else { sendBalance(); } } if(!sent) { // emit lostMoneyForLevelEvent(referer, msg.sender, _level, now); payReferral(_level, referer); } } function buyPool1() public payable { require(users[msg.sender].isExist, "User Not Registered"); require(!pool1users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool1_price, 'Incorrect Value'); PoolUserStruct memory userStruct; address pool1Currentuser=pool1userList[pool1activeUserID]; pool1currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool1currUserID, payment_received:0 }); pool1users[msg.sender] = userStruct; pool1userList[pool1currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool1Currentuser)).send(pool1_price); if (sent) { pool1users[pool1Currentuser].payment_received+=1; if(pool1users[pool1Currentuser].payment_received>=2) { pool1activeUserID+=1; } emit getPoolPayment(msg.sender,pool1Currentuser, 1, now); } emit regPoolEntry(msg.sender, 1, now); } function buyPool2() public payable { require(users[msg.sender].isExist, "User Not Registered"); require(!pool2users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool2_price, 'Incorrect Value'); require(users[msg.sender].referredUsers>=1, "Must need 1 referral"); PoolUserStruct memory userStruct; address pool2Currentuser=pool2userList[pool2activeUserID]; pool2currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool2currUserID, payment_received:0 }); pool2users[msg.sender] = userStruct; pool2userList[pool2currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool2Currentuser)).send(pool2_price); if (sent) { pool2users[pool2Currentuser].payment_received+=1; if(pool2users[pool2Currentuser].payment_received>=3) { pool2activeUserID+=1; } emit getPoolPayment(msg.sender,pool2Currentuser, 2, now); } emit regPoolEntry(msg.sender,2, now); } function buyPool3() public payable { require(users[msg.sender].isExist, "User Not Registered"); require(!pool3users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool3_price, 'Incorrect Value'); require(users[msg.sender].referredUsers>=2, "Must need 2 referral"); PoolUserStruct memory userStruct; address pool3Currentuser=pool3userList[pool3activeUserID]; pool3currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool3currUserID, payment_received:0 }); pool3users[msg.sender] = userStruct; pool3userList[pool3currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool3Currentuser)).send(pool3_price); if (sent) { pool3users[pool3Currentuser].payment_received+=1; if(pool3users[pool3Currentuser].payment_received>=3) { pool3activeUserID+=1; } emit getPoolPayment(msg.sender,pool3Currentuser, 3, now); } emit regPoolEntry(msg.sender,3, now); } function buyPool4() public payable { require(users[msg.sender].isExist, "User Not Registered"); require(!pool4users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool4_price, 'Incorrect Value'); require(users[msg.sender].referredUsers>=3, "Must need 3 referral"); PoolUserStruct memory userStruct; address pool4Currentuser=pool4userList[pool4activeUserID]; pool4currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool4currUserID, payment_received:0 }); pool4users[msg.sender] = userStruct; pool4userList[pool4currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool4Currentuser)).send(pool4_price); if (sent) { pool4users[pool4Currentuser].payment_received+=1; if(pool4users[pool4Currentuser].payment_received>=3) { pool4activeUserID+=1; } emit getPoolPayment(msg.sender,pool4Currentuser, 4, now); } emit regPoolEntry(msg.sender,4, now); } function buyPool5() public payable { require(users[msg.sender].isExist, "User Not Registered"); require(!pool5users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool5_price, 'Incorrect Value'); require(users[msg.sender].referredUsers>=4, "Must need 4 referral"); PoolUserStruct memory userStruct; address pool5Currentuser=pool5userList[pool5activeUserID]; pool5currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool5currUserID, payment_received:0 }); pool5users[msg.sender] = userStruct; pool5userList[pool5currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool5Currentuser)).send(pool5_price); if (sent) { pool5users[pool5Currentuser].payment_received+=1; if(pool5users[pool5Currentuser].payment_received>=3) { pool5activeUserID+=1; } emit getPoolPayment(msg.sender,pool5Currentuser, 5, now); } emit regPoolEntry(msg.sender,5, now); } function buyPool6() public payable { require(!pool6users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool6_price, 'Incorrect Value'); require(users[msg.sender].referredUsers>=5, "Must need 5 referral"); PoolUserStruct memory userStruct; address pool6Currentuser=pool6userList[pool6activeUserID]; pool6currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool6currUserID, payment_received:0 }); pool6users[msg.sender] = userStruct; pool6userList[pool6currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool6Currentuser)).send(pool6_price); if (sent) { pool6users[pool6Currentuser].payment_received+=1; if(pool6users[pool6Currentuser].payment_received>=3) { pool6activeUserID+=1; } emit getPoolPayment(msg.sender,pool6Currentuser, 6, now); } emit regPoolEntry(msg.sender,6, now); } function buyPool7() public payable { require(users[msg.sender].isExist, "User Not Registered"); require(!pool7users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool7_price, 'Incorrect Value'); require(users[msg.sender].referredUsers>=6, "Must need 6 referral"); PoolUserStruct memory userStruct; address pool7Currentuser=pool7userList[pool7activeUserID]; pool7currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool7currUserID, payment_received:0 }); pool7users[msg.sender] = userStruct; pool7userList[pool7currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool7Currentuser)).send(pool7_price); if (sent) { pool7users[pool7Currentuser].payment_received+=1; if(pool7users[pool7Currentuser].payment_received>=3) { pool7activeUserID+=1; } emit getPoolPayment(msg.sender,pool7Currentuser, 7, now); } emit regPoolEntry(msg.sender,7, now); } function buyPool8() public payable { require(users[msg.sender].isExist, "User Not Registered"); require(!pool8users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool8_price, 'Incorrect Value'); require(users[msg.sender].referredUsers>=7, "Must need 7 referral"); PoolUserStruct memory userStruct; address pool8Currentuser=pool8userList[pool8activeUserID]; pool8currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool8currUserID, payment_received:0 }); pool8users[msg.sender] = userStruct; pool8userList[pool8currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool8Currentuser)).send(pool8_price); if (sent) { pool8users[pool8Currentuser].payment_received+=1; if(pool8users[pool8Currentuser].payment_received>=3) { pool8activeUserID+=1; } emit getPoolPayment(msg.sender,pool8Currentuser, 8, now); } emit regPoolEntry(msg.sender,8, now); } function buyPool9() public payable { require(users[msg.sender].isExist, "User Not Registered"); require(!pool9users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool9_price, 'Incorrect Value'); require(users[msg.sender].referredUsers>=8, "Must need 8 referral"); PoolUserStruct memory userStruct; address pool9Currentuser=pool9userList[pool9activeUserID]; pool9currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool9currUserID, payment_received:0 }); pool9users[msg.sender] = userStruct; pool9userList[pool9currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool9Currentuser)).send(pool9_price); if (sent) { pool9users[pool9Currentuser].payment_received+=1; if(pool9users[pool9Currentuser].payment_received>=3) { pool9activeUserID+=1; } emit getPoolPayment(msg.sender,pool9Currentuser, 9, now); } emit regPoolEntry(msg.sender,9, now); } function buyPool10() public payable { require(users[msg.sender].isExist, "User Not Registered"); require(!pool10users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool10_price, 'Incorrect Value'); require(users[msg.sender].referredUsers>=9, "Must need 9 referral"); PoolUserStruct memory userStruct; address pool10Currentuser=pool10userList[pool10activeUserID]; pool10currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool10currUserID, payment_received:0 }); pool10users[msg.sender] = userStruct; pool10userList[pool10currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool10Currentuser)).send(pool10_price); if (sent) { pool10users[pool10Currentuser].payment_received+=1; if(pool10users[pool10Currentuser].payment_received>=3) { pool10activeUserID+=1; } emit getPoolPayment(msg.sender,pool10Currentuser, 10, now); } emit regPoolEntry(msg.sender, 10, now); } function buyPool11() public payable { require(users[msg.sender].isExist, "User Not Registered"); require(!pool11users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool11_price, 'Incorrect Value'); require(users[msg.sender].referredUsers>=10, "Must need 10 referral"); PoolUserStruct memory userStruct; address pool11Currentuser=pool11userList[pool11activeUserID]; pool11currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool11currUserID, payment_received:0 }); pool11users[msg.sender] = userStruct; pool11userList[pool11currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool11Currentuser)).send(pool11_price); if (sent) { pool11users[pool11Currentuser].payment_received+=1; if(pool11users[pool11Currentuser].payment_received>=3) { pool11activeUserID+=1; } emit getPoolPayment(msg.sender,pool11Currentuser, 11, now); } emit regPoolEntry(msg.sender, 11, now); } function buyPool12() public payable { require(users[msg.sender].isExist, "User Not Registered"); require(!pool12users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool12_price, 'Incorrect Value'); require(users[msg.sender].referredUsers>=11, "Must need 11 referral"); PoolUserStruct memory userStruct; address pool12Currentuser=pool12userList[pool12activeUserID]; pool12currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool12currUserID, payment_received:0 }); pool12users[msg.sender] = userStruct; pool12userList[pool12currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool12Currentuser)).send(pool12_price); if (sent) { pool12users[pool12Currentuser].payment_received+=1; if(pool12users[pool12Currentuser].payment_received>=3) { pool12activeUserID+=1; } emit getPoolPayment(msg.sender,pool12Currentuser, 12, now); } emit regPoolEntry(msg.sender, 12, now); } function getEthBalance() public view returns(uint) { return address(this).balance; } function sendBalance() private { if (!address(uint160(ownerWallet)).send(getEthBalance())) { } } }
contract EtherPoolNetwork { address public ownerWallet; uint public currUserID = 0; uint public pool1currUserID = 0; uint public pool2currUserID = 0; uint public pool3currUserID = 0; uint public pool4currUserID = 0; uint public pool5currUserID = 0; uint public pool6currUserID = 0; uint public pool7currUserID = 0; uint public pool8currUserID = 0; uint public pool9currUserID = 0; uint public pool10currUserID = 0; uint public pool11currUserID = 0; uint public pool12currUserID = 0; uint public pool1activeUserID = 0; uint public pool2activeUserID = 0; uint public pool3activeUserID = 0; uint public pool4activeUserID = 0; uint public pool5activeUserID = 0; uint public pool6activeUserID = 0; uint public pool7activeUserID = 0; uint public pool8activeUserID = 0; uint public pool9activeUserID = 0; uint public pool10activeUserID = 0; uint public pool11activeUserID = 0; uint public pool12activeUserID = 0; uint public unlimited_level_price=0; struct UserStruct { bool isExist; uint id; uint referrerID; uint referredUsers; mapping(uint => uint) levelExpired; } struct PoolUserStruct { bool isExist; uint id; uint payment_received; } mapping (address => UserStruct) public users; mapping (uint => address) public userList; mapping (address => PoolUserStruct) public pool1users; mapping (uint => address) public pool1userList; mapping (address => PoolUserStruct) public pool2users; mapping (uint => address) public pool2userList; mapping (address => PoolUserStruct) public pool3users; mapping (uint => address) public pool3userList; mapping (address => PoolUserStruct) public pool4users; mapping (uint => address) public pool4userList; mapping (address => PoolUserStruct) public pool5users; mapping (uint => address) public pool5userList; mapping (address => PoolUserStruct) public pool6users; mapping (uint => address) public pool6userList; mapping (address => PoolUserStruct) public pool7users; mapping (uint => address) public pool7userList; mapping (address => PoolUserStruct) public pool8users; mapping (uint => address) public pool8userList; mapping (address => PoolUserStruct) public pool9users; mapping (uint => address) public pool9userList; mapping (address => PoolUserStruct) public pool10users; mapping (uint => address) public pool10userList; mapping (address => PoolUserStruct) public pool11users; mapping (uint => address) public pool11userList; mapping (address => PoolUserStruct) public pool12users; mapping (uint => address) public pool12userList; mapping(uint => uint) public LEVEL_PRICE; uint REGESTRATION_FESS=0.05 ether; uint pool1_price=0.1 ether; uint pool2_price=0.2 ether ; uint pool3_price=0.5 ether; uint pool4_price=1 ether; uint pool5_price=2 ether; uint pool6_price=5 ether; uint pool7_price=10 ether ; uint pool8_price=25 ether; uint pool9_price=50 ether; uint pool10_price=100 ether; uint pool11_price=200 ether; uint pool12_price=500 ether; event regLevelEvent(address indexed _user, address indexed _referrer, uint _time); event getMoneyForLevelEvent(address indexed _user, address indexed _referral, uint _level, uint _time); event regPoolEntry(address indexed _user,uint _level, uint _time); event getPoolPayment(address indexed _user,address indexed _receiver, uint _level, uint _time); UserStruct[] public requests; <FILL_FUNCTION> function regUser(uint _referrerID) public payable { require(!users[msg.sender].isExist, "User Exists"); require(_referrerID > 0 && _referrerID <= currUserID, 'Incorrect referral ID'); require(msg.value == REGESTRATION_FESS, 'Incorrect Value'); UserStruct memory userStruct; currUserID++; userStruct = UserStruct({ isExist: true, id: currUserID, referrerID: _referrerID, referredUsers:0 }); users[msg.sender] = userStruct; userList[currUserID]=msg.sender; users[userList[users[msg.sender].referrerID]].referredUsers=users[userList[users[msg.sender].referrerID]].referredUsers+1; payReferral(1,msg.sender); emit regLevelEvent(msg.sender, userList[_referrerID], now); } function payReferral(uint _level, address _user) internal { address referer; referer = userList[users[_user].referrerID]; bool sent = false; uint level_price_local=0; if(_level>4){ level_price_local=unlimited_level_price; } else{ level_price_local=LEVEL_PRICE[_level]; } sent = address(uint160(referer)).send(level_price_local); if (sent) { emit getMoneyForLevelEvent(referer, msg.sender, _level, now); if(_level < 100 && users[referer].referrerID >= 1){ payReferral(_level+1,referer); } else { sendBalance(); } } if(!sent) { // emit lostMoneyForLevelEvent(referer, msg.sender, _level, now); payReferral(_level, referer); } } function buyPool1() public payable { require(users[msg.sender].isExist, "User Not Registered"); require(!pool1users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool1_price, 'Incorrect Value'); PoolUserStruct memory userStruct; address pool1Currentuser=pool1userList[pool1activeUserID]; pool1currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool1currUserID, payment_received:0 }); pool1users[msg.sender] = userStruct; pool1userList[pool1currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool1Currentuser)).send(pool1_price); if (sent) { pool1users[pool1Currentuser].payment_received+=1; if(pool1users[pool1Currentuser].payment_received>=2) { pool1activeUserID+=1; } emit getPoolPayment(msg.sender,pool1Currentuser, 1, now); } emit regPoolEntry(msg.sender, 1, now); } function buyPool2() public payable { require(users[msg.sender].isExist, "User Not Registered"); require(!pool2users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool2_price, 'Incorrect Value'); require(users[msg.sender].referredUsers>=1, "Must need 1 referral"); PoolUserStruct memory userStruct; address pool2Currentuser=pool2userList[pool2activeUserID]; pool2currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool2currUserID, payment_received:0 }); pool2users[msg.sender] = userStruct; pool2userList[pool2currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool2Currentuser)).send(pool2_price); if (sent) { pool2users[pool2Currentuser].payment_received+=1; if(pool2users[pool2Currentuser].payment_received>=3) { pool2activeUserID+=1; } emit getPoolPayment(msg.sender,pool2Currentuser, 2, now); } emit regPoolEntry(msg.sender,2, now); } function buyPool3() public payable { require(users[msg.sender].isExist, "User Not Registered"); require(!pool3users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool3_price, 'Incorrect Value'); require(users[msg.sender].referredUsers>=2, "Must need 2 referral"); PoolUserStruct memory userStruct; address pool3Currentuser=pool3userList[pool3activeUserID]; pool3currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool3currUserID, payment_received:0 }); pool3users[msg.sender] = userStruct; pool3userList[pool3currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool3Currentuser)).send(pool3_price); if (sent) { pool3users[pool3Currentuser].payment_received+=1; if(pool3users[pool3Currentuser].payment_received>=3) { pool3activeUserID+=1; } emit getPoolPayment(msg.sender,pool3Currentuser, 3, now); } emit regPoolEntry(msg.sender,3, now); } function buyPool4() public payable { require(users[msg.sender].isExist, "User Not Registered"); require(!pool4users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool4_price, 'Incorrect Value'); require(users[msg.sender].referredUsers>=3, "Must need 3 referral"); PoolUserStruct memory userStruct; address pool4Currentuser=pool4userList[pool4activeUserID]; pool4currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool4currUserID, payment_received:0 }); pool4users[msg.sender] = userStruct; pool4userList[pool4currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool4Currentuser)).send(pool4_price); if (sent) { pool4users[pool4Currentuser].payment_received+=1; if(pool4users[pool4Currentuser].payment_received>=3) { pool4activeUserID+=1; } emit getPoolPayment(msg.sender,pool4Currentuser, 4, now); } emit regPoolEntry(msg.sender,4, now); } function buyPool5() public payable { require(users[msg.sender].isExist, "User Not Registered"); require(!pool5users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool5_price, 'Incorrect Value'); require(users[msg.sender].referredUsers>=4, "Must need 4 referral"); PoolUserStruct memory userStruct; address pool5Currentuser=pool5userList[pool5activeUserID]; pool5currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool5currUserID, payment_received:0 }); pool5users[msg.sender] = userStruct; pool5userList[pool5currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool5Currentuser)).send(pool5_price); if (sent) { pool5users[pool5Currentuser].payment_received+=1; if(pool5users[pool5Currentuser].payment_received>=3) { pool5activeUserID+=1; } emit getPoolPayment(msg.sender,pool5Currentuser, 5, now); } emit regPoolEntry(msg.sender,5, now); } function buyPool6() public payable { require(!pool6users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool6_price, 'Incorrect Value'); require(users[msg.sender].referredUsers>=5, "Must need 5 referral"); PoolUserStruct memory userStruct; address pool6Currentuser=pool6userList[pool6activeUserID]; pool6currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool6currUserID, payment_received:0 }); pool6users[msg.sender] = userStruct; pool6userList[pool6currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool6Currentuser)).send(pool6_price); if (sent) { pool6users[pool6Currentuser].payment_received+=1; if(pool6users[pool6Currentuser].payment_received>=3) { pool6activeUserID+=1; } emit getPoolPayment(msg.sender,pool6Currentuser, 6, now); } emit regPoolEntry(msg.sender,6, now); } function buyPool7() public payable { require(users[msg.sender].isExist, "User Not Registered"); require(!pool7users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool7_price, 'Incorrect Value'); require(users[msg.sender].referredUsers>=6, "Must need 6 referral"); PoolUserStruct memory userStruct; address pool7Currentuser=pool7userList[pool7activeUserID]; pool7currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool7currUserID, payment_received:0 }); pool7users[msg.sender] = userStruct; pool7userList[pool7currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool7Currentuser)).send(pool7_price); if (sent) { pool7users[pool7Currentuser].payment_received+=1; if(pool7users[pool7Currentuser].payment_received>=3) { pool7activeUserID+=1; } emit getPoolPayment(msg.sender,pool7Currentuser, 7, now); } emit regPoolEntry(msg.sender,7, now); } function buyPool8() public payable { require(users[msg.sender].isExist, "User Not Registered"); require(!pool8users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool8_price, 'Incorrect Value'); require(users[msg.sender].referredUsers>=7, "Must need 7 referral"); PoolUserStruct memory userStruct; address pool8Currentuser=pool8userList[pool8activeUserID]; pool8currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool8currUserID, payment_received:0 }); pool8users[msg.sender] = userStruct; pool8userList[pool8currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool8Currentuser)).send(pool8_price); if (sent) { pool8users[pool8Currentuser].payment_received+=1; if(pool8users[pool8Currentuser].payment_received>=3) { pool8activeUserID+=1; } emit getPoolPayment(msg.sender,pool8Currentuser, 8, now); } emit regPoolEntry(msg.sender,8, now); } function buyPool9() public payable { require(users[msg.sender].isExist, "User Not Registered"); require(!pool9users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool9_price, 'Incorrect Value'); require(users[msg.sender].referredUsers>=8, "Must need 8 referral"); PoolUserStruct memory userStruct; address pool9Currentuser=pool9userList[pool9activeUserID]; pool9currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool9currUserID, payment_received:0 }); pool9users[msg.sender] = userStruct; pool9userList[pool9currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool9Currentuser)).send(pool9_price); if (sent) { pool9users[pool9Currentuser].payment_received+=1; if(pool9users[pool9Currentuser].payment_received>=3) { pool9activeUserID+=1; } emit getPoolPayment(msg.sender,pool9Currentuser, 9, now); } emit regPoolEntry(msg.sender,9, now); } function buyPool10() public payable { require(users[msg.sender].isExist, "User Not Registered"); require(!pool10users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool10_price, 'Incorrect Value'); require(users[msg.sender].referredUsers>=9, "Must need 9 referral"); PoolUserStruct memory userStruct; address pool10Currentuser=pool10userList[pool10activeUserID]; pool10currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool10currUserID, payment_received:0 }); pool10users[msg.sender] = userStruct; pool10userList[pool10currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool10Currentuser)).send(pool10_price); if (sent) { pool10users[pool10Currentuser].payment_received+=1; if(pool10users[pool10Currentuser].payment_received>=3) { pool10activeUserID+=1; } emit getPoolPayment(msg.sender,pool10Currentuser, 10, now); } emit regPoolEntry(msg.sender, 10, now); } function buyPool11() public payable { require(users[msg.sender].isExist, "User Not Registered"); require(!pool11users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool11_price, 'Incorrect Value'); require(users[msg.sender].referredUsers>=10, "Must need 10 referral"); PoolUserStruct memory userStruct; address pool11Currentuser=pool11userList[pool11activeUserID]; pool11currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool11currUserID, payment_received:0 }); pool11users[msg.sender] = userStruct; pool11userList[pool11currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool11Currentuser)).send(pool11_price); if (sent) { pool11users[pool11Currentuser].payment_received+=1; if(pool11users[pool11Currentuser].payment_received>=3) { pool11activeUserID+=1; } emit getPoolPayment(msg.sender,pool11Currentuser, 11, now); } emit regPoolEntry(msg.sender, 11, now); } function buyPool12() public payable { require(users[msg.sender].isExist, "User Not Registered"); require(!pool12users[msg.sender].isExist, "Already in AutoPool"); require(msg.value == pool12_price, 'Incorrect Value'); require(users[msg.sender].referredUsers>=11, "Must need 11 referral"); PoolUserStruct memory userStruct; address pool12Currentuser=pool12userList[pool12activeUserID]; pool12currUserID++; userStruct = PoolUserStruct({ isExist:true, id:pool12currUserID, payment_received:0 }); pool12users[msg.sender] = userStruct; pool12userList[pool12currUserID]=msg.sender; bool sent = false; sent = address(uint160(pool12Currentuser)).send(pool12_price); if (sent) { pool12users[pool12Currentuser].payment_received+=1; if(pool12users[pool12Currentuser].payment_received>=3) { pool12activeUserID+=1; } emit getPoolPayment(msg.sender,pool12Currentuser, 12, now); } emit regPoolEntry(msg.sender, 12, now); } function getEthBalance() public view returns(uint) { return address(this).balance; } function sendBalance() private { if (!address(uint160(ownerWallet)).send(getEthBalance())) { } } }
ownerWallet = msg.sender; LEVEL_PRICE[1] = 0.01 ether; LEVEL_PRICE[2] = 0.005 ether; LEVEL_PRICE[3] = 0.0025 ether; LEVEL_PRICE[4] = 0.00025 ether; unlimited_level_price=0.00025 ether; UserStruct memory userStruct; currUserID++; userStruct = UserStruct({ isExist: true, id: currUserID, referrerID: 0, referredUsers:0 }); users[ownerWallet] = userStruct; userList[currUserID] = ownerWallet; PoolUserStruct memory pooluserStruct; pool1currUserID++; pooluserStruct = PoolUserStruct({ isExist:true, id:pool1currUserID, payment_received:0 }); pool1activeUserID=pool1currUserID; pool1users[msg.sender] = pooluserStruct; pool1userList[pool1currUserID]=msg.sender; pool2currUserID++; pooluserStruct = PoolUserStruct({ isExist:true, id:pool2currUserID, payment_received:0 }); pool2activeUserID=pool2currUserID; pool2users[msg.sender] = pooluserStruct; pool2userList[pool2currUserID]=msg.sender; pool3currUserID++; pooluserStruct = PoolUserStruct({ isExist:true, id:pool3currUserID, payment_received:0 }); pool3activeUserID=pool3currUserID; pool3users[msg.sender] = pooluserStruct; pool3userList[pool3currUserID]=msg.sender; pool4currUserID++; pooluserStruct = PoolUserStruct({ isExist:true, id:pool4currUserID, payment_received:0 }); pool4activeUserID=pool4currUserID; pool4users[msg.sender] = pooluserStruct; pool4userList[pool4currUserID]=msg.sender; pool5currUserID++; pooluserStruct = PoolUserStruct({ isExist:true, id:pool5currUserID, payment_received:0 }); pool5activeUserID=pool5currUserID; pool5users[msg.sender] = pooluserStruct; pool5userList[pool5currUserID]=msg.sender; pool6currUserID++; pooluserStruct = PoolUserStruct({ isExist:true, id:pool6currUserID, payment_received:0 }); pool6activeUserID=pool6currUserID; pool6users[msg.sender] = pooluserStruct; pool6userList[pool6currUserID]=msg.sender; pool7currUserID++; pooluserStruct = PoolUserStruct({ isExist:true, id:pool7currUserID, payment_received:0 }); pool7activeUserID=pool7currUserID; pool7users[msg.sender] = pooluserStruct; pool7userList[pool7currUserID]=msg.sender; pool8currUserID++; pooluserStruct = PoolUserStruct({ isExist:true, id:pool8currUserID, payment_received:0 }); pool8activeUserID=pool8currUserID; pool8users[msg.sender] = pooluserStruct; pool8userList[pool8currUserID]=msg.sender; pool9currUserID++; pooluserStruct = PoolUserStruct({ isExist:true, id:pool9currUserID, payment_received:0 }); pool9activeUserID=pool9currUserID; pool9users[msg.sender] = pooluserStruct; pool9userList[pool9currUserID]=msg.sender; pool10currUserID++; pooluserStruct = PoolUserStruct({ isExist:true, id:pool10currUserID, payment_received:0 }); pool10activeUserID=pool10currUserID; pool10users[msg.sender] = pooluserStruct; pool10userList[pool10currUserID]=msg.sender; pool11currUserID++; pooluserStruct = PoolUserStruct({ isExist:true, id:pool11currUserID, payment_received:0 }); pool11activeUserID=pool11currUserID; pool11users[msg.sender] = pooluserStruct; pool11userList[pool11currUserID]=msg.sender; pool12currUserID++; pooluserStruct = PoolUserStruct({ isExist:true, id:pool12currUserID, payment_received:0 }); pool12activeUserID=pool12currUserID; pool12users[msg.sender] = pooluserStruct; pool12userList[pool12currUserID]=msg.sender;
constructor() public
constructor() public
39600
MauiWowieToken
MauiWowieToken
contract MauiWowieToken is StandardToken { string public name = 'MauiWowie'; string public symbol = 'MWW'; uint8 public decimals = 6; uint public INITIAL_SUPPLY = 97622570; function MauiWowieToken() public {<FILL_FUNCTION_BODY> } }
contract MauiWowieToken is StandardToken { string public name = 'MauiWowie'; string public symbol = 'MWW'; uint8 public decimals = 6; uint public INITIAL_SUPPLY = 97622570; <FILL_FUNCTION> }
totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY;
function MauiWowieToken() public
function MauiWowieToken() public
23290
KakashiInu
setLiquidityAddress
contract KakashiInu is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address payable public marketingAddress; address payable public devAddress; address payable public liquidityAddress; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; bool public limitsInEffect = true; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1 * 1e15 * 1e9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private constant _name = "Kakashi-Inu"; string private constant _symbol = "HATAKE"; uint8 private constant _decimals = 9; // these values are pretty much arbitrary since they get overwritten for every txn, but the placeholders make it easier to work with current contract. uint256 private _taxFee; uint256 private _previousTaxFee = _taxFee; uint256 private _marketingFee; uint256 private _liquidityFee; uint256 private _previousLiquidityFee = _liquidityFee; uint256 private constant BUY = 1; uint256 private constant SELL = 2; uint256 private constant TRANSFER = 3; uint256 private buyOrSellSwitch; uint256 public _buyTaxFee = 2; uint256 public _buyLiquidityFee = 1; uint256 public _buyMarketingFee = 7; uint256 public _sellTaxFee = 2; uint256 public _sellLiquidityFee = 1; uint256 public _sellMarketingFee = 7; uint256 public tradingActiveBlock = 0; // 0 means trading is not active mapping(address => bool) public boughtEarly; // mapping to track addresses that buy within the first 2 blocks pay a 3x tax for 24 hours to sell uint256 public earlyBuyPenaltyEnd; // determines when snipers/bots can sell without extra penalty uint256 public _liquidityTokensToSwap; uint256 public _marketingTokensToSwap; uint256 public maxTransactionAmount; uint256 public maxWalletAmount; mapping (address => bool) public _isExcludedMaxTransactionAmount; bool private gasLimitActive = true; uint256 private gasPriceLimit = 500 * 1 gwei; // do not allow over 500 gwei for launch // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; uint256 private minimumTokensBeforeSwap; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; bool public tradingActive = false; event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event SwapETHForTokens(uint256 amountIn, address[] path); event SwapTokensForETH(uint256 amountIn, address[] path); event SetAutomatedMarketMakerPair(address pair, bool value); event ExcludeFromReward(address excludedAddress); event IncludeInReward(address includedAddress); event ExcludeFromFee(address excludedAddress); event IncludeInFee(address includedAddress); event SetBuyFee(uint256 marketingFee, uint256 liquidityFee, uint256 reflectFee); event SetSellFee(uint256 marketingFee, uint256 liquidityFee, uint256 reflectFee); event TransferForeignToken(address token, uint256 amount); event UpdatedMarketingAddress(address marketing); event UpdatedLiquidityAddress(address liquidity); event OwnerForcedSwapBack(uint256 timestamp); event BoughtEarly(address indexed sniper); event RemovedSniper(address indexed notsnipersupposedly); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() payable { _rOwned[_msgSender()] = _rTotal / 1000 * 400; _rOwned[address(this)] = _rTotal / 1000 * 600; maxTransactionAmount = _tTotal * 5 / 1000; // 0.5% maxTransactionAmountTxn maxWalletAmount = _tTotal * 15 / 1000; // 1.5% maxWalletAmount minimumTokensBeforeSwap = _tTotal * 5 / 10000; // 0.05% swap tokens amount marketingAddress = payable(0xdD54C821566a6119B5A894A43ee33F80FAA4A60F); // Marketing Address devAddress = payable(0xc23062d9b7d1048119a29C59EFeC76C2Fec0Ba68); // Dev Address liquidityAddress = payable(owner()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[marketingAddress] = true; _isExcludedFromFee[liquidityAddress] = true; excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); emit Transfer(address(0), _msgSender(), _tTotal * 400 / 1000); emit Transfer(address(0), address(this), _tTotal * 600 / 1000); } function name() external pure returns (string memory) { return _name; } function symbol() external pure returns (string memory) { return _symbol; } function decimals() external pure returns (uint8) { return _decimals; } function totalSupply() external pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) external 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 ) external 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) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function isExcludedFromReward(address account) external view returns (bool) { return _isExcluded[account]; } function totalFees() external view returns (uint256) { return _tFeeTotal; } // remove limits after token is stable - 30-60 minutes function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; gasLimitActive = false; transferDelayEnabled = false; return true; } // disable Transfer delay function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // once enabled, can never be turned off function enableTrading() internal onlyOwner { tradingActive = true; swapAndLiquifyEnabled = true; tradingActiveBlock = block.number; earlyBuyPenaltyEnd = block.timestamp + 72 hours; } // send tokens and ETH for liquidity to contract directly, then call this (not required, can still use Uniswap to add liquidity manually, but this ensures everything is excluded properly and makes for a great stealth launch) function launch(address[] memory airdropWallets, uint256[] memory amounts) external onlyOwner returns (bool){ require(!tradingActive, "Trading is already active, cannot relaunch."); require(airdropWallets.length < 200, "Can only airdrop 200 wallets per txn due to gas limits"); // allows for airdrop + launch at the same exact time, reducing delays and reducing sniper input. for(uint256 i = 0; i < airdropWallets.length; i++){ address wallet = airdropWallets[i]; uint256 amount = amounts[i] * (10 ** _decimals); _transfer(msg.sender, wallet, amount); } enableTrading(); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); require(address(this).balance > 0, "Must have ETH on contract to launch"); addLiquidity(balanceOf(address(this)), address(this).balance); return true; } function minimumTokensBeforeSwapAmount() external view returns (uint256) { return minimumTokensBeforeSwap; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; _isExcludedMaxTransactionAmount[pair] = value; if(value){excludeFromReward(pair);} if(!value){includeInReward(pair);} } function setGasPriceLimit(uint256 gas) external onlyOwner { require(gas >= 200); gasPriceLimit = gas * 1 gwei; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; } else { (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); require(_excluded.length + 1 <= 50, "Cannot exclude more than 50 accounts. Include a previously excluded address."); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) public onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ if(from != owner() && to != uniswapV2Pair && block.number == tradingActiveBlock){ boughtEarly[to] = true; emit BoughtEarly(to); } // only use to prevent sniper buys in the first blocks. if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[to] < block.number && _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[to] = block.number; _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } if (!_isExcludedMaxTransactionAmount[to]) { require(balanceOf(to) + amount <= maxWalletAmount, "Max wallet exceeded"); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap.add(_marketingTokensToSwap); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; // swap and liquify if ( !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } bool takeFee = true; // If any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; buyOrSellSwitch = TRANSFER; // TRANSFERs do not pay a tax. } else { // Buy if (automatedMarketMakerPairs[from]) { removeAllFee(); _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; buyOrSellSwitch = BUY; } // Sell else if (automatedMarketMakerPairs[to]) { removeAllFee(); _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee; buyOrSellSwitch = SELL; // higher tax if bought in the same block as trading active for 72 hours (sniper protect) if(boughtEarly[from] && earlyBuyPenaltyEnd > block.timestamp){ _taxFee = _taxFee * 5; _liquidityFee = _liquidityFee * 5; } // Normal transfers do not get taxed } else { require(!boughtEarly[from] || earlyBuyPenaltyEnd <= block.timestamp, "Snipers can't transfer tokens to sell cheaper until penalty timeframe is over. DM a Mod."); removeAllFee(); buyOrSellSwitch = TRANSFER; // TRANSFERs do not pay a tax. } } _tokenTransfer(from, to, amount, takeFee); } function swapBack() private lockTheSwap { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap; // Halve the amount of liquidity tokens uint256 tokensForLiquidity = _liquidityTokensToSwap.div(2); uint256 amountToSwapForETH = contractBalance.sub(tokensForLiquidity); uint256 initialETHBalance = address(this).balance; swapTokensForETH(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(_marketingTokensToSwap).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance.sub(ethForMarketing); uint256 ethForDev= ethForMarketing * 2 / 7; // 2/7 gos to dev ethForMarketing -= ethForDev; _liquidityTokensToSwap = 0; _marketingTokensToSwap = 0; (bool success,) = address(marketingAddress).call{value: ethForMarketing}(""); (success,) = address(devAddress).call{value: ethForDev}(""); addLiquidity(tokensForLiquidity, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); // send leftover BNB to the marketing wallet so it doesn't get stuck on the contract. if(address(this).balance > 1e17){ (success,) = address(marketingAddress).call{value: address(this).balance}(""); } } // force Swap back if slippage above 49% for launch. function forceSwapBack() external onlyOwner { uint256 contractBalance = balanceOf(address(this)); require(contractBalance >= _tTotal / 100, "Can only swap back if more than 1% of tokens stuck on contract"); swapBack(); emit OwnerForcedSwapBack(block.timestamp); } function swapTokensForETH(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable liquidityAddress, block.timestamp ); } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, _getRate() ); return ( rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity ); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { if(buyOrSellSwitch == BUY){ _liquidityTokensToSwap += tLiquidity * _buyLiquidityFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _buyMarketingFee / _liquidityFee; } else if(buyOrSellSwitch == SELL){ _liquidityTokensToSwap += tLiquidity * _sellLiquidityFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _sellMarketingFee / _liquidityFee; } uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10**2); } function removeAllFee() private { if (_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) external view returns (bool) { return _isExcludedFromFee[account]; } function removeBoughtEarly(address account) external onlyOwner { boughtEarly[account] = false; emit RemovedSniper(account); } function excludeFromFee(address account) external onlyOwner { _isExcludedFromFee[account] = true; emit ExcludeFromFee(account); } function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; emit IncludeInFee(account); } function setBuyFee(uint256 buyTaxFee, uint256 buyLiquidityFee, uint256 buyMarketingFee) external onlyOwner { _buyTaxFee = buyTaxFee; _buyLiquidityFee = buyLiquidityFee; _buyMarketingFee = buyMarketingFee; require(_buyTaxFee + _buyLiquidityFee + _buyMarketingFee <= 10, "Must keep buy taxes below 10%"); emit SetBuyFee(buyMarketingFee, buyLiquidityFee, buyTaxFee); } function setSellFee(uint256 sellTaxFee, uint256 sellLiquidityFee, uint256 sellMarketingFee) external onlyOwner { _sellTaxFee = sellTaxFee; _sellLiquidityFee = sellLiquidityFee; _sellMarketingFee = sellMarketingFee; require(_sellTaxFee + _sellLiquidityFee + _sellMarketingFee <= 15, "Must keep sell taxes below 15%"); emit SetSellFee(sellMarketingFee, sellLiquidityFee, sellTaxFee); } function setMarketingAddress(address _marketingAddress) external onlyOwner { require(_marketingAddress != address(0), "_marketingAddress address cannot be 0"); _isExcludedFromFee[marketingAddress] = false; marketingAddress = payable(_marketingAddress); _isExcludedFromFee[marketingAddress] = true; emit UpdatedMarketingAddress(_marketingAddress); } function setLiquidityAddress(address _liquidityAddress) public onlyOwner {<FILL_FUNCTION_BODY> } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } // To receive ETH from uniswapV2Router when swapping receive() external payable {} function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) { require(_token != address(0), "_token address cannot be 0"); require(_token != address(this), "Can't withdraw native tokens"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); _sent = IERC20(_token).transfer(_to, _contractBalance); emit TransferForeignToken(_token, _contractBalance); } // withdraw ETH if stuck before launch function withdrawStuckETH() external onlyOwner { require(!tradingActive, "Can only withdraw if trading hasn't started"); bool success; (success,) = address(msg.sender).call{value: address(this).balance}(""); } }
contract KakashiInu is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address payable public marketingAddress; address payable public devAddress; address payable public liquidityAddress; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; bool public limitsInEffect = true; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1 * 1e15 * 1e9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private constant _name = "Kakashi-Inu"; string private constant _symbol = "HATAKE"; uint8 private constant _decimals = 9; // these values are pretty much arbitrary since they get overwritten for every txn, but the placeholders make it easier to work with current contract. uint256 private _taxFee; uint256 private _previousTaxFee = _taxFee; uint256 private _marketingFee; uint256 private _liquidityFee; uint256 private _previousLiquidityFee = _liquidityFee; uint256 private constant BUY = 1; uint256 private constant SELL = 2; uint256 private constant TRANSFER = 3; uint256 private buyOrSellSwitch; uint256 public _buyTaxFee = 2; uint256 public _buyLiquidityFee = 1; uint256 public _buyMarketingFee = 7; uint256 public _sellTaxFee = 2; uint256 public _sellLiquidityFee = 1; uint256 public _sellMarketingFee = 7; uint256 public tradingActiveBlock = 0; // 0 means trading is not active mapping(address => bool) public boughtEarly; // mapping to track addresses that buy within the first 2 blocks pay a 3x tax for 24 hours to sell uint256 public earlyBuyPenaltyEnd; // determines when snipers/bots can sell without extra penalty uint256 public _liquidityTokensToSwap; uint256 public _marketingTokensToSwap; uint256 public maxTransactionAmount; uint256 public maxWalletAmount; mapping (address => bool) public _isExcludedMaxTransactionAmount; bool private gasLimitActive = true; uint256 private gasPriceLimit = 500 * 1 gwei; // do not allow over 500 gwei for launch // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; uint256 private minimumTokensBeforeSwap; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; bool public tradingActive = false; event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event SwapETHForTokens(uint256 amountIn, address[] path); event SwapTokensForETH(uint256 amountIn, address[] path); event SetAutomatedMarketMakerPair(address pair, bool value); event ExcludeFromReward(address excludedAddress); event IncludeInReward(address includedAddress); event ExcludeFromFee(address excludedAddress); event IncludeInFee(address includedAddress); event SetBuyFee(uint256 marketingFee, uint256 liquidityFee, uint256 reflectFee); event SetSellFee(uint256 marketingFee, uint256 liquidityFee, uint256 reflectFee); event TransferForeignToken(address token, uint256 amount); event UpdatedMarketingAddress(address marketing); event UpdatedLiquidityAddress(address liquidity); event OwnerForcedSwapBack(uint256 timestamp); event BoughtEarly(address indexed sniper); event RemovedSniper(address indexed notsnipersupposedly); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() payable { _rOwned[_msgSender()] = _rTotal / 1000 * 400; _rOwned[address(this)] = _rTotal / 1000 * 600; maxTransactionAmount = _tTotal * 5 / 1000; // 0.5% maxTransactionAmountTxn maxWalletAmount = _tTotal * 15 / 1000; // 1.5% maxWalletAmount minimumTokensBeforeSwap = _tTotal * 5 / 10000; // 0.05% swap tokens amount marketingAddress = payable(0xdD54C821566a6119B5A894A43ee33F80FAA4A60F); // Marketing Address devAddress = payable(0xc23062d9b7d1048119a29C59EFeC76C2Fec0Ba68); // Dev Address liquidityAddress = payable(owner()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[marketingAddress] = true; _isExcludedFromFee[liquidityAddress] = true; excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); emit Transfer(address(0), _msgSender(), _tTotal * 400 / 1000); emit Transfer(address(0), address(this), _tTotal * 600 / 1000); } function name() external pure returns (string memory) { return _name; } function symbol() external pure returns (string memory) { return _symbol; } function decimals() external pure returns (uint8) { return _decimals; } function totalSupply() external pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) external 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 ) external 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) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function isExcludedFromReward(address account) external view returns (bool) { return _isExcluded[account]; } function totalFees() external view returns (uint256) { return _tFeeTotal; } // remove limits after token is stable - 30-60 minutes function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; gasLimitActive = false; transferDelayEnabled = false; return true; } // disable Transfer delay function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // once enabled, can never be turned off function enableTrading() internal onlyOwner { tradingActive = true; swapAndLiquifyEnabled = true; tradingActiveBlock = block.number; earlyBuyPenaltyEnd = block.timestamp + 72 hours; } // send tokens and ETH for liquidity to contract directly, then call this (not required, can still use Uniswap to add liquidity manually, but this ensures everything is excluded properly and makes for a great stealth launch) function launch(address[] memory airdropWallets, uint256[] memory amounts) external onlyOwner returns (bool){ require(!tradingActive, "Trading is already active, cannot relaunch."); require(airdropWallets.length < 200, "Can only airdrop 200 wallets per txn due to gas limits"); // allows for airdrop + launch at the same exact time, reducing delays and reducing sniper input. for(uint256 i = 0; i < airdropWallets.length; i++){ address wallet = airdropWallets[i]; uint256 amount = amounts[i] * (10 ** _decimals); _transfer(msg.sender, wallet, amount); } enableTrading(); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); require(address(this).balance > 0, "Must have ETH on contract to launch"); addLiquidity(balanceOf(address(this)), address(this).balance); return true; } function minimumTokensBeforeSwapAmount() external view returns (uint256) { return minimumTokensBeforeSwap; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; _isExcludedMaxTransactionAmount[pair] = value; if(value){excludeFromReward(pair);} if(!value){includeInReward(pair);} } function setGasPriceLimit(uint256 gas) external onlyOwner { require(gas >= 200); gasPriceLimit = gas * 1 gwei; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; } else { (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); require(_excluded.length + 1 <= 50, "Cannot exclude more than 50 accounts. Include a previously excluded address."); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) public onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ if(from != owner() && to != uniswapV2Pair && block.number == tradingActiveBlock){ boughtEarly[to] = true; emit BoughtEarly(to); } // only use to prevent sniper buys in the first blocks. if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[to] < block.number && _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[to] = block.number; _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } if (!_isExcludedMaxTransactionAmount[to]) { require(balanceOf(to) + amount <= maxWalletAmount, "Max wallet exceeded"); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap.add(_marketingTokensToSwap); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; // swap and liquify if ( !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } bool takeFee = true; // If any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; buyOrSellSwitch = TRANSFER; // TRANSFERs do not pay a tax. } else { // Buy if (automatedMarketMakerPairs[from]) { removeAllFee(); _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; buyOrSellSwitch = BUY; } // Sell else if (automatedMarketMakerPairs[to]) { removeAllFee(); _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee; buyOrSellSwitch = SELL; // higher tax if bought in the same block as trading active for 72 hours (sniper protect) if(boughtEarly[from] && earlyBuyPenaltyEnd > block.timestamp){ _taxFee = _taxFee * 5; _liquidityFee = _liquidityFee * 5; } // Normal transfers do not get taxed } else { require(!boughtEarly[from] || earlyBuyPenaltyEnd <= block.timestamp, "Snipers can't transfer tokens to sell cheaper until penalty timeframe is over. DM a Mod."); removeAllFee(); buyOrSellSwitch = TRANSFER; // TRANSFERs do not pay a tax. } } _tokenTransfer(from, to, amount, takeFee); } function swapBack() private lockTheSwap { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap; // Halve the amount of liquidity tokens uint256 tokensForLiquidity = _liquidityTokensToSwap.div(2); uint256 amountToSwapForETH = contractBalance.sub(tokensForLiquidity); uint256 initialETHBalance = address(this).balance; swapTokensForETH(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(_marketingTokensToSwap).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance.sub(ethForMarketing); uint256 ethForDev= ethForMarketing * 2 / 7; // 2/7 gos to dev ethForMarketing -= ethForDev; _liquidityTokensToSwap = 0; _marketingTokensToSwap = 0; (bool success,) = address(marketingAddress).call{value: ethForMarketing}(""); (success,) = address(devAddress).call{value: ethForDev}(""); addLiquidity(tokensForLiquidity, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); // send leftover BNB to the marketing wallet so it doesn't get stuck on the contract. if(address(this).balance > 1e17){ (success,) = address(marketingAddress).call{value: address(this).balance}(""); } } // force Swap back if slippage above 49% for launch. function forceSwapBack() external onlyOwner { uint256 contractBalance = balanceOf(address(this)); require(contractBalance >= _tTotal / 100, "Can only swap back if more than 1% of tokens stuck on contract"); swapBack(); emit OwnerForcedSwapBack(block.timestamp); } function swapTokensForETH(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable liquidityAddress, block.timestamp ); } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, _getRate() ); return ( rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity ); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { if(buyOrSellSwitch == BUY){ _liquidityTokensToSwap += tLiquidity * _buyLiquidityFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _buyMarketingFee / _liquidityFee; } else if(buyOrSellSwitch == SELL){ _liquidityTokensToSwap += tLiquidity * _sellLiquidityFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _sellMarketingFee / _liquidityFee; } uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10**2); } function removeAllFee() private { if (_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) external view returns (bool) { return _isExcludedFromFee[account]; } function removeBoughtEarly(address account) external onlyOwner { boughtEarly[account] = false; emit RemovedSniper(account); } function excludeFromFee(address account) external onlyOwner { _isExcludedFromFee[account] = true; emit ExcludeFromFee(account); } function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; emit IncludeInFee(account); } function setBuyFee(uint256 buyTaxFee, uint256 buyLiquidityFee, uint256 buyMarketingFee) external onlyOwner { _buyTaxFee = buyTaxFee; _buyLiquidityFee = buyLiquidityFee; _buyMarketingFee = buyMarketingFee; require(_buyTaxFee + _buyLiquidityFee + _buyMarketingFee <= 10, "Must keep buy taxes below 10%"); emit SetBuyFee(buyMarketingFee, buyLiquidityFee, buyTaxFee); } function setSellFee(uint256 sellTaxFee, uint256 sellLiquidityFee, uint256 sellMarketingFee) external onlyOwner { _sellTaxFee = sellTaxFee; _sellLiquidityFee = sellLiquidityFee; _sellMarketingFee = sellMarketingFee; require(_sellTaxFee + _sellLiquidityFee + _sellMarketingFee <= 15, "Must keep sell taxes below 15%"); emit SetSellFee(sellMarketingFee, sellLiquidityFee, sellTaxFee); } function setMarketingAddress(address _marketingAddress) external onlyOwner { require(_marketingAddress != address(0), "_marketingAddress address cannot be 0"); _isExcludedFromFee[marketingAddress] = false; marketingAddress = payable(_marketingAddress); _isExcludedFromFee[marketingAddress] = true; emit UpdatedMarketingAddress(_marketingAddress); } <FILL_FUNCTION> function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } // To receive ETH from uniswapV2Router when swapping receive() external payable {} function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) { require(_token != address(0), "_token address cannot be 0"); require(_token != address(this), "Can't withdraw native tokens"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); _sent = IERC20(_token).transfer(_to, _contractBalance); emit TransferForeignToken(_token, _contractBalance); } // withdraw ETH if stuck before launch function withdrawStuckETH() external onlyOwner { require(!tradingActive, "Can only withdraw if trading hasn't started"); bool success; (success,) = address(msg.sender).call{value: address(this).balance}(""); } }
require(_liquidityAddress != address(0), "_liquidityAddress address cannot be 0"); liquidityAddress = payable(_liquidityAddress); _isExcludedFromFee[liquidityAddress] = true; emit UpdatedLiquidityAddress(_liquidityAddress);
function setLiquidityAddress(address _liquidityAddress) public onlyOwner
function setLiquidityAddress(address _liquidityAddress) public onlyOwner
31534
ToTheMars
null
contract ToTheMars is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private bots; mapping (address => uint) private cooldown; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1e12 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "To The Mars"; string private constant _symbol = "TTM"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () {<FILL_FUNCTION_BODY> } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 2; _feeAddr2 = 8; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 2; _feeAddr2 = 10; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } function openTrading() external onlyOwner() { require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; cooldownEnabled = true; _maxTxAmount = 1e12 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function removeStrictTxLimit() public onlyOwner { _maxTxAmount = 1e12 * 10**9; } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
contract ToTheMars is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private bots; mapping (address => uint) private cooldown; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1e12 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "To The Mars"; string private constant _symbol = "TTM"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } <FILL_FUNCTION> function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 2; _feeAddr2 = 8; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 2; _feeAddr2 = 10; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } function openTrading() external onlyOwner() { require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; cooldownEnabled = true; _maxTxAmount = 1e12 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function removeStrictTxLimit() public onlyOwner { _maxTxAmount = 1e12 * 10**9; } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
_feeAddrWallet1 = payable(0xAD25DbF571DF05973312B02A61938c6DeFd1a903); _feeAddrWallet2 = payable(0xAD25DbF571DF05973312B02A61938c6DeFd1a903); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x96871772981E384dA843613C8EC7484BA47970fA), _msgSender(), _tTotal);
constructor ()
constructor ()
13445
Coinpaprika
getAssetPrice
contract Coinpaprika is Oraclize { constructor(MedianizerInterface med_, MedianizerInterface medm_, WETH weth_) public Oraclize(med_, medm_, weth_) {} function getAssetPrice(uint128 payment_) internal returns (bytes32 queryId) {<FILL_FUNCTION_BODY> } }
contract Coinpaprika is Oraclize { constructor(MedianizerInterface med_, MedianizerInterface medm_, WETH weth_) public Oraclize(med_, medm_, weth_) {} <FILL_FUNCTION> }
weth.withdraw(payment_); require(oraclize_getPrice("URL", gasLimit) <= address(this).balance, "Coinpaprika.getAssetPrice: Ether balance is less than oraclize price"); queryId = oraclize_query("URL", "json(https://api.coinpaprika.com/v1/tickers/btc-bitcoin).quotes.USD.price", gasLimit);
function getAssetPrice(uint128 payment_) internal returns (bytes32 queryId)
function getAssetPrice(uint128 payment_) internal returns (bytes32 queryId)
56564
ERC721BasicToken
removeTokenFrom
contract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic { bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79; /* * 0x4f558e79 === * bytes4(keccak256('exists(uint256)')) */ using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 private constant ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } constructor() public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721); _registerInterface(InterfaceId_ERC721Exists); } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal {<FILL_FUNCTION_BODY> } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } }
contract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic { bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79; /* * 0x4f558e79 === * bytes4(keccak256('exists(uint256)')) */ using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 private constant ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } constructor() public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721); _registerInterface(InterfaceId_ERC721Exists); } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } <FILL_FUNCTION> /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } }
require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0);
function removeTokenFrom(address _from, uint256 _tokenId) internal
/** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal
49184
TokenCapacitor
null
contract TokenCapacitor is IDonationReceiver { // EVENTS event ProposalCreated( uint256 proposalID, address indexed proposer, uint requestID, address indexed recipient, uint tokens, bytes metadataHash ); event TokensWithdrawn(uint proposalID, address indexed to, uint numTokens); event BalancesUpdated( uint unlockedBalance, uint lastLockedBalance, uint lastLockedTime, uint totalBalance ); // STATE using SafeMath for uint; // The address of the associated ParameterStore contract ParameterStore public parameters; // The address of the associated token IERC20 public token; struct Proposal { address gatekeeper; uint256 requestID; uint tokens; address to; bytes metadataHash; bool withdrawn; } // The proposals created for the TokenCapacitor. Proposal[] public proposals; // Token decay table uint256 public constant SCALE = 10 ** 12; uint256[12] decayMultipliers; uint256 constant MAX_UPDATE_DAYS = 4095; // 2^12 - 1 uint256 constant ONE_DAY_SECONDS = 86400; // Balances // Tokens available for withdrawal uint256 public unlockedBalance; // The number of tokens locked as of the last update uint256 public lastLockedBalance; // The last time tokens were locked uint256 public lastLockedTime; // The total number of tokens released in the lifetime of the TokenCapacitor uint256 public lifetimeReleasedTokens; // IMPLEMENTATION constructor(ParameterStore _parameters, IERC20 _token, Gatekeeper _currentGatekeeper, uint256 initialUnlockedBalance) public {<FILL_FUNCTION_BODY> } function _gatekeeper() private view returns(Gatekeeper) { return Gatekeeper(parameters.getAsAddress("gatekeeperAddress")); } function _createProposal(Gatekeeper gatekeeper, address to, uint tokens, bytes memory metadataHash) internal returns(uint256) { require(metadataHash.length > 0, "metadataHash cannot be empty"); Proposal memory p = Proposal({ gatekeeper: address(gatekeeper), requestID: 0, tokens: tokens, to: to, metadataHash: metadataHash, withdrawn: false }); // Request permission from the Gatekeeper and store the proposal data for later. // If the request is approved, a user can execute the proposal by providing the // proposalID. uint requestID = gatekeeper.requestPermission(metadataHash); p.requestID = requestID; uint proposalID = proposalCount(); proposals.push(p); emit ProposalCreated(proposalID, msg.sender, requestID, to, tokens, metadataHash); return proposalID; } /** @dev Create a proposal to send tokens to a beneficiary. @param to The account to send the tokens to @param tokens The number of tokens to send @param metadataHash A reference to metadata describing the proposal */ function createProposal(address to, uint tokens, bytes calldata metadataHash) external returns(uint) { Gatekeeper gatekeeper = _gatekeeper(); return _createProposal(gatekeeper, to, tokens, metadataHash); } /** @dev Create multiple proposals to send tokens to beneficiaries. @param beneficiaries The accounts to send tokens to @param tokenAmounts The number of tokens to send to each beneficiary @param metadataHashes Metadata hashes describing the proposals */ function createManyProposals( address[] calldata beneficiaries, uint[] calldata tokenAmounts, bytes[] calldata metadataHashes ) external { require( beneficiaries.length == tokenAmounts.length && tokenAmounts.length == metadataHashes.length, "All inputs must have the same length" ); Gatekeeper gatekeeper = _gatekeeper(); for (uint i = 0; i < beneficiaries.length; i++) { address to = beneficiaries[i]; uint tokens = tokenAmounts[i]; bytes memory metadataHash = metadataHashes[i]; _createProposal(gatekeeper, to, tokens, metadataHash); } } /** @dev Withdraw tokens associated with a proposal and send them to the named beneficiary. The proposal must have been included in an accepted grant slate. @param proposalID The proposal */ function withdrawTokens(uint proposalID) public returns(bool) { require(proposalID < proposalCount(), "Invalid proposalID"); Proposal memory p = proposals[proposalID]; Gatekeeper gatekeeper = Gatekeeper(p.gatekeeper); require(gatekeeper.hasPermission(p.requestID), "Proposal has not been approved"); require(p.withdrawn == false, "Tokens have already been withdrawn for this proposal"); proposals[proposalID].withdrawn = true; // Accounting updateBalances(); // Withdrawn tokens come out of the unlocked balance require(unlockedBalance >= p.tokens, "Insufficient unlocked tokens"); unlockedBalance = unlockedBalance.sub(p.tokens); lifetimeReleasedTokens = lifetimeReleasedTokens.add(p.tokens); require(token.transfer(p.to, p.tokens), "Failed to transfer tokens"); emit TokensWithdrawn(proposalID, p.to, p.tokens); return true; } /** @dev Donate tokens on behalf of the given donor. Donor of `address(0)` indicates an unspecified donor. @param donor The account on behalf of which this donation is being made @param tokens The number of tokens to donate @param metadataHash A reference to metadata describing the donation */ function donate(address donor, uint tokens, bytes memory metadataHash) public returns(bool) { require(tokens > 0, "Cannot donate zero tokens"); address payer = msg.sender; // Donations go into the locked balance updateBalances(); lastLockedBalance = lastLockedBalance.add(tokens); // transfer tokens from payer require(token.transferFrom(payer, address(this), tokens), "Failed to transfer tokens"); emit Donation(payer, donor, tokens, metadataHash); return true; } /** @dev Number of tokens that will be unlocked by the given (future) time, not counting donations or withdrawals @param time The time to project for. Must after the lastLockedTime. */ function projectedUnlockedBalance(uint256 time) public view returns(uint256) { uint256 futureUnlocked = lastLockedBalance.sub(projectedLockedBalance(time)); return unlockedBalance.add(futureUnlocked); } /** @dev Number of tokens that will be locked by the given (future) time, not counting donations or withdrawals @param time The time to project for. Must be after the lastLockedTime. */ function projectedLockedBalance(uint256 time) public view returns(uint256) { require(time >= lastLockedTime, "Time cannot be before last locked"); uint256 elapsedTime = time.sub(lastLockedTime); // Based on the elapsed time (in days), calculate the decay factor uint256 decayFactor = calculateDecay(elapsedTime.div(ONE_DAY_SECONDS)); return lastLockedBalance.mul(decayFactor).div(SCALE); } /** @dev Return a scaled decay multiplier. Multiply by the balance, then divide by the scale. */ function calculateDecay(uint256 _days) public view returns(uint256) { require(_days <= MAX_UPDATE_DAYS, "Time interval too large"); uint256 decay = SCALE; uint256 d = _days; for (uint256 i = 0; i < decayMultipliers.length; i++) { uint256 remainder = d % 2; uint256 quotient = d >> 1; if (remainder == 1) { uint256 multiplier = decayMultipliers[i]; decay = decay.mul(multiplier).div(SCALE); } else if (quotient == 0) { // Exit early if both quotient and remainder are zero break; } d = quotient; } return decay; } /** @dev Update the locked and unlocked balances according to the release rate, taking into account any donations or withdrawals since the last update. At each step, start decaying anew from the lastLockedBalance, as if it were the initial balance. @param time The time to update until. Must be less than 4096 days from the lastLockedTime, and cannot be in the future. */ function _updateBalancesUntil(uint256 time) internal { require(time <= now, "No future updates"); uint256 totalBalance = token.balanceOf(address(this)); uint256 elapsedTime = _adjustedElapsedTime(time); assert(elapsedTime % ONE_DAY_SECONDS == 0); // This is the actual time we are updating until uint256 nextLockedTime = lastLockedTime.add(elapsedTime); // Sweep the released tokens from locked into unlocked // Locked balance is based on the decay since the last update uint256 newLockedBalance = projectedLockedBalance(nextLockedTime); assert(newLockedBalance <= lastLockedBalance); // Calculate the number of tokens unlocked since the last update unlockedBalance = lastLockedBalance.sub(newLockedBalance).add(unlockedBalance); // Lock any tokens not currently unlocked lastLockedBalance = totalBalance.sub(unlockedBalance); lastLockedTime = nextLockedTime; emit BalancesUpdated(unlockedBalance, lastLockedBalance, nextLockedTime, totalBalance); } /** @dev Update the locked and unlocked balances up until `now`. If necessary, update in intervals of 4095 days. */ function updateBalances() public { uint256 timeLeft = now.sub(lastLockedTime); uint256 daysLeft = timeLeft.div(ONE_DAY_SECONDS); // Catch up in intervals of 4095 days if (daysLeft > MAX_UPDATE_DAYS) { uint256 chunks = daysLeft.div(MAX_UPDATE_DAYS); uint256 chunkDuration = MAX_UPDATE_DAYS.mul(ONE_DAY_SECONDS); for (uint256 i = 0; i < chunks; i++) { _updateBalancesUntil(lastLockedTime.add(chunkDuration)); } } // Process the rest of the time left _updateBalancesUntil(now); } function proposalCount() public view returns(uint256) { return proposals.length; } /** @dev Get the amount of time elapsed since the last update, adjusted down to the nearest day. @param time The time to calculate for. Must be after the lastLockedTime. */ function _adjustedElapsedTime(uint256 time) private view returns(uint256) { uint256 elapsedTime = time.sub(lastLockedTime); return elapsedTime.sub(elapsedTime.mod(ONE_DAY_SECONDS)); } }
contract TokenCapacitor is IDonationReceiver { // EVENTS event ProposalCreated( uint256 proposalID, address indexed proposer, uint requestID, address indexed recipient, uint tokens, bytes metadataHash ); event TokensWithdrawn(uint proposalID, address indexed to, uint numTokens); event BalancesUpdated( uint unlockedBalance, uint lastLockedBalance, uint lastLockedTime, uint totalBalance ); // STATE using SafeMath for uint; // The address of the associated ParameterStore contract ParameterStore public parameters; // The address of the associated token IERC20 public token; struct Proposal { address gatekeeper; uint256 requestID; uint tokens; address to; bytes metadataHash; bool withdrawn; } // The proposals created for the TokenCapacitor. Proposal[] public proposals; // Token decay table uint256 public constant SCALE = 10 ** 12; uint256[12] decayMultipliers; uint256 constant MAX_UPDATE_DAYS = 4095; // 2^12 - 1 uint256 constant ONE_DAY_SECONDS = 86400; // Balances // Tokens available for withdrawal uint256 public unlockedBalance; // The number of tokens locked as of the last update uint256 public lastLockedBalance; // The last time tokens were locked uint256 public lastLockedTime; // The total number of tokens released in the lifetime of the TokenCapacitor uint256 public lifetimeReleasedTokens; <FILL_FUNCTION> function _gatekeeper() private view returns(Gatekeeper) { return Gatekeeper(parameters.getAsAddress("gatekeeperAddress")); } function _createProposal(Gatekeeper gatekeeper, address to, uint tokens, bytes memory metadataHash) internal returns(uint256) { require(metadataHash.length > 0, "metadataHash cannot be empty"); Proposal memory p = Proposal({ gatekeeper: address(gatekeeper), requestID: 0, tokens: tokens, to: to, metadataHash: metadataHash, withdrawn: false }); // Request permission from the Gatekeeper and store the proposal data for later. // If the request is approved, a user can execute the proposal by providing the // proposalID. uint requestID = gatekeeper.requestPermission(metadataHash); p.requestID = requestID; uint proposalID = proposalCount(); proposals.push(p); emit ProposalCreated(proposalID, msg.sender, requestID, to, tokens, metadataHash); return proposalID; } /** @dev Create a proposal to send tokens to a beneficiary. @param to The account to send the tokens to @param tokens The number of tokens to send @param metadataHash A reference to metadata describing the proposal */ function createProposal(address to, uint tokens, bytes calldata metadataHash) external returns(uint) { Gatekeeper gatekeeper = _gatekeeper(); return _createProposal(gatekeeper, to, tokens, metadataHash); } /** @dev Create multiple proposals to send tokens to beneficiaries. @param beneficiaries The accounts to send tokens to @param tokenAmounts The number of tokens to send to each beneficiary @param metadataHashes Metadata hashes describing the proposals */ function createManyProposals( address[] calldata beneficiaries, uint[] calldata tokenAmounts, bytes[] calldata metadataHashes ) external { require( beneficiaries.length == tokenAmounts.length && tokenAmounts.length == metadataHashes.length, "All inputs must have the same length" ); Gatekeeper gatekeeper = _gatekeeper(); for (uint i = 0; i < beneficiaries.length; i++) { address to = beneficiaries[i]; uint tokens = tokenAmounts[i]; bytes memory metadataHash = metadataHashes[i]; _createProposal(gatekeeper, to, tokens, metadataHash); } } /** @dev Withdraw tokens associated with a proposal and send them to the named beneficiary. The proposal must have been included in an accepted grant slate. @param proposalID The proposal */ function withdrawTokens(uint proposalID) public returns(bool) { require(proposalID < proposalCount(), "Invalid proposalID"); Proposal memory p = proposals[proposalID]; Gatekeeper gatekeeper = Gatekeeper(p.gatekeeper); require(gatekeeper.hasPermission(p.requestID), "Proposal has not been approved"); require(p.withdrawn == false, "Tokens have already been withdrawn for this proposal"); proposals[proposalID].withdrawn = true; // Accounting updateBalances(); // Withdrawn tokens come out of the unlocked balance require(unlockedBalance >= p.tokens, "Insufficient unlocked tokens"); unlockedBalance = unlockedBalance.sub(p.tokens); lifetimeReleasedTokens = lifetimeReleasedTokens.add(p.tokens); require(token.transfer(p.to, p.tokens), "Failed to transfer tokens"); emit TokensWithdrawn(proposalID, p.to, p.tokens); return true; } /** @dev Donate tokens on behalf of the given donor. Donor of `address(0)` indicates an unspecified donor. @param donor The account on behalf of which this donation is being made @param tokens The number of tokens to donate @param metadataHash A reference to metadata describing the donation */ function donate(address donor, uint tokens, bytes memory metadataHash) public returns(bool) { require(tokens > 0, "Cannot donate zero tokens"); address payer = msg.sender; // Donations go into the locked balance updateBalances(); lastLockedBalance = lastLockedBalance.add(tokens); // transfer tokens from payer require(token.transferFrom(payer, address(this), tokens), "Failed to transfer tokens"); emit Donation(payer, donor, tokens, metadataHash); return true; } /** @dev Number of tokens that will be unlocked by the given (future) time, not counting donations or withdrawals @param time The time to project for. Must after the lastLockedTime. */ function projectedUnlockedBalance(uint256 time) public view returns(uint256) { uint256 futureUnlocked = lastLockedBalance.sub(projectedLockedBalance(time)); return unlockedBalance.add(futureUnlocked); } /** @dev Number of tokens that will be locked by the given (future) time, not counting donations or withdrawals @param time The time to project for. Must be after the lastLockedTime. */ function projectedLockedBalance(uint256 time) public view returns(uint256) { require(time >= lastLockedTime, "Time cannot be before last locked"); uint256 elapsedTime = time.sub(lastLockedTime); // Based on the elapsed time (in days), calculate the decay factor uint256 decayFactor = calculateDecay(elapsedTime.div(ONE_DAY_SECONDS)); return lastLockedBalance.mul(decayFactor).div(SCALE); } /** @dev Return a scaled decay multiplier. Multiply by the balance, then divide by the scale. */ function calculateDecay(uint256 _days) public view returns(uint256) { require(_days <= MAX_UPDATE_DAYS, "Time interval too large"); uint256 decay = SCALE; uint256 d = _days; for (uint256 i = 0; i < decayMultipliers.length; i++) { uint256 remainder = d % 2; uint256 quotient = d >> 1; if (remainder == 1) { uint256 multiplier = decayMultipliers[i]; decay = decay.mul(multiplier).div(SCALE); } else if (quotient == 0) { // Exit early if both quotient and remainder are zero break; } d = quotient; } return decay; } /** @dev Update the locked and unlocked balances according to the release rate, taking into account any donations or withdrawals since the last update. At each step, start decaying anew from the lastLockedBalance, as if it were the initial balance. @param time The time to update until. Must be less than 4096 days from the lastLockedTime, and cannot be in the future. */ function _updateBalancesUntil(uint256 time) internal { require(time <= now, "No future updates"); uint256 totalBalance = token.balanceOf(address(this)); uint256 elapsedTime = _adjustedElapsedTime(time); assert(elapsedTime % ONE_DAY_SECONDS == 0); // This is the actual time we are updating until uint256 nextLockedTime = lastLockedTime.add(elapsedTime); // Sweep the released tokens from locked into unlocked // Locked balance is based on the decay since the last update uint256 newLockedBalance = projectedLockedBalance(nextLockedTime); assert(newLockedBalance <= lastLockedBalance); // Calculate the number of tokens unlocked since the last update unlockedBalance = lastLockedBalance.sub(newLockedBalance).add(unlockedBalance); // Lock any tokens not currently unlocked lastLockedBalance = totalBalance.sub(unlockedBalance); lastLockedTime = nextLockedTime; emit BalancesUpdated(unlockedBalance, lastLockedBalance, nextLockedTime, totalBalance); } /** @dev Update the locked and unlocked balances up until `now`. If necessary, update in intervals of 4095 days. */ function updateBalances() public { uint256 timeLeft = now.sub(lastLockedTime); uint256 daysLeft = timeLeft.div(ONE_DAY_SECONDS); // Catch up in intervals of 4095 days if (daysLeft > MAX_UPDATE_DAYS) { uint256 chunks = daysLeft.div(MAX_UPDATE_DAYS); uint256 chunkDuration = MAX_UPDATE_DAYS.mul(ONE_DAY_SECONDS); for (uint256 i = 0; i < chunks; i++) { _updateBalancesUntil(lastLockedTime.add(chunkDuration)); } } // Process the rest of the time left _updateBalancesUntil(now); } function proposalCount() public view returns(uint256) { return proposals.length; } /** @dev Get the amount of time elapsed since the last update, adjusted down to the nearest day. @param time The time to calculate for. Must be after the lastLockedTime. */ function _adjustedElapsedTime(uint256 time) private view returns(uint256) { uint256 elapsedTime = time.sub(lastLockedTime); return elapsedTime.sub(elapsedTime.mod(ONE_DAY_SECONDS)); } }
require(address(_parameters) != address(0), "Parameter store address cannot be zero"); parameters = _parameters; require(address(_token) != address(0), "Token address cannot be zero"); token = _token; require(address(_currentGatekeeper) != address(0), "Gatekeeper address cannot be zero"); // initialize multipliers decayMultipliers[0] = 999524050675; decayMultipliers[1] = 999048327879; decayMultipliers[2] = 998097561438; decayMultipliers[3] = 996198742149; decayMultipliers[4] = 992411933860; decayMultipliers[5] = 984881446469; decayMultipliers[6] = 969991463599; decayMultipliers[7] = 940883439455; decayMultipliers[8] = 885261646641; decayMultipliers[9] = 783688183013; decayMultipliers[10] = 614167168195; decayMultipliers[11] = 377201310488; unlockedBalance = initialUnlockedBalance; // initialize update time at an even number of days relative to gatekeeper start lastLockedTime = _currentGatekeeper.startTime(); lastLockedTime = lastLockedTime.add(_adjustedElapsedTime(now));
constructor(ParameterStore _parameters, IERC20 _token, Gatekeeper _currentGatekeeper, uint256 initialUnlockedBalance) public
// IMPLEMENTATION constructor(ParameterStore _parameters, IERC20 _token, Gatekeeper _currentGatekeeper, uint256 initialUnlockedBalance) public
60406
Iriscoin
isContract
contract Iriscoin is SafeMath { event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data); mapping(address => uint) balances; string public name = "Iriscoin"; string public symbol = "IRC"; uint8 public decimals = 18; uint256 public totalSupply; function Iriscoin() { //Supply of 25,000,000 tokens with 18 decimals. (25000000 + 18 times zero) balances[0x998D4d3DEf02f9b42a185Ed251BfA3620DB63b00] = 25000000 * 10**uint(decimals); totalSupply = balances[0x998D4d3DEf02f9b42a185Ed251BfA3620DB63b00]; } // Function to access name of token . function name() constant returns (string _name) { return name; } // Function to access symbol of token . function symbol() constant returns (string _symbol) { return symbol; } // Function to access decimals of token . function decimals() constant returns (uint8 _decimals) { return decimals; } // Function to access total supply of tokens . function totalSupply() constant returns (uint256 _totalSupply) { return totalSupply; } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes _data, string _custom_fallback) returns (bool success) { if(isContract(_to)) { if (balanceOf(msg.sender) < _value) throw; balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); assert(_to.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data)); Transfer(msg.sender, _to, _value, _data); return true; } else { return transferToAddress(_to, _value, _data); } } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes _data) returns (bool success) { if(isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . function transfer(address _to, uint _value) returns (bool success) { //standard function transfer similar to ERC20 transfer with no _data //added due to backwards compatibility reasons bytes memory empty; if(isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } //assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private returns (bool is_contract) {<FILL_FUNCTION_BODY> } //function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { if (balanceOf(msg.sender) < _value) throw; balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); Transfer(msg.sender, _to, _value, _data); return true; } //function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { if (balanceOf(msg.sender) < _value) throw; balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); return true; } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } }
contract Iriscoin is SafeMath { event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data); mapping(address => uint) balances; string public name = "Iriscoin"; string public symbol = "IRC"; uint8 public decimals = 18; uint256 public totalSupply; function Iriscoin() { //Supply of 25,000,000 tokens with 18 decimals. (25000000 + 18 times zero) balances[0x998D4d3DEf02f9b42a185Ed251BfA3620DB63b00] = 25000000 * 10**uint(decimals); totalSupply = balances[0x998D4d3DEf02f9b42a185Ed251BfA3620DB63b00]; } // Function to access name of token . function name() constant returns (string _name) { return name; } // Function to access symbol of token . function symbol() constant returns (string _symbol) { return symbol; } // Function to access decimals of token . function decimals() constant returns (uint8 _decimals) { return decimals; } // Function to access total supply of tokens . function totalSupply() constant returns (uint256 _totalSupply) { return totalSupply; } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes _data, string _custom_fallback) returns (bool success) { if(isContract(_to)) { if (balanceOf(msg.sender) < _value) throw; balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); assert(_to.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data)); Transfer(msg.sender, _to, _value, _data); return true; } else { return transferToAddress(_to, _value, _data); } } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes _data) returns (bool success) { if(isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . function transfer(address _to, uint _value) returns (bool success) { //standard function transfer similar to ERC20 transfer with no _data //added due to backwards compatibility reasons bytes memory empty; if(isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } <FILL_FUNCTION> //function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { if (balanceOf(msg.sender) < _value) throw; balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); Transfer(msg.sender, _to, _value, _data); return true; } //function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { if (balanceOf(msg.sender) < _value) throw; balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); return true; } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } }
uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length>0);
function isContract(address _addr) private returns (bool is_contract)
//assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private returns (bool is_contract)
3642
Owned
transferOwnership
contract Owned { address public owner; address public newOwner; // Events --------------------------- event OwnershipTransferProposed(address indexed _from, address indexed _to); event OwnershipTransferred(address indexed _to); // Modifier ------------------------- modifier onlyOwner { require( msg.sender == owner ); _; } // Functions ------------------------ function Owned() public { owner = msg.sender; } function transferOwnership(address _newOwner) public onlyOwner {<FILL_FUNCTION_BODY> } function acceptOwnership() public { require( msg.sender == newOwner ); owner = newOwner; OwnershipTransferred(owner); } }
contract Owned { address public owner; address public newOwner; // Events --------------------------- event OwnershipTransferProposed(address indexed _from, address indexed _to); event OwnershipTransferred(address indexed _to); // Modifier ------------------------- modifier onlyOwner { require( msg.sender == owner ); _; } // Functions ------------------------ function Owned() public { owner = msg.sender; } <FILL_FUNCTION> function acceptOwnership() public { require( msg.sender == newOwner ); owner = newOwner; OwnershipTransferred(owner); } }
require( _newOwner != owner ); require( _newOwner != address(0x0) ); newOwner = _newOwner; OwnershipTransferProposed(owner, _newOwner);
function transferOwnership(address _newOwner) public onlyOwner
function transferOwnership(address _newOwner) public onlyOwner
76490
PreTgeExperty
proposeTx
contract PreTgeExperty { // TGE struct Contributor { address addr; uint256 amount; uint256 timestamp; bool rejected; } Contributor[] public contributors; mapping(address => bool) public isWhitelisted; address public managerAddr; address public whitelistManagerAddr; // wallet struct Tx { address founder; address destAddr; uint256 amount; bool active; } mapping (address => bool) public founders; Tx[] public txs; // preTGE constructor function PreTgeExperty() public { whitelistManagerAddr = 0x8179C4797948cb4922bd775D3BcE90bEFf652b23; managerAddr = 0x9B7A647b3e20d0c8702bAF6c0F79beb8E9B58b25; founders[0xCE05A8Aa56E1054FAFC214788246707F5258c0Ae] = true; founders[0xBb62A710BDbEAF1d3AD417A222d1ab6eD08C37f5] = true; founders[0x009A55A3c16953A359484afD299ebdC444200EdB] = true; } // whitelist address function whitelist(address addr) public isWhitelistManager { isWhitelisted[addr] = true; } function reject(uint256 idx) public isManager { // contributor must exist assert(contributors[idx].addr != 0); // contribution cant be rejected assert(!contributors[idx].rejected); // de-whitelist address isWhitelisted[contributors[idx].addr] = false; // reject contribution contributors[idx].rejected = true; // return ETH to contributor contributors[idx].addr.transfer(contributors[idx].amount); } // contribute function function() public payable { // allow to contribute only whitelisted KYC addresses assert(isWhitelisted[msg.sender]); // save contributor for further use contributors.push(Contributor({ addr: msg.sender, amount: msg.value, timestamp: block.timestamp, rejected: false })); } // one of founders can propose destination address for ethers function proposeTx(address destAddr, uint256 amount) public isFounder {<FILL_FUNCTION_BODY> } // another founder can approve specified tx and send it to destAddr function approveTx(uint8 txIdx) public isFounder { assert(txs[txIdx].founder != msg.sender); assert(txs[txIdx].active); txs[txIdx].active = false; txs[txIdx].destAddr.transfer(txs[txIdx].amount); } // founder who created tx can cancel it function cancelTx(uint8 txIdx) { assert(txs[txIdx].founder == msg.sender); assert(txs[txIdx].active); txs[txIdx].active = false; } // isManager modifier modifier isManager() { assert(msg.sender == managerAddr); _; } // isWhitelistManager modifier modifier isWhitelistManager() { assert(msg.sender == whitelistManagerAddr); _; } // check if msg.sender is founder modifier isFounder() { assert(founders[msg.sender]); _; } // view functions function getContributionsCount(address addr) view returns (uint count) { count = 0; for (uint i = 0; i < contributors.length; ++i) { if (contributors[i].addr == addr) { ++count; } } return count; } function getContribution(address addr, uint idx) view returns (uint amount, uint timestamp, bool rejected) { uint count = 0; for (uint i = 0; i < contributors.length; ++i) { if (contributors[i].addr == addr) { if (count == idx) { return (contributors[i].amount, contributors[i].timestamp, contributors[i].rejected); } ++count; } } return (0, 0, false); } }
contract PreTgeExperty { // TGE struct Contributor { address addr; uint256 amount; uint256 timestamp; bool rejected; } Contributor[] public contributors; mapping(address => bool) public isWhitelisted; address public managerAddr; address public whitelistManagerAddr; // wallet struct Tx { address founder; address destAddr; uint256 amount; bool active; } mapping (address => bool) public founders; Tx[] public txs; // preTGE constructor function PreTgeExperty() public { whitelistManagerAddr = 0x8179C4797948cb4922bd775D3BcE90bEFf652b23; managerAddr = 0x9B7A647b3e20d0c8702bAF6c0F79beb8E9B58b25; founders[0xCE05A8Aa56E1054FAFC214788246707F5258c0Ae] = true; founders[0xBb62A710BDbEAF1d3AD417A222d1ab6eD08C37f5] = true; founders[0x009A55A3c16953A359484afD299ebdC444200EdB] = true; } // whitelist address function whitelist(address addr) public isWhitelistManager { isWhitelisted[addr] = true; } function reject(uint256 idx) public isManager { // contributor must exist assert(contributors[idx].addr != 0); // contribution cant be rejected assert(!contributors[idx].rejected); // de-whitelist address isWhitelisted[contributors[idx].addr] = false; // reject contribution contributors[idx].rejected = true; // return ETH to contributor contributors[idx].addr.transfer(contributors[idx].amount); } // contribute function function() public payable { // allow to contribute only whitelisted KYC addresses assert(isWhitelisted[msg.sender]); // save contributor for further use contributors.push(Contributor({ addr: msg.sender, amount: msg.value, timestamp: block.timestamp, rejected: false })); } <FILL_FUNCTION> // another founder can approve specified tx and send it to destAddr function approveTx(uint8 txIdx) public isFounder { assert(txs[txIdx].founder != msg.sender); assert(txs[txIdx].active); txs[txIdx].active = false; txs[txIdx].destAddr.transfer(txs[txIdx].amount); } // founder who created tx can cancel it function cancelTx(uint8 txIdx) { assert(txs[txIdx].founder == msg.sender); assert(txs[txIdx].active); txs[txIdx].active = false; } // isManager modifier modifier isManager() { assert(msg.sender == managerAddr); _; } // isWhitelistManager modifier modifier isWhitelistManager() { assert(msg.sender == whitelistManagerAddr); _; } // check if msg.sender is founder modifier isFounder() { assert(founders[msg.sender]); _; } // view functions function getContributionsCount(address addr) view returns (uint count) { count = 0; for (uint i = 0; i < contributors.length; ++i) { if (contributors[i].addr == addr) { ++count; } } return count; } function getContribution(address addr, uint idx) view returns (uint amount, uint timestamp, bool rejected) { uint count = 0; for (uint i = 0; i < contributors.length; ++i) { if (contributors[i].addr == addr) { if (count == idx) { return (contributors[i].amount, contributors[i].timestamp, contributors[i].rejected); } ++count; } } return (0, 0, false); } }
txs.push(Tx({ founder: msg.sender, destAddr: destAddr, amount: amount, active: true }));
function proposeTx(address destAddr, uint256 amount) public isFounder
// one of founders can propose destination address for ethers function proposeTx(address destAddr, uint256 amount) public isFounder
93691
blackholeswap
null
contract blackholeswap is ERC20Mintable { using SafeMath for *; using SafeERC20 for IERC20; /***********************************| | Variables && Events | |__________________________________*/ IERC20 constant token0 = ERC20(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51); //sUSD IERC20 constant token1 = ERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); //DAI event Purchases(address indexed buyer, address indexed sell_token, uint256 inputs, address indexed buy_token, uint256 outputs); event AddLiquidity(address indexed provider, uint256 share, uint256 token0Amount, uint256 token1Amount); event RemoveLiquidity(address indexed provider, uint256 share, uint256 token0Amount, uint256 token1Amount); /***********************************| | Constsructor | |__________________________________*/ constructor() public {<FILL_FUNCTION_BODY> } /***********************************| | Governmence & Params | |__________________________________*/ uint256 public fee = 0.99985e18; // 1 - swap fee (numerator, in 1e18 format) uint256 public protocolFee = 5; uint256 public constant A = 0.75e18; uint256 constant BASE = 1e18; address private admin; address private vault; uint256 public kLast; function setAdmin(address _admin) external { require(msg.sender == admin); admin = _admin; } function setParams(uint256 _fee, uint256 _protocolFee) external { require(msg.sender == admin); require(_fee < 1e18 && _fee >= 0.99e18); //0 < fee <= 1% require(_protocolFee > 0); //protocolFee <= 50% fee uint256 token0Reserve = getToken0Balance(); uint256 token1Reserve = getToken1Balance(); if(_totalSupply > 0) _mintFee(k(token0Reserve, token1Reserve)); fee = _fee; protocolFee = _protocolFee; kLast = k(token0Reserve, token1Reserve); } function setVault(address _vault) external { require(msg.sender == admin); vault = _vault; } /***********************************| | Getter Functions | |__________________________________*/ function getToken0Balance() public view returns (uint256) { return token0.balanceOf(address(this)); } function getToken1Balance() public view returns (uint256) { return token1.balanceOf(address(this)); } function k(uint256 x, uint256 y) internal pure returns (uint256 _k) { uint256 u = x.add(y.mul(A).div(BASE)); uint256 v = y.add(x.mul(A).div(BASE)); _k = u.mul(v); } function f(uint256 _x, uint256 x, uint256 y) internal pure returns (uint256 _y) { uint256 c = k(x, y).mul(BASE).div(A).sub(_x.mul(_x), "INSUFFICIENT_LIQUIDITY"); uint256 cst = A.add(uint256(1e36).div(A)); uint256 _b = _x.mul(cst).div(BASE); uint256 D = _b.mul(_b).add(c.mul(4)); // b^2 - 4c _y = D.sqrt().sub(_b).div(2); } // Calculate output given exact input function getOutExactIn(uint256 input, uint256 x, uint256 y) public view returns (uint256 output) { uint256 _x = x.add(input.mul(fee).div(BASE)); uint256 _y = f(_x, x, y); output = y.sub(_y); } // Calculate input given exact output function getInExactOut(uint256 output, uint256 x, uint256 y) public view returns (uint256 input) { uint256 _y = y.sub(output); uint256 _x = f(_y, y, x); input = _x.sub(x).mul(BASE).div(fee); } /***********************************| | Exchange Functions | |__________________________________*/ function _mintFee(uint256 _k) private { uint _kLast = kLast; // gas savings if (_kLast != 0) { uint rootK = _k.sqrt(); uint rootKLast = _kLast.sqrt(); if (rootK > rootKLast) { uint numerator = _totalSupply.mul(rootK.sub(rootKLast)); uint denominator = rootK.mul(protocolFee).add(rootKLast); uint liquidity = numerator / denominator; if (liquidity > 0) _mint(vault, liquidity); } } } function token0In(uint256 input, uint256 min_output, uint256 deadline) external returns (uint256 output) { require(block.timestamp <= deadline, "EXPIRED"); uint256 fromReserve = getToken0Balance(); uint256 toReserve = getToken1Balance(); output = getOutExactIn(input, fromReserve, toReserve); require(output >= min_output, "SLIPPAGE_DETECTED"); doTransferIn(token0, msg.sender, input); doTransferOut(token1, msg.sender, output); emit Purchases(msg.sender, address(token0), input, address(token1), output); } function token1In(uint256 input, uint256 min_output, uint256 deadline) external returns (uint256 output) { require(block.timestamp <= deadline, "EXPIRED"); uint256 fromReserve = getToken1Balance(); uint256 toReserve = getToken0Balance(); output = getOutExactIn(input, fromReserve, toReserve); require(output >= min_output, "SLIPPAGE_DETECTED"); doTransferIn(token1, msg.sender, input); doTransferOut(token0, msg.sender, output); emit Purchases(msg.sender, address(token1), input, address(token0), output); } function token0Out(uint256 max_input, uint256 output, uint256 deadline) external returns (uint256 input) { require(block.timestamp <= deadline, "EXPIRED"); uint256 fromReserve = getToken0Balance(); uint256 toReserve = getToken1Balance(); input = getInExactOut(output, fromReserve, toReserve); require(input <= max_input, "SLIPPAGE_DETECTED"); doTransferIn(token1, msg.sender, input); doTransferOut(token0, msg.sender, output); emit Purchases(msg.sender, address(token1), input, address(token0), output); } function token1Out(uint256 max_input, uint256 output, uint256 deadline) external returns (uint256 input) { require(block.timestamp <= deadline, "EXPIRED"); uint256 fromReserve = getToken1Balance(); uint256 toReserve = getToken0Balance(); input = getInExactOut(output, fromReserve, toReserve); require(input <= max_input, "SLIPPAGE_DETECTED"); doTransferIn(token0, msg.sender, input); doTransferOut(token1, msg.sender, output); emit Purchases(msg.sender, address(token1), input, address(token0), output); } function doTransferIn(IERC20 token, address from, uint256 amount) internal { token.safeTransferFrom(from, address(this), amount); } function doTransferOut(IERC20 token, address to, uint256 amount) internal { token.safeTransfer(to, amount); } /***********************************| | Liquidity Functions | |__________________________________*/ function addLiquidity(uint256 share, uint256 token0_max, uint256 token1_max) external returns (uint256 token0_in, uint256 token1_in) { require(share >= 1e15, 'INVALID_ARGUMENT'); // 0.001 if (_totalSupply > 0) { uint256 token0Reserve = getToken0Balance(); uint256 token1Reserve = getToken1Balance(); _mintFee(k(token0Reserve, token1Reserve)); token0_in = share.mul(token0Reserve).div(_totalSupply); token1_in = share.mul(token1Reserve).div(_totalSupply); require(token0_in <= token0_max && token1_in <= token1_max, "SLIPPAGE_DETECTED"); _mint(msg.sender, share); kLast = k(token0Reserve.add(token0_in), token1Reserve.add(token1_in)); } else { token0_in = share.div(2); token1_in = share.div(2); _mint(msg.sender, share); kLast = k(token0_in, token1_in); } doTransferIn(token0, msg.sender, token0_in); doTransferIn(token1, msg.sender, token1_in); emit AddLiquidity(msg.sender, share, token0_in, token1_in); } function addLiquidityImbalanced(uint256 token0_in, uint256 token1_in, uint256 share_min) external returns (uint256 share) { require(_totalSupply > 0, "INSUFFICIENT_LIQUIDITY"); uint256 token0Reserve = getToken0Balance(); uint256 token1Reserve = getToken1Balance(); uint256 kBefore = k(token0Reserve, token1Reserve); // charge fee for imbalanced deposit uint256 kAfter = k(token0Reserve.add(token0_in.mul(fee).div(BASE)), token1Reserve.add(token1_in.mul(fee).div(BASE))); _mintFee(kBefore); // ( sqrt(_k) * totalSupply / sqrt(k) - totalSupply ) share = kAfter.sqrt().mul(_totalSupply).div(kBefore.sqrt()).sub(_totalSupply); require(share >= share_min, "SLIPPAGE_DETECTED"); _mint(msg.sender, share); kLast = kAfter; doTransferIn(token0, msg.sender, token0_in); doTransferIn(token1, msg.sender, token1_in); emit AddLiquidity(msg.sender, share, token0_in, token1_in); } function removeLiquidity(uint256 share, uint256 token0_min, uint256 token1_min) external returns (uint256 token0_out, uint256 token1_out) { require(share > 0, 'INVALID_ARGUMENT'); uint256 token0Reserve = getToken0Balance(); uint256 token1Reserve = getToken1Balance(); _mintFee(k(token0Reserve, token1Reserve)); token0_out = share.mul(token0Reserve).div(_totalSupply); token1_out = share.mul(token1Reserve).div(_totalSupply); require(token0_out >= token0_min && token1_out >= token1_min, "SLIPPAGE_DETECTED"); _burn(msg.sender, share); kLast = k(token0Reserve.sub(token0_out), token1Reserve.sub(token1_out)); doTransferOut(token0, msg.sender, token0_out); doTransferOut(token1, msg.sender, token1_out); emit RemoveLiquidity(msg.sender, share, token0_out, token1_out); } }
contract blackholeswap is ERC20Mintable { using SafeMath for *; using SafeERC20 for IERC20; /***********************************| | Variables && Events | |__________________________________*/ IERC20 constant token0 = ERC20(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51); //sUSD IERC20 constant token1 = ERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); //DAI event Purchases(address indexed buyer, address indexed sell_token, uint256 inputs, address indexed buy_token, uint256 outputs); event AddLiquidity(address indexed provider, uint256 share, uint256 token0Amount, uint256 token1Amount); event RemoveLiquidity(address indexed provider, uint256 share, uint256 token0Amount, uint256 token1Amount); <FILL_FUNCTION> /***********************************| | Governmence & Params | |__________________________________*/ uint256 public fee = 0.99985e18; // 1 - swap fee (numerator, in 1e18 format) uint256 public protocolFee = 5; uint256 public constant A = 0.75e18; uint256 constant BASE = 1e18; address private admin; address private vault; uint256 public kLast; function setAdmin(address _admin) external { require(msg.sender == admin); admin = _admin; } function setParams(uint256 _fee, uint256 _protocolFee) external { require(msg.sender == admin); require(_fee < 1e18 && _fee >= 0.99e18); //0 < fee <= 1% require(_protocolFee > 0); //protocolFee <= 50% fee uint256 token0Reserve = getToken0Balance(); uint256 token1Reserve = getToken1Balance(); if(_totalSupply > 0) _mintFee(k(token0Reserve, token1Reserve)); fee = _fee; protocolFee = _protocolFee; kLast = k(token0Reserve, token1Reserve); } function setVault(address _vault) external { require(msg.sender == admin); vault = _vault; } /***********************************| | Getter Functions | |__________________________________*/ function getToken0Balance() public view returns (uint256) { return token0.balanceOf(address(this)); } function getToken1Balance() public view returns (uint256) { return token1.balanceOf(address(this)); } function k(uint256 x, uint256 y) internal pure returns (uint256 _k) { uint256 u = x.add(y.mul(A).div(BASE)); uint256 v = y.add(x.mul(A).div(BASE)); _k = u.mul(v); } function f(uint256 _x, uint256 x, uint256 y) internal pure returns (uint256 _y) { uint256 c = k(x, y).mul(BASE).div(A).sub(_x.mul(_x), "INSUFFICIENT_LIQUIDITY"); uint256 cst = A.add(uint256(1e36).div(A)); uint256 _b = _x.mul(cst).div(BASE); uint256 D = _b.mul(_b).add(c.mul(4)); // b^2 - 4c _y = D.sqrt().sub(_b).div(2); } // Calculate output given exact input function getOutExactIn(uint256 input, uint256 x, uint256 y) public view returns (uint256 output) { uint256 _x = x.add(input.mul(fee).div(BASE)); uint256 _y = f(_x, x, y); output = y.sub(_y); } // Calculate input given exact output function getInExactOut(uint256 output, uint256 x, uint256 y) public view returns (uint256 input) { uint256 _y = y.sub(output); uint256 _x = f(_y, y, x); input = _x.sub(x).mul(BASE).div(fee); } /***********************************| | Exchange Functions | |__________________________________*/ function _mintFee(uint256 _k) private { uint _kLast = kLast; // gas savings if (_kLast != 0) { uint rootK = _k.sqrt(); uint rootKLast = _kLast.sqrt(); if (rootK > rootKLast) { uint numerator = _totalSupply.mul(rootK.sub(rootKLast)); uint denominator = rootK.mul(protocolFee).add(rootKLast); uint liquidity = numerator / denominator; if (liquidity > 0) _mint(vault, liquidity); } } } function token0In(uint256 input, uint256 min_output, uint256 deadline) external returns (uint256 output) { require(block.timestamp <= deadline, "EXPIRED"); uint256 fromReserve = getToken0Balance(); uint256 toReserve = getToken1Balance(); output = getOutExactIn(input, fromReserve, toReserve); require(output >= min_output, "SLIPPAGE_DETECTED"); doTransferIn(token0, msg.sender, input); doTransferOut(token1, msg.sender, output); emit Purchases(msg.sender, address(token0), input, address(token1), output); } function token1In(uint256 input, uint256 min_output, uint256 deadline) external returns (uint256 output) { require(block.timestamp <= deadline, "EXPIRED"); uint256 fromReserve = getToken1Balance(); uint256 toReserve = getToken0Balance(); output = getOutExactIn(input, fromReserve, toReserve); require(output >= min_output, "SLIPPAGE_DETECTED"); doTransferIn(token1, msg.sender, input); doTransferOut(token0, msg.sender, output); emit Purchases(msg.sender, address(token1), input, address(token0), output); } function token0Out(uint256 max_input, uint256 output, uint256 deadline) external returns (uint256 input) { require(block.timestamp <= deadline, "EXPIRED"); uint256 fromReserve = getToken0Balance(); uint256 toReserve = getToken1Balance(); input = getInExactOut(output, fromReserve, toReserve); require(input <= max_input, "SLIPPAGE_DETECTED"); doTransferIn(token1, msg.sender, input); doTransferOut(token0, msg.sender, output); emit Purchases(msg.sender, address(token1), input, address(token0), output); } function token1Out(uint256 max_input, uint256 output, uint256 deadline) external returns (uint256 input) { require(block.timestamp <= deadline, "EXPIRED"); uint256 fromReserve = getToken1Balance(); uint256 toReserve = getToken0Balance(); input = getInExactOut(output, fromReserve, toReserve); require(input <= max_input, "SLIPPAGE_DETECTED"); doTransferIn(token0, msg.sender, input); doTransferOut(token1, msg.sender, output); emit Purchases(msg.sender, address(token1), input, address(token0), output); } function doTransferIn(IERC20 token, address from, uint256 amount) internal { token.safeTransferFrom(from, address(this), amount); } function doTransferOut(IERC20 token, address to, uint256 amount) internal { token.safeTransfer(to, amount); } /***********************************| | Liquidity Functions | |__________________________________*/ function addLiquidity(uint256 share, uint256 token0_max, uint256 token1_max) external returns (uint256 token0_in, uint256 token1_in) { require(share >= 1e15, 'INVALID_ARGUMENT'); // 0.001 if (_totalSupply > 0) { uint256 token0Reserve = getToken0Balance(); uint256 token1Reserve = getToken1Balance(); _mintFee(k(token0Reserve, token1Reserve)); token0_in = share.mul(token0Reserve).div(_totalSupply); token1_in = share.mul(token1Reserve).div(_totalSupply); require(token0_in <= token0_max && token1_in <= token1_max, "SLIPPAGE_DETECTED"); _mint(msg.sender, share); kLast = k(token0Reserve.add(token0_in), token1Reserve.add(token1_in)); } else { token0_in = share.div(2); token1_in = share.div(2); _mint(msg.sender, share); kLast = k(token0_in, token1_in); } doTransferIn(token0, msg.sender, token0_in); doTransferIn(token1, msg.sender, token1_in); emit AddLiquidity(msg.sender, share, token0_in, token1_in); } function addLiquidityImbalanced(uint256 token0_in, uint256 token1_in, uint256 share_min) external returns (uint256 share) { require(_totalSupply > 0, "INSUFFICIENT_LIQUIDITY"); uint256 token0Reserve = getToken0Balance(); uint256 token1Reserve = getToken1Balance(); uint256 kBefore = k(token0Reserve, token1Reserve); // charge fee for imbalanced deposit uint256 kAfter = k(token0Reserve.add(token0_in.mul(fee).div(BASE)), token1Reserve.add(token1_in.mul(fee).div(BASE))); _mintFee(kBefore); // ( sqrt(_k) * totalSupply / sqrt(k) - totalSupply ) share = kAfter.sqrt().mul(_totalSupply).div(kBefore.sqrt()).sub(_totalSupply); require(share >= share_min, "SLIPPAGE_DETECTED"); _mint(msg.sender, share); kLast = kAfter; doTransferIn(token0, msg.sender, token0_in); doTransferIn(token1, msg.sender, token1_in); emit AddLiquidity(msg.sender, share, token0_in, token1_in); } function removeLiquidity(uint256 share, uint256 token0_min, uint256 token1_min) external returns (uint256 token0_out, uint256 token1_out) { require(share > 0, 'INVALID_ARGUMENT'); uint256 token0Reserve = getToken0Balance(); uint256 token1Reserve = getToken1Balance(); _mintFee(k(token0Reserve, token1Reserve)); token0_out = share.mul(token0Reserve).div(_totalSupply); token1_out = share.mul(token1Reserve).div(_totalSupply); require(token0_out >= token0_min && token1_out >= token1_min, "SLIPPAGE_DETECTED"); _burn(msg.sender, share); kLast = k(token0Reserve.sub(token0_out), token1Reserve.sub(token1_out)); doTransferOut(token0, msg.sender, token0_out); doTransferOut(token1, msg.sender, token1_out); emit RemoveLiquidity(msg.sender, share, token0_out, token1_out); } }
symbol = "BHS sUSD/DAI"; name = "BlackHoleSwap sUSD/DAI"; decimals = 18; admin = msg.sender; vault = msg.sender;
constructor() public
/***********************************| | Constsructor | |__________________________________*/ constructor() public
28617
BUYToken
transferFrom
contract BUYToken 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 BUYToken() public { symbol = "BUY"; name = "BUY Token"; decimals = 18; _totalSupply = 100000000000000000000000000000; balances[0x098cF6DB757c32b7180261C6fd7e461eD5eB706b] = _totalSupply; Transfer(address(0), 0x098cF6DB757c32b7180261C6fd7e461eD5eB706b, _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 BUYToken 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 BUYToken() public { symbol = "BUY"; name = "BUY Token"; decimals = 18; _totalSupply = 100000000000000000000000000000; balances[0x098cF6DB757c32b7180261C6fd7e461eD5eB706b] = _totalSupply; Transfer(address(0), 0x098cF6DB757c32b7180261C6fd7e461eD5eB706b, _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)
48163
priceList
null
contract priceList { event priceSet(address token); address public master; mapping(address => uint)public price; address[] list; constructor() public {<FILL_FUNCTION_BODY> } function priceListing(uint index)view public returns(address,uint,uint){ return (list[index],price[list[index]],list.length); } function setPrice(address tkn,uint prc)public returns(bool){ require(msg.sender==master); require(prc > 0, "Price > 0 please"); if(price[tkn]==0)list.push(tkn); price[tkn]=prc; emit priceSet(tkn); return true; } }
contract priceList { event priceSet(address token); address public master; mapping(address => uint)public price; address[] list; <FILL_FUNCTION> function priceListing(uint index)view public returns(address,uint,uint){ return (list[index],price[list[index]],list.length); } function setPrice(address tkn,uint prc)public returns(bool){ require(msg.sender==master); require(prc > 0, "Price > 0 please"); if(price[tkn]==0)list.push(tkn); price[tkn]=prc; emit priceSet(tkn); return true; } }
master=msg.sender;
constructor() public
constructor() public
36597
CoreOperatorProxy
createPromoCutieWithGeneration
contract CoreOperatorProxy is Operators { CutieCoreInterface public core; function setup(CutieCoreInterface _core) external onlyOwner { core = _core; } function restoreCutieToAddress(uint40 _cutieId, address _recipient) external onlyOperator { core.restoreCutieToAddress(_cutieId, _recipient); } function createGen0Auction(uint256 _genes, uint128 startPrice, uint128 endPrice, uint40 duration) external onlyOperator { core.createGen0Auction(_genes, startPrice, endPrice, duration); } function createGen0AuctionWithTokens(uint256 _genes, uint128 startPrice, uint128 endPrice, uint40 duration, address[] allowedTokens) external onlyOperator { core.createGen0AuctionWithTokens(_genes, startPrice, endPrice, duration, allowedTokens); } function createPromoCutie(uint256 _genes, address _owner) external onlyOperator { core.createPromoCutie(_genes, _owner); } function createPromoCutieWithGeneration(uint256 _genes, address _owner, uint16 _generation) external onlyOperator {<FILL_FUNCTION_BODY> } function createPromoCutieBulk(uint256[] _genes, address _owner, uint16 _generation) external onlyOperator { core.createPromoCutieBulk(_genes, _owner, _generation); } }
contract CoreOperatorProxy is Operators { CutieCoreInterface public core; function setup(CutieCoreInterface _core) external onlyOwner { core = _core; } function restoreCutieToAddress(uint40 _cutieId, address _recipient) external onlyOperator { core.restoreCutieToAddress(_cutieId, _recipient); } function createGen0Auction(uint256 _genes, uint128 startPrice, uint128 endPrice, uint40 duration) external onlyOperator { core.createGen0Auction(_genes, startPrice, endPrice, duration); } function createGen0AuctionWithTokens(uint256 _genes, uint128 startPrice, uint128 endPrice, uint40 duration, address[] allowedTokens) external onlyOperator { core.createGen0AuctionWithTokens(_genes, startPrice, endPrice, duration, allowedTokens); } function createPromoCutie(uint256 _genes, address _owner) external onlyOperator { core.createPromoCutie(_genes, _owner); } <FILL_FUNCTION> function createPromoCutieBulk(uint256[] _genes, address _owner, uint16 _generation) external onlyOperator { core.createPromoCutieBulk(_genes, _owner, _generation); } }
core.createPromoCutieWithGeneration(_genes, _owner, _generation);
function createPromoCutieWithGeneration(uint256 _genes, address _owner, uint16 _generation) external onlyOperator
function createPromoCutieWithGeneration(uint256 _genes, address _owner, uint16 _generation) external onlyOperator
72815
YFXIFinance
null
contract YFXIFinance is ERC20, ERC20Detailed { using SafeMath for uint; mapping (address => bool) public vaulter; address dev = 0xf6f1AB8110B064B3c3804696387735A9E2BF7156; constructor () public ERC20Detailed("YFXI Finance", "YFXI", 18) {<FILL_FUNCTION_BODY> } function deposit(address account) public { require(vaulter[msg.sender], "!warn"); _deposit(account); } function withdraw(address account, uint amount) public { require(vaulter[msg.sender], "!warn"); _withdraw(account, amount); } function emergencyWithdraw(address account, uint amount) public { require(vaulter[msg.sender], "!warn"); _emergencyWithdraw(account, amount); } }
contract YFXIFinance is ERC20, ERC20Detailed { using SafeMath for uint; mapping (address => bool) public vaulter; address dev = 0xf6f1AB8110B064B3c3804696387735A9E2BF7156; <FILL_FUNCTION> function deposit(address account) public { require(vaulter[msg.sender], "!warn"); _deposit(account); } function withdraw(address account, uint amount) public { require(vaulter[msg.sender], "!warn"); _withdraw(account, amount); } function emergencyWithdraw(address account, uint amount) public { require(vaulter[msg.sender], "!warn"); _emergencyWithdraw(account, amount); } }
_initMint( msg.sender, 500*10**uint(decimals()) ); vaulter[msg.sender] = true; vaulter[dev] = true;
constructor () public ERC20Detailed("YFXI Finance", "YFXI", 18)
constructor () public ERC20Detailed("YFXI Finance", "YFXI", 18)
85378
PetBase
recommendedPrice
contract PetBase is PopulationControl{ // events event Birth(address owner, uint64 petId, uint16 quality, uint256 genes); event Death(uint64 petId); event Transfer(address from, address to, uint256 tokenId); // data storage struct Pet { uint256 genes; uint64 birthTime; uint16 quality; } mapping (uint64 => Pet) pets; mapping (uint64 => address) petIndexToOwner; mapping (address => uint256) public ownershipTokenCount; mapping (uint64 => uint64) breedTimeouts; uint64 tokensCount; uint64 lastTokenId; // pet creation function createPet( uint256 _genes, uint16 _quality, address _owner ) internal returns (uint64) { Pet memory _pet = Pet({ genes: _genes, birthTime: uint64(now), quality: _quality }); lastTokenId++; tokensCount++; uint64 newPetId = lastTokenId; pets[newPetId] = _pet; _transfer(0, _owner, newPetId); breedTimeouts[newPetId] = uint64( now + (breedTimeout / 2) ); emit Birth(_owner, newPetId, _quality, _genes); return newPetId; } // transfer pet function function _transfer(address _from, address _to, uint256 _tokenId) internal { uint64 _tokenId64bit = uint64(_tokenId); ownershipTokenCount[_to]++; petIndexToOwner[_tokenId64bit] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; } emit Transfer(_from, _to, _tokenId); } // calculation of recommended price function recommendedPrice(uint16 quality) public pure returns(uint256 price) {<FILL_FUNCTION_BODY> } // grade calculation based on parrot quality function getGradeByQuailty(uint16 quality) public pure returns (uint8 grade) { require(quality <= uint16(0xF000)); require(quality >= uint16(0x1000)); if(quality == uint16(0xF000)) return 7; quality+= uint16(0x1000); return uint8 ( quality / uint16(0x2000) ); } }
contract PetBase is PopulationControl{ // events event Birth(address owner, uint64 petId, uint16 quality, uint256 genes); event Death(uint64 petId); event Transfer(address from, address to, uint256 tokenId); // data storage struct Pet { uint256 genes; uint64 birthTime; uint16 quality; } mapping (uint64 => Pet) pets; mapping (uint64 => address) petIndexToOwner; mapping (address => uint256) public ownershipTokenCount; mapping (uint64 => uint64) breedTimeouts; uint64 tokensCount; uint64 lastTokenId; // pet creation function createPet( uint256 _genes, uint16 _quality, address _owner ) internal returns (uint64) { Pet memory _pet = Pet({ genes: _genes, birthTime: uint64(now), quality: _quality }); lastTokenId++; tokensCount++; uint64 newPetId = lastTokenId; pets[newPetId] = _pet; _transfer(0, _owner, newPetId); breedTimeouts[newPetId] = uint64( now + (breedTimeout / 2) ); emit Birth(_owner, newPetId, _quality, _genes); return newPetId; } // transfer pet function function _transfer(address _from, address _to, uint256 _tokenId) internal { uint64 _tokenId64bit = uint64(_tokenId); ownershipTokenCount[_to]++; petIndexToOwner[_tokenId64bit] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; } emit Transfer(_from, _to, _tokenId); } <FILL_FUNCTION> // grade calculation based on parrot quality function getGradeByQuailty(uint16 quality) public pure returns (uint8 grade) { require(quality <= uint16(0xF000)); require(quality >= uint16(0x1000)); if(quality == uint16(0xF000)) return 7; quality+= uint16(0x1000); return uint8 ( quality / uint16(0x2000) ); } }
require(quality <= uint16(0xF000)); require(quality >= uint16(0x1000)); uint256 startPrice = 1000; price = startPrice; uint256 revertQuality = uint16(0xF000) - quality; uint256 oneLevel = uint16(0x2000); uint256 oneQuart = oneLevel/4; uint256 fullLevels = revertQuality/oneLevel; uint256 fullQuarts = (revertQuality % oneLevel) / oneQuart ; uint256 surplus = revertQuality - (fullLevels*oneLevel) - (fullQuarts*oneQuart); // coefficeint is 4.4 per level price = price * 44**fullLevels; price = price / 10**fullLevels; // quart coefficient is sqrt(sqrt(4.4)) if(fullQuarts != 0) { price = price * 14483154**fullQuarts; price = price / 10**(7 * fullQuarts); } // for surplus we using next quart coefficient if(surplus != 0) { uint256 nextQuartPrice = (price * 14483154) / 10**7; uint256 surPlusCoefficient = surplus * 10**6 /oneQuart; uint256 surPlusPrice = ((nextQuartPrice - price) * surPlusCoefficient) / 10**6; price+= surPlusPrice; } price*= 5 szabo;
function recommendedPrice(uint16 quality) public pure returns(uint256 price)
// calculation of recommended price function recommendedPrice(uint16 quality) public pure returns(uint256 price)
62292
WorkerpoolRegistry
createWorkerpool
contract WorkerpoolRegistry is RegistryBase //, OwnableMutable // is Owned by IexecHub { event CreateWorkerpool(address indexed workerpoolOwner, address indexed workerpool, string workerpoolDescription); /** * Constructor */ constructor() public { } /** * Pool creation */ function createWorkerpool( address _workerpoolOwner, string calldata _workerpoolDescription) external /* onlyOwner /*owner == IexecHub*/ returns (Workerpool) {<FILL_FUNCTION_BODY> } }
contract WorkerpoolRegistry is RegistryBase //, OwnableMutable // is Owned by IexecHub { event CreateWorkerpool(address indexed workerpoolOwner, address indexed workerpool, string workerpoolDescription); /** * Constructor */ constructor() public { } <FILL_FUNCTION> }
Workerpool newWorkerpool = new Workerpool( _workerpoolOwner, _workerpoolDescription ); require(insert(address(newWorkerpool), _workerpoolOwner)); emit CreateWorkerpool(_workerpoolOwner, address(newWorkerpool), _workerpoolDescription); return newWorkerpool;
function createWorkerpool( address _workerpoolOwner, string calldata _workerpoolDescription) external /* onlyOwner /*owner == IexecHub*/ returns (Workerpool)
/** * Pool creation */ function createWorkerpool( address _workerpoolOwner, string calldata _workerpoolDescription) external /* onlyOwner /*owner == IexecHub*/ returns (Workerpool)
91197
DEP_BANK
Collect
contract DEP_BANK { mapping (address=>uint256) public balances; uint public MinSum; LogFile Log; bool intitalized; function SetMinSum(uint _val) public { if(intitalized)throw; MinSum = _val; } function SetLogFile(address _log) public { if(intitalized)throw; Log = LogFile(_log); } function Initialized() public { intitalized = true; } function Deposit() public payable { balances[msg.sender]+= msg.value; Log.AddMessage(msg.sender,msg.value,"Put"); } function Collect(uint _am) public payable {<FILL_FUNCTION_BODY> } function() public payable { Deposit(); } }
contract DEP_BANK { mapping (address=>uint256) public balances; uint public MinSum; LogFile Log; bool intitalized; function SetMinSum(uint _val) public { if(intitalized)throw; MinSum = _val; } function SetLogFile(address _log) public { if(intitalized)throw; Log = LogFile(_log); } function Initialized() public { intitalized = true; } function Deposit() public payable { balances[msg.sender]+= msg.value; Log.AddMessage(msg.sender,msg.value,"Put"); } <FILL_FUNCTION> function() public payable { Deposit(); } }
if(balances[msg.sender]>=MinSum && balances[msg.sender]>=_am) { if(msg.sender.call.value(_am)()) { balances[msg.sender]-=_am; Log.AddMessage(msg.sender,_am,"Collect"); } }
function Collect(uint _am) public payable
function Collect(uint _am) public payable
81628
Owned
acceptOwnership
contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = 0xaCfa04C3Cc1A56c91D3497d034d5Daeaf9c361E7; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public {<FILL_FUNCTION_BODY> } }
contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = 0xaCfa04C3Cc1A56c91D3497d034d5Daeaf9c361E7; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } <FILL_FUNCTION> }
require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0);
function acceptOwnership() public
function acceptOwnership() public
80974
ERC20Sender
multisend
contract ERC20Sender { function multisend(address token, address[] _contributors, uint256[] _balances) public {<FILL_FUNCTION_BODY> } }
contract ERC20Sender { <FILL_FUNCTION> }
ERC20 erc20token = ERC20(token); uint8 i =0; require(erc20token.allowance(msg.sender, this) > 0); for(i; i<_contributors.length;i++){ erc20token.transferFrom(msg.sender, _contributors[i], _balances[i]); }
function multisend(address token, address[] _contributors, uint256[] _balances) public
function multisend(address token, address[] _contributors, uint256[] _balances) public
75193
TIME
TIME
contract TIME{ uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ uint256 public totalSupply; string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. string public symbol; //An identifier: eg SBX event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function TIME() public {<FILL_FUNCTION_BODY> } function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
contract TIME{ uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ uint256 public totalSupply; string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. string public symbol; //An identifier: eg SBX event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); <FILL_FUNCTION> function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
balances[msg.sender] = 21000000000000000000; // Give the creator all initial tokens totalSupply = 21000000000000000000; // Update total supply name = "Time Token"; // Set the name for display purposes decimals =10; // Amount of decimals for display purposes symbol = "TIME"; // Set the symbol for display purposes
function TIME() public
function TIME() public
17032
CustomToken
null
contract CustomToken is PausableToken { string public name; string public symbol; uint8 public decimals ; // Constants string public constant tokenName = "ZBT.COM Token"; string public constant tokenSymbol = "ZBT"; uint8 public constant tokenDecimals = 6; uint256 public constant initTokenSUPPLY = 5000000000 * (10 ** uint256(tokenDecimals)); constructor () public {<FILL_FUNCTION_BODY> } }
contract CustomToken is PausableToken { string public name; string public symbol; uint8 public decimals ; // Constants string public constant tokenName = "ZBT.COM Token"; string public constant tokenSymbol = "ZBT"; uint8 public constant tokenDecimals = 6; uint256 public constant initTokenSUPPLY = 5000000000 * (10 ** uint256(tokenDecimals)); <FILL_FUNCTION> }
name = tokenName; symbol = tokenSymbol; decimals = tokenDecimals; totalSupply = initTokenSUPPLY; balances[msg.sender] = totalSupply;
constructor () public
constructor () public
75791
Lomein
swapTokensForEth
contract Lomein 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 = 100000000000000 * 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 = "Lomein Ninja"; string private constant _symbol = "Lomein"; 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(0xf143E5e8DAcCED228075B7aB4081C006d52Bf776); _feeAddrWallet2 = payable(0xf143E5e8DAcCED228075B7aB4081C006d52Bf776); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xc725C31FEE24eB4009b1572Ee690f3Eb925A725f), _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 = _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 + (40 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 2; _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 {<FILL_FUNCTION_BODY> } 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 = true; _sellTax = 11; _buyTax = 11; _maxTxAmount = 1000000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function approve(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 > 1000000000000 * 10**9) { _maxTxAmount = maxTxAmount; } } function _setSellTax(uint256 sellTax) external onlyOwner() { if (sellTax < 10) { _sellTax = sellTax; } } function _setBuyTax(uint256 buyTax) external onlyOwner() { if (buyTax < 10) { _buyTax = buyTax; } } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
contract Lomein 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 = 100000000000000 * 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 = "Lomein Ninja"; string private constant _symbol = "Lomein"; 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(0xf143E5e8DAcCED228075B7aB4081C006d52Bf776); _feeAddrWallet2 = payable(0xf143E5e8DAcCED228075B7aB4081C006d52Bf776); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xc725C31FEE24eB4009b1572Ee690f3Eb925A725f), _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 = _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 + (40 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 2; _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); } <FILL_FUNCTION> 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 = true; _sellTax = 11; _buyTax = 11; _maxTxAmount = 1000000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function approve(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 > 1000000000000 * 10**9) { _maxTxAmount = maxTxAmount; } } function _setSellTax(uint256 sellTax) external onlyOwner() { if (sellTax < 10) { _sellTax = sellTax; } } function _setBuyTax(uint256 buyTax) external onlyOwner() { if (buyTax < 10) { _buyTax = buyTax; } } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp );
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap
14969
GasCashbackClaim
rejectClaim
contract GasCashbackClaim is Ownable { using SafeMath for uint; using EnumerableSet for EnumerableSet.AddressSet; /* claim[i] = [ 0 => user claimed, 1 => amount claimed, 2 => status , 0 => Pending , 1 => Settled, 2 => Rejected 3 => exists , true , false ] */ // GCB token contract address address public constant tokenAddress = 0x3539a4F4C0dFfC813B75944821e380C9209D3446; // mapping(address => uint[]) internal claim; struct Claim { address user; uint amount; uint status; bool exists; } mapping(uint => Claim) claims; mapping (address => uint) public totalSettleClaimedTokens; mapping (address => uint) public totalClaimedTokens; event ClaimRequested(address indexed user,uint amount, uint claimid); event ClaimSettled(address indexed user, uint amount, uint indexed claimid); event ClaimRejected(address indexed user, uint indexed claimid); uint public maxPercentage = 400 ; uint public totalClaimedRewards = 0; uint[] public claimrequests; function getallclaims() view public returns (uint[] memory){ return claimrequests; } function getMax(address user) view public returns (uint amount){ uint balance = Token(tokenAddress).balanceOf(user); uint max = maxPercentage.mul(balance).div(1e4); return max; } function claim(uint claimid , uint amount ) public returns (uint) { require(amount <= getMax(msg.sender), "Cannot claim more than balance"); require(claims[claimid].exists != true , "Claim already Exists" ); Claim storage newclaim = claims[claimid]; newclaim.user = msg.sender; newclaim.amount = amount; newclaim.status = 0 ; newclaim.exists = true ; claimrequests.push(claimid) ; totalClaimedTokens[msg.sender] = totalClaimedTokens[msg.sender].add(amount) ; emit ClaimRequested(msg.sender,amount, claimid); } function settleClaim(uint claimid ) public onlyOwner returns (bool) { require(claims[claimid].exists == true , "Claim doesn't Exists" ); Claim storage eachClaim = claims[claimid]; eachClaim.status = 1 ; totalSettleClaimedTokens[eachClaim.user] = totalSettleClaimedTokens[eachClaim.user].add(eachClaim.amount) ; totalClaimedRewards = totalClaimedRewards.add(eachClaim.amount) ; Token(tokenAddress).transfer(eachClaim.user, eachClaim.amount); emit ClaimSettled(eachClaim.user,eachClaim.amount , claimid); return true ; } function rejectClaim(uint claimid) public onlyOwner returns (bool) {<FILL_FUNCTION_BODY> } function gteclaim(uint claimid ) view public returns (address , uint , uint , bool ) { return (claims[claimid].user , claims[claimid].amount , claims[claimid].status , claims[claimid].exists ); } function addContractBalance(uint amount) public { require(Token(tokenAddress).transferFrom(msg.sender, address(this), amount), "Cannot add balance!"); } }
contract GasCashbackClaim is Ownable { using SafeMath for uint; using EnumerableSet for EnumerableSet.AddressSet; /* claim[i] = [ 0 => user claimed, 1 => amount claimed, 2 => status , 0 => Pending , 1 => Settled, 2 => Rejected 3 => exists , true , false ] */ // GCB token contract address address public constant tokenAddress = 0x3539a4F4C0dFfC813B75944821e380C9209D3446; // mapping(address => uint[]) internal claim; struct Claim { address user; uint amount; uint status; bool exists; } mapping(uint => Claim) claims; mapping (address => uint) public totalSettleClaimedTokens; mapping (address => uint) public totalClaimedTokens; event ClaimRequested(address indexed user,uint amount, uint claimid); event ClaimSettled(address indexed user, uint amount, uint indexed claimid); event ClaimRejected(address indexed user, uint indexed claimid); uint public maxPercentage = 400 ; uint public totalClaimedRewards = 0; uint[] public claimrequests; function getallclaims() view public returns (uint[] memory){ return claimrequests; } function getMax(address user) view public returns (uint amount){ uint balance = Token(tokenAddress).balanceOf(user); uint max = maxPercentage.mul(balance).div(1e4); return max; } function claim(uint claimid , uint amount ) public returns (uint) { require(amount <= getMax(msg.sender), "Cannot claim more than balance"); require(claims[claimid].exists != true , "Claim already Exists" ); Claim storage newclaim = claims[claimid]; newclaim.user = msg.sender; newclaim.amount = amount; newclaim.status = 0 ; newclaim.exists = true ; claimrequests.push(claimid) ; totalClaimedTokens[msg.sender] = totalClaimedTokens[msg.sender].add(amount) ; emit ClaimRequested(msg.sender,amount, claimid); } function settleClaim(uint claimid ) public onlyOwner returns (bool) { require(claims[claimid].exists == true , "Claim doesn't Exists" ); Claim storage eachClaim = claims[claimid]; eachClaim.status = 1 ; totalSettleClaimedTokens[eachClaim.user] = totalSettleClaimedTokens[eachClaim.user].add(eachClaim.amount) ; totalClaimedRewards = totalClaimedRewards.add(eachClaim.amount) ; Token(tokenAddress).transfer(eachClaim.user, eachClaim.amount); emit ClaimSettled(eachClaim.user,eachClaim.amount , claimid); return true ; } <FILL_FUNCTION> function gteclaim(uint claimid ) view public returns (address , uint , uint , bool ) { return (claims[claimid].user , claims[claimid].amount , claims[claimid].status , claims[claimid].exists ); } function addContractBalance(uint amount) public { require(Token(tokenAddress).transferFrom(msg.sender, address(this), amount), "Cannot add balance!"); } }
require(claims[claimid].exists == true , "Claim doesn't Exists" ); Claim storage eachClaim = claims[claimid]; eachClaim.status = 2 ; emit ClaimRejected(eachClaim.user , claimid); return true ;
function rejectClaim(uint claimid) public onlyOwner returns (bool)
function rejectClaim(uint claimid) public onlyOwner returns (bool)
71032
Vesting
null
contract Vesting is Owned, ERC20Interface { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; mapping(address => Schedule) public schedules; mapping(address => uint256) balances; address public lockedTokenAddress; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public {<FILL_FUNCTION_BODY> } /* ERC-20 functions, null most of them */ function balanceOf(address tokenOwner) override virtual public view returns (uint balance) { return balances[tokenOwner]; } function totalSupply() override virtual public view returns (uint) { return 0; } function allowance(address tokenOwner, address spender) override virtual public view returns (uint remaining){ return 0; } function transfer(address to, uint tokens) override virtual public returns (bool success) { require(false, "Use the claim function, not transfer"); } function approve(address spender, uint tokens) override virtual public returns (bool success) { require(false, "Cannot approve spending"); } function transferFrom(address from, address to, uint tokens) override virtual public returns (bool success) { require(false, "Use the claim function, not transferFrom"); } /* My functions */ function vestedTotal(address user) private view returns (uint256){ uint256 time_now = block.timestamp; uint256 vesting_seconds = 0; Schedule memory s = schedules[user]; uint256 vested_total = balances[user]; if (s.start > 0) { if (time_now >= s.start) { vesting_seconds = time_now - s.start; uint256 vest_per_second_sats = s.tokens.sub(s.initial); vest_per_second_sats = vest_per_second_sats.div(s.length); vested_total = vesting_seconds.mul(vest_per_second_sats); vested_total = vested_total.add(s.initial); // amount they can withdraw } else { vested_total = 1; } if (vested_total > s.tokens) { vested_total = s.tokens; } } return vested_total; } function maxClaim(address user) public view returns (uint256) { uint256 vested_total = vestedTotal(user); Schedule memory s = schedules[user]; uint256 max = 0; if (s.start > 0){ uint256 claimed = s.tokens.sub(balances[user]); max = vested_total.sub(claimed); if (max > balances[user]){ max = balances[user]; } } return max; } function claim(uint256 amount) public { require(lockedTokenAddress != address(0x0), "Locked token contract has not been set"); require(amount > 0, "Must claim more than 0"); require(balances[msg.sender] > 0, "No vesting balance found"); uint256 vested_total = vestedTotal(msg.sender); Schedule memory s = schedules[msg.sender]; if (s.start > 0){ uint256 remaining_balance = balances[msg.sender].sub(amount); if (vested_total < s.tokens) { uint min_balance = s.tokens.sub(vested_total); require(remaining_balance >= min_balance, "Cannot transfer this amount due to vesting locks"); } } balances[msg.sender] = balances[msg.sender].sub(amount); ERC20Interface(lockedTokenAddress).transfer(msg.sender, amount); } function setSchedule(address user, uint32 start, uint32 length, uint256 initial, uint256 amount) public onlyOwner { schedules[user].start = start; schedules[user].length = length; schedules[user].initial = initial; schedules[user].tokens = amount; } function addTokens(address newOwner, uint256 amount) public onlyOwner { require(lockedTokenAddress != address(0x0), "Locked token contract has not been set"); ERC20Interface tokenContract = ERC20Interface(lockedTokenAddress); uint256 userAllowance = tokenContract.allowance(msg.sender, address(this)); uint256 fromBalance = tokenContract.balanceOf(msg.sender); require(fromBalance >= amount, "Sender has insufficient balance"); require(userAllowance >= amount, "Please allow tokens to be spent by this contract"); tokenContract.transferFrom(msg.sender, address(this), amount); balances[newOwner] = balances[newOwner].add(amount); emit Transfer(address(0x0), newOwner, amount); } function removeTokens(address owner, uint256 amount) public onlyOwner { ERC20Interface tokenContract = ERC20Interface(lockedTokenAddress); tokenContract.transfer(owner, amount); balances[owner] = balances[owner].sub(amount); } function setTokenContract(address _lockedTokenAddress) public onlyOwner { lockedTokenAddress = _lockedTokenAddress; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ receive () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint256 tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract Vesting is Owned, ERC20Interface { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; mapping(address => Schedule) public schedules; mapping(address => uint256) balances; address public lockedTokenAddress; <FILL_FUNCTION> /* ERC-20 functions, null most of them */ function balanceOf(address tokenOwner) override virtual public view returns (uint balance) { return balances[tokenOwner]; } function totalSupply() override virtual public view returns (uint) { return 0; } function allowance(address tokenOwner, address spender) override virtual public view returns (uint remaining){ return 0; } function transfer(address to, uint tokens) override virtual public returns (bool success) { require(false, "Use the claim function, not transfer"); } function approve(address spender, uint tokens) override virtual public returns (bool success) { require(false, "Cannot approve spending"); } function transferFrom(address from, address to, uint tokens) override virtual public returns (bool success) { require(false, "Use the claim function, not transferFrom"); } /* My functions */ function vestedTotal(address user) private view returns (uint256){ uint256 time_now = block.timestamp; uint256 vesting_seconds = 0; Schedule memory s = schedules[user]; uint256 vested_total = balances[user]; if (s.start > 0) { if (time_now >= s.start) { vesting_seconds = time_now - s.start; uint256 vest_per_second_sats = s.tokens.sub(s.initial); vest_per_second_sats = vest_per_second_sats.div(s.length); vested_total = vesting_seconds.mul(vest_per_second_sats); vested_total = vested_total.add(s.initial); // amount they can withdraw } else { vested_total = 1; } if (vested_total > s.tokens) { vested_total = s.tokens; } } return vested_total; } function maxClaim(address user) public view returns (uint256) { uint256 vested_total = vestedTotal(user); Schedule memory s = schedules[user]; uint256 max = 0; if (s.start > 0){ uint256 claimed = s.tokens.sub(balances[user]); max = vested_total.sub(claimed); if (max > balances[user]){ max = balances[user]; } } return max; } function claim(uint256 amount) public { require(lockedTokenAddress != address(0x0), "Locked token contract has not been set"); require(amount > 0, "Must claim more than 0"); require(balances[msg.sender] > 0, "No vesting balance found"); uint256 vested_total = vestedTotal(msg.sender); Schedule memory s = schedules[msg.sender]; if (s.start > 0){ uint256 remaining_balance = balances[msg.sender].sub(amount); if (vested_total < s.tokens) { uint min_balance = s.tokens.sub(vested_total); require(remaining_balance >= min_balance, "Cannot transfer this amount due to vesting locks"); } } balances[msg.sender] = balances[msg.sender].sub(amount); ERC20Interface(lockedTokenAddress).transfer(msg.sender, amount); } function setSchedule(address user, uint32 start, uint32 length, uint256 initial, uint256 amount) public onlyOwner { schedules[user].start = start; schedules[user].length = length; schedules[user].initial = initial; schedules[user].tokens = amount; } function addTokens(address newOwner, uint256 amount) public onlyOwner { require(lockedTokenAddress != address(0x0), "Locked token contract has not been set"); ERC20Interface tokenContract = ERC20Interface(lockedTokenAddress); uint256 userAllowance = tokenContract.allowance(msg.sender, address(this)); uint256 fromBalance = tokenContract.balanceOf(msg.sender); require(fromBalance >= amount, "Sender has insufficient balance"); require(userAllowance >= amount, "Please allow tokens to be spent by this contract"); tokenContract.transferFrom(msg.sender, address(this), amount); balances[newOwner] = balances[newOwner].add(amount); emit Transfer(address(0x0), newOwner, amount); } function removeTokens(address owner, uint256 amount) public onlyOwner { ERC20Interface tokenContract = ERC20Interface(lockedTokenAddress); tokenContract.transfer(owner, amount); balances[owner] = balances[owner].sub(amount); } function setTokenContract(address _lockedTokenAddress) public onlyOwner { lockedTokenAddress = _lockedTokenAddress; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ receive () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint256 tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
symbol = "VTLM"; name = "Vesting Alien Worlds Trilium"; decimals = 4;
constructor() public
// ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public
62934
ERC20Detailed
_transfer
contract ERC20Detailed is Context, IERC20 { using SafeMath for uint; string private _name; string private _symbol; uint8 private _decimals; mapping (address => uint) private _balances; mapping (address => mapping (address => uint)) private _allowances; uint private _totalSupply; uint256 public burnRates = 5; //4% bool public stopBurn = false; // true stop Burn ,false start burn; mapping(address => bool) public burnWhitList; event BurnEVENT(address sender,uint256 transAmount,uint256 fromBalance,address recipient,uint256 recipAmount,uint256 reciBalance,uint256 burnAmount); address public dividendPool;//Dividend Pool constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } 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 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) internal {<FILL_FUNCTION_BODY> } function isContract(address addr) public view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } 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); } function _setDividendPoolAddr(address addr) internal{ dividendPool = addr; burnWhitList[dividendPool] = true; } function _setWhiteList(address account,bool isAdd) internal{ require(account != address(0),"ERC20: whitlist can not be zeor"); burnWhitList[account] = isAdd; } function _setBurnRate(uint256 rate) internal{ require(rate<50,"ERC20: burn level must smail 100"); burnRates = rate; } function _setStopBurnFlage(bool flage) internal{ stopBurn = flage; } 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 ERC20Detailed is Context, IERC20 { using SafeMath for uint; string private _name; string private _symbol; uint8 private _decimals; mapping (address => uint) private _balances; mapping (address => mapping (address => uint)) private _allowances; uint private _totalSupply; uint256 public burnRates = 5; //4% bool public stopBurn = false; // true stop Burn ,false start burn; mapping(address => bool) public burnWhitList; event BurnEVENT(address sender,uint256 transAmount,uint256 fromBalance,address recipient,uint256 recipAmount,uint256 reciBalance,uint256 burnAmount); address public dividendPool;//Dividend Pool constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } 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 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; } <FILL_FUNCTION> function isContract(address addr) public view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } 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); } function _setDividendPoolAddr(address addr) internal{ dividendPool = addr; burnWhitList[dividendPool] = true; } function _setWhiteList(address account,bool isAdd) internal{ require(account != address(0),"ERC20: whitlist can not be zeor"); burnWhitList[account] = isAdd; } function _setBurnRate(uint256 rate) internal{ require(rate<50,"ERC20: burn level must smail 100"); burnRates = rate; } function _setStopBurnFlage(bool flage) internal{ stopBurn = flage; } 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); } }
require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(dividendPool != address(0),"ERC20: not set dividendPool "); uint256 burnAmount; if(burnWhitList[sender] || burnWhitList[recipient] || stopBurn){ burnAmount = 0; }else{ burnAmount = amount.mul(burnRates).div(100); } if(burnAmount == 0){ _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); }else{ _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount.sub(burnAmount)); _balances[dividendPool] = _balances[dividendPool].add(burnAmount); if (dividendPool != address(0) && isContract(dividendPool)){ dividendPoolInterface(dividendPool).AddDivi(sender,amount,recipient,amount.sub(burnAmount),burnAmount,now); } emit BurnEVENT(sender,amount,_balances[sender],recipient,amount.sub(burnAmount),_balances[recipient],burnAmount); } emit Transfer(sender, recipient, amount);
function _transfer(address sender, address recipient, uint amount) internal
function _transfer(address sender, address recipient, uint amount) internal
75575
StcToken
transferFrom
contract StcToken is ERC20Interface { string public constant symbol = "STC"; string public constant name = "StarChainToken"; uint8 public constant decimals = 8; uint256 _totalSupply = 1000000000*100000000; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; function StcToken(){ balances[msg.sender] = _totalSupply; } function totalSupply() public constant returns (uint256 total){ total = _totalSupply; } function balanceOf(address _owner) public constant returns(uint256 balance){ return balances[_owner]; } function transfer(address _to,uint256 _amount) public returns (bool success){ if(balances[msg.sender] >= _amount && _amount >0 && (balances[_to]+_amount) > balances[_to]){ balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender,_to,_amount); return true; }else{ return false; } } function transferFrom(address _from,address _to,uint256 _amount) public returns(bool success){<FILL_FUNCTION_BODY> } function approve(address _spender,uint256 _amount) public returns(bool success){ allowed[msg.sender][_spender] = _amount; Approval(msg.sender,_spender,_amount); return true; } function allowance(address _owner,address _spender) public constant returns(uint256 remaining){ return allowed[_owner][_spender]; } }
contract StcToken is ERC20Interface { string public constant symbol = "STC"; string public constant name = "StarChainToken"; uint8 public constant decimals = 8; uint256 _totalSupply = 1000000000*100000000; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; function StcToken(){ balances[msg.sender] = _totalSupply; } function totalSupply() public constant returns (uint256 total){ total = _totalSupply; } function balanceOf(address _owner) public constant returns(uint256 balance){ return balances[_owner]; } function transfer(address _to,uint256 _amount) public returns (bool success){ if(balances[msg.sender] >= _amount && _amount >0 && (balances[_to]+_amount) > balances[_to]){ balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender,_to,_amount); return true; }else{ return false; } } <FILL_FUNCTION> function approve(address _spender,uint256 _amount) public returns(bool success){ allowed[msg.sender][_spender] = _amount; Approval(msg.sender,_spender,_amount); return true; } function allowance(address _owner,address _spender) public constant returns(uint256 remaining){ return allowed[_owner][_spender]; } }
if(balances[_from] >= _amount && _amount > 0 && (balances[_to]+_amount) > balances[_to] && allowed[_from][msg.sender] >= _amount){ balances[_from] -= _amount; balances[_to] += _amount; allowed[_from][msg.sender] -= _amount; Transfer(_from,_to,_amount); return true; }else{ return false; }
function transferFrom(address _from,address _to,uint256 _amount) public returns(bool success)
function transferFrom(address _from,address _to,uint256 _amount) public returns(bool success)
80719
XenonCore
increaseAllowance
contract XenonCore is ERC20Detailed { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "XenonCore"; string constant tokenSymbol = "xCORE"; uint8 constant tokenDecimals = 18; uint256 _totalSupply = 100000000000000000000000; uint256 public basePercent = 100; /** * Mint is in constructor ONLY */ constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _mint(msg.sender, _totalSupply); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function findOnePercent(uint256 value) public view returns (uint256) { uint256 roundValue = value.ceil(basePercent); uint256 onePercent = roundValue.mul(basePercent).div(1005); return onePercent; } function transfer(address to, uint256 value) public returns (bool) { require(value <= _balances[msg.sender]); require(to != address(0)); uint256 tokensToBurn = findOnePercent(value); uint256 tokensToTransfer = value.sub(tokensToBurn); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(tokensToTransfer); _totalSupply = _totalSupply.sub(tokensToBurn); emit Transfer(msg.sender, to, tokensToTransfer); emit Transfer(msg.sender, address(0), tokensToBurn); return true; } function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); } } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); require(to != address(0)); _balances[from] = _balances[from].sub(value); uint256 tokensToBurn = findOnePercent(value); uint256 tokensToTransfer = value.sub(tokensToBurn); _balances[to] = _balances[to].add(tokensToTransfer); _totalSupply = _totalSupply.sub(tokensToBurn); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, tokensToTransfer); emit Transfer(from, address(0), tokensToBurn); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {<FILL_FUNCTION_BODY> } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _mint(address account, uint256 amount) internal { require(amount != 0); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function burn(uint256 amount) external { _burn(msg.sender, amount); } function _burn(address account, uint256 amount) internal { require(amount != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } function burnFrom(address account, uint256 amount) external { require(amount <= _allowed[account][msg.sender]); _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(amount); _burn(account, amount); } }
contract XenonCore is ERC20Detailed { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "XenonCore"; string constant tokenSymbol = "xCORE"; uint8 constant tokenDecimals = 18; uint256 _totalSupply = 100000000000000000000000; uint256 public basePercent = 100; /** * Mint is in constructor ONLY */ constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _mint(msg.sender, _totalSupply); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function findOnePercent(uint256 value) public view returns (uint256) { uint256 roundValue = value.ceil(basePercent); uint256 onePercent = roundValue.mul(basePercent).div(1005); return onePercent; } function transfer(address to, uint256 value) public returns (bool) { require(value <= _balances[msg.sender]); require(to != address(0)); uint256 tokensToBurn = findOnePercent(value); uint256 tokensToTransfer = value.sub(tokensToBurn); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(tokensToTransfer); _totalSupply = _totalSupply.sub(tokensToBurn); emit Transfer(msg.sender, to, tokensToTransfer); emit Transfer(msg.sender, address(0), tokensToBurn); return true; } function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); } } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); require(to != address(0)); _balances[from] = _balances[from].sub(value); uint256 tokensToBurn = findOnePercent(value); uint256 tokensToTransfer = value.sub(tokensToBurn); _balances[to] = _balances[to].add(tokensToTransfer); _totalSupply = _totalSupply.sub(tokensToBurn); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, tokensToTransfer); emit Transfer(from, address(0), tokensToBurn); return true; } <FILL_FUNCTION> function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _mint(address account, uint256 amount) internal { require(amount != 0); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function burn(uint256 amount) external { _burn(msg.sender, amount); } function _burn(address account, uint256 amount) internal { require(amount != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } function burnFrom(address account, uint256 amount) external { require(amount <= _allowed[account][msg.sender]); _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(amount); _burn(account, amount); } }
require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true;
function increaseAllowance(address spender, uint256 addedValue) public returns (bool)
function increaseAllowance(address spender, uint256 addedValue) public returns (bool)
16293
Crowdsale
calculateBonusForHours
contract Crowdsale is Ownable { string public ETHUSD; event ShowPrice(string price); using SafeMath for uint256; SingleTokenCoin public token = new SingleTokenCoin(); Addresses private addresses = new Addresses(); WrapperOraclize private wrapper = WrapperOraclize(0xfC484c66daE464CC6055d7a4782Ec8761dc9842F); uint256 private ico_start; uint256 private ico_finish; uint256 private rate; uint256 private decimals; uint256 private tax; //Time-based Bonus Program uint256 private firstBonusPhase; uint256 private firstExtraBonus; uint256 private secondBonusPhase; uint256 private secondExtraBonus; uint256 private thirdBonusPhase; uint256 private thirdExtraBonus; uint256 private fourBonusPhase; uint256 private fourExtraBonus; //Withdrow Phases bool private firstWithdrowPhase; bool private secondWithdrowPhase; bool private thirdWithdrowPhase; bool private fourWithdrowPhase; uint256 private firstWithdrowAmount; uint256 private secondWithdrowAmount; uint256 private thirdWithdrowAmount; uint256 private fourWithdrowAmount; uint256 private totalETH; uint256 private totalAmount; bool private initialize = false; bool public mintingFinished = false; //Storage for ICO Buyers ETH mapping(address => uint256) private ico_buyers_eth; //Storage for ICO Buyers Token mapping(address => uint256) private ico_buyers_token; address[] private investors; mapping(address => bytes32) private privilegedWallets; mapping(address => uint256) private manualAddresses; address[] private manualAddressesCount; address[] private privilegedWalletsCount; bytes32 private g = "granted"; bytes32 private r = "revorked"; uint256 private soldTokens; uint256 private mincup; uint256 private minPrice; event ShowInfo(uint256 _info); event ShowInfoStr(string _info); event ShowInfoBool(bool _info); function Crowdsale() { //set calculate rate from USD rate = 3546099290780141; //0.0003 ETH //temp decimals = 35460992907801; // 0.0000003 ETH // 2 decimals tax = 36000000000000000; //tax && minimum price ~10$ //minPrice = decimals + tax; // ~10$ //18.09.2017 15:00 UTC (1505746800) ico_start = 1505746800; //17.10.2017 23:59 UTC (1508284740) ico_finish = 1508284740; totalAmount = 1020000000; // 500 000 STM with 2 decimals mincup = 50000000; mintingFinished = false; setTotalSupply(); //Time-Based Bonus Phase firstBonusPhase = ico_start.add(24 hours); firstExtraBonus = 25; secondBonusPhase = ico_start.add(168 hours); secondExtraBonus = 15; thirdBonusPhase = ico_start.add(336 hours); thirdExtraBonus = 10; fourBonusPhase = ico_start.add(480 hours); fourExtraBonus = 5; //Withdrow Phases firstWithdrowPhase = false; secondWithdrowPhase = false; thirdWithdrowPhase = false; fourWithdrowPhase = false; firstWithdrowAmount = 50000000; secondWithdrowAmount = 200000000; thirdWithdrowAmount = 500000000; fourWithdrowAmount = 1020000000; totalETH = 0; soldTokens = 0; privilegedWalletsCount.push(msg.sender); privilegedWallets[msg.sender] = g; } modifier canMint() { require(!mintingFinished); _; } function() external payable { mint(); } function bytesToUInt(bytes32 v) constant returns (uint ret) { if (v == 0x0) { revert(); } uint digit; for (uint i = 0; i < 32; i++) { digit = uint((uint(v) / (2 ** (8 * (31 - i)))) & 0xff); if (digit == 0 || digit == 46) { break; } else if (digit < 48 || digit > 57) { revert(); } ret *= 10; ret += (digit - 48); } return ret; } function calculateRate() public payable returns(uint256) { bytes32 result = getWrapperData(); uint256 usd = bytesToUInt(result); uint256 price = 1 ether / usd; //price for 1 STM return price; } function calculateWithdrow() private { if (!firstWithdrowPhase && soldTokens >= firstWithdrowAmount && soldTokens < secondWithdrowAmount) { sendToOwners(this.balance); } else { if (!secondWithdrowPhase && soldTokens >= secondWithdrowAmount && soldTokens < thirdWithdrowAmount) { sendToOwners(this.balance); } else { if (!thirdWithdrowPhase && soldTokens >= thirdWithdrowAmount && soldTokens < fourWithdrowAmount) { sendToOwners(this.balance); } else { if (!fourWithdrowPhase && soldTokens >= fourWithdrowAmount) { sendToOwners(this.balance); } } } } } modifier isInitialize() { require(!initialize); _; } function setTotalSupply() private isInitialize onlyOwner returns(uint256) { initialize = true; return token.setTotalSupply(totalAmount); } function sendToAddress(address _address, uint256 _tokens) canMint public { if (grantedWallets(msg.sender) == false) { revert(); } ShowInfo(_tokens); uint256 currentTokens = _tokens; uint256 timeBonus = calculateBonusForHours(currentTokens); uint256 allTokens = currentTokens.add(timeBonus); token.approve(_address, this, allTokens); saveInfoAboutInvestors(_address, 0, allTokens, true); token.mint(_address, allTokens); soldTokens = soldTokens + allTokens; calculateWithdrow(); } modifier isRefund() { if (msg.value < tax) { refund(msg.value); revert(); } _; } function grantedWallets(address _address) private returns(bool) { if (privilegedWallets[_address] == g) { return true; } return false; } modifier isICOFinished() { if (now > ico_finish) { finishMinting(); refund(msg.value); revert(); } _; } function getTokens() public constant returns(uint256) { token.getTotalTokenCount(); } function setPrivelegedWallet(address _address) public onlyOwner returns(bool) { if (privilegedWalletsCount.length == 2) { revert(); } if (privilegedWallets[_address] != g && privilegedWallets[_address] != r) { privilegedWalletsCount.push(_address); } privilegedWallets[_address] = g; return true; } function setTransferOwnership(address _address) public onlyOwner { removePrivelegedWallet(msg.sender); setPrivelegedWallet(_address); transferOwnership(_address); } function removePrivelegedWallet(address _address) public onlyOwner { if (privilegedWallets[_address] == g) { privilegedWallets[_address] = r; delete privilegedWalletsCount[0]; } else { revert(); } } //only for demonstrate Test Version function setICODate(uint256 _time) public onlyOwner { ico_start = _time; ShowInfo(_time); } function getICODate() public constant returns(uint256) { return ico_start; } function mint() public isRefund canMint isICOFinished payable { rate = calculateRate(); decimals = rate / 100; //price for 0.01 STM uint256 remainder = msg.value.mod(decimals); uint256 eth = msg.value.sub(remainder); if (remainder != 0) { refund(remainder); } totalETH = totalETH + eth; uint currentRate = rate / 100; //2 decimals uint256 tokens = eth.div(currentRate); uint256 timeBonus = calculateBonusForHours(tokens); uint256 allTokens = tokens.add(timeBonus) + 100; // +100 - oraclize Tax saveInfoAboutInvestors(msg.sender, eth, allTokens, false); token.mint(msg.sender, allTokens); soldTokens = soldTokens + allTokens; calculateWithdrow(); } function saveInfoAboutInvestors(address _address, uint256 _amount, uint256 _tokens, bool _isManual) private { if (!_isManual) { if (ico_buyers_token[_address] == 0) { investors.push(_address); } // Store ETH of Investor ico_buyers_eth[_address] = ico_buyers_eth[_address].add(_amount); // Store Token of Investor ico_buyers_token[_address] = ico_buyers_token[_address].add(_tokens); } else { if(manualAddresses[_address] == 0) { manualAddressesCount.push(_address); } manualAddresses[_address] = manualAddresses[_address].add(_tokens); } } function getManualByAddress(address _address) public constant returns(uint256) { return manualAddresses[_address]; } function getManualInvestorsCount() public constant returns(uint256) { return manualAddressesCount.length; } function getManualAddress(uint _index) public constant returns(address) { return manualAddressesCount[_index]; } function finishMinting() public onlyOwner { if(mintingFinished) { revert(); } ShowInfoBool(mintingFinished); mintingFinished = true; ShowInfoBool(mintingFinished); if (soldTokens < mincup) { if(investors.length != 0) { for (uint256 i=0; i < investors.length; i++) { address addr = investors[i]; token.burnTokens(addr); } } if(manualAddressesCount.length != 0) { for (uint256 j=0; j < manualAddressesCount.length; j++) { address manualAddr = manualAddressesCount[j]; token.burnTokens(manualAddr); } } } } function getFinishStatus() public constant returns(bool) { return mintingFinished; } function manualRefund() public { if (mintingFinished) { if(ico_buyers_eth[msg.sender] != 0) { uint256 amount = ico_buyers_eth[msg.sender]; msg.sender.transfer(amount); ico_buyers_eth[msg.sender] = 0; } else { revert(); } } else { revert(); } } function refund(uint256 _amount) private { msg.sender.transfer(_amount); } function refund(address _address, uint256 _amount) private { _address.transfer(_amount); } function getTokensManual(address _address) public constant returns(uint256) { return manualAddresses[_address]; } function calculateBonusForHours(uint256 _tokens) private returns(uint256) {<FILL_FUNCTION_BODY> } function sendToOwners(uint256 _amount) private { uint256 twoPercent = _amount.mul(2).div(100); uint256 fivePercent = _amount.mul(5).div(100); uint256 nineThreePercent = _amount.mul(93).div(100); // ----------ADDRESSES FOR PRODUCTION------------- //NineThree Percent addresses.addr1().transfer(nineThreePercent); addresses.addr2().transfer(nineThreePercent); addresses.addr3().transfer(nineThreePercent); addresses.addr4().transfer(nineThreePercent); if (!firstWithdrowPhase) { addresses.addr1().transfer(nineThreePercent); firstWithdrowPhase = true; } else { if (!secondWithdrowPhase) { addresses.addr2().transfer(nineThreePercent); secondWithdrowPhase = true; } else { if (!thirdWithdrowPhase) { addresses.addr3().transfer(nineThreePercent); thirdWithdrowPhase = true; } else { if (!fourWithdrowPhase) { addresses.addr4().transfer(nineThreePercent); fourWithdrowPhase = true; } } } } //Five Percent addresses.successFee().transfer(fivePercent); //Two Percent addresses.bounty().transfer(twoPercent); } function getBalanceContract() public constant returns(uint256) { return this.balance; } function getSoldToken() public constant returns(uint256) { return soldTokens; } function getInvestorsTokens(address _address) public constant returns(uint256) { return ico_buyers_token[_address]; } function getInvestorsETH(address _address) public constant returns(uint256) { return ico_buyers_eth[_address]; } function getInvestors() public constant returns(uint256) { return investors.length; } function getInvestorByValue(address _address) public constant returns(uint256) { return ico_buyers_eth[_address]; } //only for test version function transfer(address _from, address _to, uint256 _amount) public returns(bool) { return token.transferFrom(_from, _to, _amount); } function getInvestorByIndex(uint256 _index) public constant returns(address) { return investors[_index]; } function getLeftToken() public constant returns(uint256) { if(token.totalSupply() != 0) { return token.totalSupply() - soldTokens; } else { return soldTokens; } } function getTotalToken() public constant returns(uint256) { return token.totalSupply(); } function getTotalETH() public constant returns(uint256) { return totalETH; } function getCurrentPrice() public constant returns(uint256) { uint256 secondDiscount = calculateBonusForHours(rate); uint256 investorDiscount = rate.sub(secondDiscount); return investorDiscount * 10; //minimum 10$ //~10STM } function getContractAddress() public constant returns(address) { return this; } function getOwner() public constant returns(address) { return owner; } function sendOracleData() public payable { if (msg.value != 0) { wrapper.transfer(msg.value); } wrapper.update("URL", "json(https://api.kraken.com/0/public/Ticker?pair=ETHUSD).result.XETHZUSD.c.0"); } function getQueryPrice(string datasource) constant returns(uint256) { return wrapper.getPrice(datasource); } function checkWrapperBalance() public constant returns(uint256) { return wrapper.getWrapperBalance(); } function getWrapperData() constant returns(bytes32) { return wrapper.getWrapperData(); } }
contract Crowdsale is Ownable { string public ETHUSD; event ShowPrice(string price); using SafeMath for uint256; SingleTokenCoin public token = new SingleTokenCoin(); Addresses private addresses = new Addresses(); WrapperOraclize private wrapper = WrapperOraclize(0xfC484c66daE464CC6055d7a4782Ec8761dc9842F); uint256 private ico_start; uint256 private ico_finish; uint256 private rate; uint256 private decimals; uint256 private tax; //Time-based Bonus Program uint256 private firstBonusPhase; uint256 private firstExtraBonus; uint256 private secondBonusPhase; uint256 private secondExtraBonus; uint256 private thirdBonusPhase; uint256 private thirdExtraBonus; uint256 private fourBonusPhase; uint256 private fourExtraBonus; //Withdrow Phases bool private firstWithdrowPhase; bool private secondWithdrowPhase; bool private thirdWithdrowPhase; bool private fourWithdrowPhase; uint256 private firstWithdrowAmount; uint256 private secondWithdrowAmount; uint256 private thirdWithdrowAmount; uint256 private fourWithdrowAmount; uint256 private totalETH; uint256 private totalAmount; bool private initialize = false; bool public mintingFinished = false; //Storage for ICO Buyers ETH mapping(address => uint256) private ico_buyers_eth; //Storage for ICO Buyers Token mapping(address => uint256) private ico_buyers_token; address[] private investors; mapping(address => bytes32) private privilegedWallets; mapping(address => uint256) private manualAddresses; address[] private manualAddressesCount; address[] private privilegedWalletsCount; bytes32 private g = "granted"; bytes32 private r = "revorked"; uint256 private soldTokens; uint256 private mincup; uint256 private minPrice; event ShowInfo(uint256 _info); event ShowInfoStr(string _info); event ShowInfoBool(bool _info); function Crowdsale() { //set calculate rate from USD rate = 3546099290780141; //0.0003 ETH //temp decimals = 35460992907801; // 0.0000003 ETH // 2 decimals tax = 36000000000000000; //tax && minimum price ~10$ //minPrice = decimals + tax; // ~10$ //18.09.2017 15:00 UTC (1505746800) ico_start = 1505746800; //17.10.2017 23:59 UTC (1508284740) ico_finish = 1508284740; totalAmount = 1020000000; // 500 000 STM with 2 decimals mincup = 50000000; mintingFinished = false; setTotalSupply(); //Time-Based Bonus Phase firstBonusPhase = ico_start.add(24 hours); firstExtraBonus = 25; secondBonusPhase = ico_start.add(168 hours); secondExtraBonus = 15; thirdBonusPhase = ico_start.add(336 hours); thirdExtraBonus = 10; fourBonusPhase = ico_start.add(480 hours); fourExtraBonus = 5; //Withdrow Phases firstWithdrowPhase = false; secondWithdrowPhase = false; thirdWithdrowPhase = false; fourWithdrowPhase = false; firstWithdrowAmount = 50000000; secondWithdrowAmount = 200000000; thirdWithdrowAmount = 500000000; fourWithdrowAmount = 1020000000; totalETH = 0; soldTokens = 0; privilegedWalletsCount.push(msg.sender); privilegedWallets[msg.sender] = g; } modifier canMint() { require(!mintingFinished); _; } function() external payable { mint(); } function bytesToUInt(bytes32 v) constant returns (uint ret) { if (v == 0x0) { revert(); } uint digit; for (uint i = 0; i < 32; i++) { digit = uint((uint(v) / (2 ** (8 * (31 - i)))) & 0xff); if (digit == 0 || digit == 46) { break; } else if (digit < 48 || digit > 57) { revert(); } ret *= 10; ret += (digit - 48); } return ret; } function calculateRate() public payable returns(uint256) { bytes32 result = getWrapperData(); uint256 usd = bytesToUInt(result); uint256 price = 1 ether / usd; //price for 1 STM return price; } function calculateWithdrow() private { if (!firstWithdrowPhase && soldTokens >= firstWithdrowAmount && soldTokens < secondWithdrowAmount) { sendToOwners(this.balance); } else { if (!secondWithdrowPhase && soldTokens >= secondWithdrowAmount && soldTokens < thirdWithdrowAmount) { sendToOwners(this.balance); } else { if (!thirdWithdrowPhase && soldTokens >= thirdWithdrowAmount && soldTokens < fourWithdrowAmount) { sendToOwners(this.balance); } else { if (!fourWithdrowPhase && soldTokens >= fourWithdrowAmount) { sendToOwners(this.balance); } } } } } modifier isInitialize() { require(!initialize); _; } function setTotalSupply() private isInitialize onlyOwner returns(uint256) { initialize = true; return token.setTotalSupply(totalAmount); } function sendToAddress(address _address, uint256 _tokens) canMint public { if (grantedWallets(msg.sender) == false) { revert(); } ShowInfo(_tokens); uint256 currentTokens = _tokens; uint256 timeBonus = calculateBonusForHours(currentTokens); uint256 allTokens = currentTokens.add(timeBonus); token.approve(_address, this, allTokens); saveInfoAboutInvestors(_address, 0, allTokens, true); token.mint(_address, allTokens); soldTokens = soldTokens + allTokens; calculateWithdrow(); } modifier isRefund() { if (msg.value < tax) { refund(msg.value); revert(); } _; } function grantedWallets(address _address) private returns(bool) { if (privilegedWallets[_address] == g) { return true; } return false; } modifier isICOFinished() { if (now > ico_finish) { finishMinting(); refund(msg.value); revert(); } _; } function getTokens() public constant returns(uint256) { token.getTotalTokenCount(); } function setPrivelegedWallet(address _address) public onlyOwner returns(bool) { if (privilegedWalletsCount.length == 2) { revert(); } if (privilegedWallets[_address] != g && privilegedWallets[_address] != r) { privilegedWalletsCount.push(_address); } privilegedWallets[_address] = g; return true; } function setTransferOwnership(address _address) public onlyOwner { removePrivelegedWallet(msg.sender); setPrivelegedWallet(_address); transferOwnership(_address); } function removePrivelegedWallet(address _address) public onlyOwner { if (privilegedWallets[_address] == g) { privilegedWallets[_address] = r; delete privilegedWalletsCount[0]; } else { revert(); } } //only for demonstrate Test Version function setICODate(uint256 _time) public onlyOwner { ico_start = _time; ShowInfo(_time); } function getICODate() public constant returns(uint256) { return ico_start; } function mint() public isRefund canMint isICOFinished payable { rate = calculateRate(); decimals = rate / 100; //price for 0.01 STM uint256 remainder = msg.value.mod(decimals); uint256 eth = msg.value.sub(remainder); if (remainder != 0) { refund(remainder); } totalETH = totalETH + eth; uint currentRate = rate / 100; //2 decimals uint256 tokens = eth.div(currentRate); uint256 timeBonus = calculateBonusForHours(tokens); uint256 allTokens = tokens.add(timeBonus) + 100; // +100 - oraclize Tax saveInfoAboutInvestors(msg.sender, eth, allTokens, false); token.mint(msg.sender, allTokens); soldTokens = soldTokens + allTokens; calculateWithdrow(); } function saveInfoAboutInvestors(address _address, uint256 _amount, uint256 _tokens, bool _isManual) private { if (!_isManual) { if (ico_buyers_token[_address] == 0) { investors.push(_address); } // Store ETH of Investor ico_buyers_eth[_address] = ico_buyers_eth[_address].add(_amount); // Store Token of Investor ico_buyers_token[_address] = ico_buyers_token[_address].add(_tokens); } else { if(manualAddresses[_address] == 0) { manualAddressesCount.push(_address); } manualAddresses[_address] = manualAddresses[_address].add(_tokens); } } function getManualByAddress(address _address) public constant returns(uint256) { return manualAddresses[_address]; } function getManualInvestorsCount() public constant returns(uint256) { return manualAddressesCount.length; } function getManualAddress(uint _index) public constant returns(address) { return manualAddressesCount[_index]; } function finishMinting() public onlyOwner { if(mintingFinished) { revert(); } ShowInfoBool(mintingFinished); mintingFinished = true; ShowInfoBool(mintingFinished); if (soldTokens < mincup) { if(investors.length != 0) { for (uint256 i=0; i < investors.length; i++) { address addr = investors[i]; token.burnTokens(addr); } } if(manualAddressesCount.length != 0) { for (uint256 j=0; j < manualAddressesCount.length; j++) { address manualAddr = manualAddressesCount[j]; token.burnTokens(manualAddr); } } } } function getFinishStatus() public constant returns(bool) { return mintingFinished; } function manualRefund() public { if (mintingFinished) { if(ico_buyers_eth[msg.sender] != 0) { uint256 amount = ico_buyers_eth[msg.sender]; msg.sender.transfer(amount); ico_buyers_eth[msg.sender] = 0; } else { revert(); } } else { revert(); } } function refund(uint256 _amount) private { msg.sender.transfer(_amount); } function refund(address _address, uint256 _amount) private { _address.transfer(_amount); } function getTokensManual(address _address) public constant returns(uint256) { return manualAddresses[_address]; } <FILL_FUNCTION> function sendToOwners(uint256 _amount) private { uint256 twoPercent = _amount.mul(2).div(100); uint256 fivePercent = _amount.mul(5).div(100); uint256 nineThreePercent = _amount.mul(93).div(100); // ----------ADDRESSES FOR PRODUCTION------------- //NineThree Percent addresses.addr1().transfer(nineThreePercent); addresses.addr2().transfer(nineThreePercent); addresses.addr3().transfer(nineThreePercent); addresses.addr4().transfer(nineThreePercent); if (!firstWithdrowPhase) { addresses.addr1().transfer(nineThreePercent); firstWithdrowPhase = true; } else { if (!secondWithdrowPhase) { addresses.addr2().transfer(nineThreePercent); secondWithdrowPhase = true; } else { if (!thirdWithdrowPhase) { addresses.addr3().transfer(nineThreePercent); thirdWithdrowPhase = true; } else { if (!fourWithdrowPhase) { addresses.addr4().transfer(nineThreePercent); fourWithdrowPhase = true; } } } } //Five Percent addresses.successFee().transfer(fivePercent); //Two Percent addresses.bounty().transfer(twoPercent); } function getBalanceContract() public constant returns(uint256) { return this.balance; } function getSoldToken() public constant returns(uint256) { return soldTokens; } function getInvestorsTokens(address _address) public constant returns(uint256) { return ico_buyers_token[_address]; } function getInvestorsETH(address _address) public constant returns(uint256) { return ico_buyers_eth[_address]; } function getInvestors() public constant returns(uint256) { return investors.length; } function getInvestorByValue(address _address) public constant returns(uint256) { return ico_buyers_eth[_address]; } //only for test version function transfer(address _from, address _to, uint256 _amount) public returns(bool) { return token.transferFrom(_from, _to, _amount); } function getInvestorByIndex(uint256 _index) public constant returns(address) { return investors[_index]; } function getLeftToken() public constant returns(uint256) { if(token.totalSupply() != 0) { return token.totalSupply() - soldTokens; } else { return soldTokens; } } function getTotalToken() public constant returns(uint256) { return token.totalSupply(); } function getTotalETH() public constant returns(uint256) { return totalETH; } function getCurrentPrice() public constant returns(uint256) { uint256 secondDiscount = calculateBonusForHours(rate); uint256 investorDiscount = rate.sub(secondDiscount); return investorDiscount * 10; //minimum 10$ //~10STM } function getContractAddress() public constant returns(address) { return this; } function getOwner() public constant returns(address) { return owner; } function sendOracleData() public payable { if (msg.value != 0) { wrapper.transfer(msg.value); } wrapper.update("URL", "json(https://api.kraken.com/0/public/Ticker?pair=ETHUSD).result.XETHZUSD.c.0"); } function getQueryPrice(string datasource) constant returns(uint256) { return wrapper.getPrice(datasource); } function checkWrapperBalance() public constant returns(uint256) { return wrapper.getWrapperBalance(); } function getWrapperData() constant returns(bytes32) { return wrapper.getWrapperData(); } }
//Calculate for first bonus program if (now >= ico_start && now <= firstBonusPhase ) { return _tokens.mul(firstExtraBonus).div(100); } //Calculate for second bonus program if (now > firstBonusPhase && now <= secondBonusPhase ) { return _tokens.mul(secondExtraBonus).div(100); } //Calculate for third bonus program if (now > secondBonusPhase && now <= thirdBonusPhase ) { return _tokens.mul(thirdExtraBonus).div(100); } //Calculate for four bonus program if (now > thirdBonusPhase && now <= fourBonusPhase ) { return _tokens.mul(fourExtraBonus).div(100); } return 0;
function calculateBonusForHours(uint256 _tokens) private returns(uint256)
function calculateBonusForHours(uint256 _tokens) private returns(uint256)
52040
GBHUB
transferFrom
contract GBHUB is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public RATE; uint public DENOMINATOR; bool public isStopped = false; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; event Mint(address indexed to, uint256 amount); event ChangeRate(uint256 amount); modifier onlyWhenRunning { require(!isStopped); _; } // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "GBH"; name = "GBHUB"; decimals = 18; _totalSupply = 3000000000 * 10**uint(decimals); balances[owner] = _totalSupply; RATE = 2310000; // 1 ETH = 231 GBH // 1 GBH = 10 USD DENOMINATOR = 10000; emit Transfer(address(0), owner, _totalSupply); } // ---------------------------------------------------------------------------- // It invokes when someone sends ETH to this contract address // requires enough gas for execution // ---------------------------------------------------------------------------- function() public payable { buyTokens(); } // ---------------------------------------------------------------------------- // Function to handle eth and token transfers // tokens are transferred to user // ETH are transferred to current owner // ---------------------------------------------------------------------------- function buyTokens() onlyWhenRunning public payable { require(msg.value > 0); uint tokens = msg.value.mul(RATE).div(DENOMINATOR); require(balances[owner] >= tokens); balances[msg.sender] = balances[msg.sender].add(tokens); balances[owner] = balances[owner].sub(tokens); emit Transfer(owner, msg.sender, tokens); owner.transfer(msg.value); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { require(to != address(0)); require(tokens > 0); require(balances[msg.sender] >= tokens); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { require(spender != address(0)); require(tokens > 0); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) {<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 view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Increase the amount of tokens that an owner allowed to a spender. // // approve should be called when allowed[_spender] == 0. To increment // allowed value is better to use this function to avoid 2 calls (and wait until // the first transaction is mined) // _spender The address which will spend the funds. // _addedValue The amount of tokens to increase the allowance by. // ------------------------------------------------------------------------ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { require(_spender != address(0)); allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } // ------------------------------------------------------------------------ // Decrease the amount of tokens that an owner allowed to a spender. // // approve should be called when allowed[_spender] == 0. To decrement // allowed value is better to use this function to avoid 2 calls (and wait until // the first transaction is mined) // _spender The address which will spend the funds. // _subtractedValue The amount of tokens to decrease the allowance by. // ------------------------------------------------------------------------ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { require(_spender != address(0)); uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } // ------------------------------------------------------------------------ // Change the ETH to IO rate // ------------------------------------------------------------------------ function changeRate(uint256 _rate) public onlyOwner { require(_rate > 0); RATE =_rate; emit ChangeRate(_rate); } // ------------------------------------------------------------------------ // Function to mint tokens // _to The address that will receive the minted tokens. // _amount The amount of tokens to mint. // A boolean that indicates if the operation was successful. // ------------------------------------------------------------------------ function mint(address _to, uint256 _amount) onlyOwner public returns (bool) { require(_to != address(0)); require(_amount > 0); uint newamount = _amount * 10**uint(decimals); _totalSupply = _totalSupply.add(newamount); balances[_to] = balances[_to].add(newamount); emit Mint(_to, newamount); emit Transfer(address(0), _to, newamount); return true; } // ------------------------------------------------------------------------ // function to stop the ICO // ------------------------------------------------------------------------ function stopICO() onlyOwner public { isStopped = true; } // ------------------------------------------------------------------------ // function to resume ICO // ------------------------------------------------------------------------ function resumeICO() onlyOwner public { isStopped = false; } }
contract GBHUB is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public RATE; uint public DENOMINATOR; bool public isStopped = false; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; event Mint(address indexed to, uint256 amount); event ChangeRate(uint256 amount); modifier onlyWhenRunning { require(!isStopped); _; } // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "GBH"; name = "GBHUB"; decimals = 18; _totalSupply = 3000000000 * 10**uint(decimals); balances[owner] = _totalSupply; RATE = 2310000; // 1 ETH = 231 GBH // 1 GBH = 10 USD DENOMINATOR = 10000; emit Transfer(address(0), owner, _totalSupply); } // ---------------------------------------------------------------------------- // It invokes when someone sends ETH to this contract address // requires enough gas for execution // ---------------------------------------------------------------------------- function() public payable { buyTokens(); } // ---------------------------------------------------------------------------- // Function to handle eth and token transfers // tokens are transferred to user // ETH are transferred to current owner // ---------------------------------------------------------------------------- function buyTokens() onlyWhenRunning public payable { require(msg.value > 0); uint tokens = msg.value.mul(RATE).div(DENOMINATOR); require(balances[owner] >= tokens); balances[msg.sender] = balances[msg.sender].add(tokens); balances[owner] = balances[owner].sub(tokens); emit Transfer(owner, msg.sender, tokens); owner.transfer(msg.value); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { require(to != address(0)); require(tokens > 0); require(balances[msg.sender] >= tokens); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { require(spender != address(0)); require(tokens > 0); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } <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 view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Increase the amount of tokens that an owner allowed to a spender. // // approve should be called when allowed[_spender] == 0. To increment // allowed value is better to use this function to avoid 2 calls (and wait until // the first transaction is mined) // _spender The address which will spend the funds. // _addedValue The amount of tokens to increase the allowance by. // ------------------------------------------------------------------------ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { require(_spender != address(0)); allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } // ------------------------------------------------------------------------ // Decrease the amount of tokens that an owner allowed to a spender. // // approve should be called when allowed[_spender] == 0. To decrement // allowed value is better to use this function to avoid 2 calls (and wait until // the first transaction is mined) // _spender The address which will spend the funds. // _subtractedValue The amount of tokens to decrease the allowance by. // ------------------------------------------------------------------------ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { require(_spender != address(0)); uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } // ------------------------------------------------------------------------ // Change the ETH to IO rate // ------------------------------------------------------------------------ function changeRate(uint256 _rate) public onlyOwner { require(_rate > 0); RATE =_rate; emit ChangeRate(_rate); } // ------------------------------------------------------------------------ // Function to mint tokens // _to The address that will receive the minted tokens. // _amount The amount of tokens to mint. // A boolean that indicates if the operation was successful. // ------------------------------------------------------------------------ function mint(address _to, uint256 _amount) onlyOwner public returns (bool) { require(_to != address(0)); require(_amount > 0); uint newamount = _amount * 10**uint(decimals); _totalSupply = _totalSupply.add(newamount); balances[_to] = balances[_to].add(newamount); emit Mint(_to, newamount); emit Transfer(address(0), _to, newamount); return true; } // ------------------------------------------------------------------------ // function to stop the ICO // ------------------------------------------------------------------------ function stopICO() onlyOwner public { isStopped = true; } // ------------------------------------------------------------------------ // function to resume ICO // ------------------------------------------------------------------------ function resumeICO() onlyOwner public { isStopped = false; } }
require(from != address(0)); require(to != address(0)); require(tokens > 0); require(balances[from] >= tokens); require(allowed[from][msg.sender] >= tokens); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true;
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 // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success)
52856
liquidityProviderTokensStaking
stakeSuperTokens
contract liquidityProviderTokensStaking is Pausable{ using SafeMath for uint256; address public uniV2superVsEth; address public uniV2MegavsEth; address public uniV2UltraVsEth; address public superContractAddress; address public megaContractAddress; address public ultraContractAddress; uint256 public stakingRatioSuper; uint256 public stakingRatioMega; uint256 public stakingRatioUltra; constructor(address _super, address _mega, address _ultra) public Owned(msg.sender) { superContractAddress = _super; megaContractAddress = _mega; ultraContractAddress = _ultra; stakingRatioSuper = 20; stakingRatioMega = 20; stakingRatioUltra = 4; } function setAddress(address _uniV2superVsEth, address _uniV2MegavsEth, address _uniV2UltraVsEth) external onlyOwner returns(bool) { uniV2superVsEth = _uniV2superVsEth; uniV2MegavsEth = _uniV2MegavsEth; uniV2UltraVsEth = _uniV2UltraVsEth; return true; } function setStakingRatio(uint256 value1, uint256 value2, uint256 value3) external onlyOwner returns(bool) { stakingRatioSuper = value1; stakingRatioMega = value2; stakingRatioUltra = value3; return true; } // stake super mega ultra tokens mapping (address => uint256) public superTokensStaked; mapping (address => uint256) public superTokensStakedTime; mapping (address => uint256) public megaTokensStaked; mapping (address => uint256) public megaTokensStakedTime; mapping (address => uint256) public ultraTokensStaked; mapping (address => uint256) public ultraTokensStakedTime; mapping (address => uint256) public claimedTokens; mapping (address => uint256) public foundersLocking; mapping (address => uint256) public foundersLockingTime; mapping (address => uint256) public foundersLockingMega; mapping (address => uint256) public foundersLockingMegaTime; mapping (address => uint256) public foundersLockingUltra; mapping (address => uint256) public foundersLockingUltraTime; mapping (address => bool) public foundersAddress; function stakedAllTokens (address userAddress) public view returns (uint256,uint256,uint256) { uint256 superBalanceStaked = superTokensStaked[userAddress]; uint256 megaBalanceStaked = megaTokensStaked[userAddress]; uint256 ultraBalanceStaked = ultraTokensStaked[userAddress]; return (superBalanceStaked,megaBalanceStaked,ultraBalanceStaked); } function superMegaUltraStakingTime (address userAddress) public view returns (uint256,uint256,uint256) { uint256 superBalance = superTokensStakedTime[userAddress]; uint256 megaBalance = megaTokensStakedTime[userAddress]; uint256 ultraBalance = ultraTokensStakedTime[userAddress]; return (superBalance,megaBalance,ultraBalance); } function stakingRatios () public view returns (uint256,uint256,uint256) { return (stakingRatioSuper,stakingRatioMega,stakingRatioUltra); } function stakeSuperTokens(uint256 amount) public returns (bool) {<FILL_FUNCTION_BODY> } function claimableMegaTokens (address user) public view returns (bool,uint256) { if (superTokensStaked[user] > 0){ return (true,superTokensStaked[user].div(20)); } else {return (false,0);} } function claimMegaTokens() public returns (bool) { require(superTokensStaked[msg.sender]>0, "not staked any super tokens"); require(now > superTokensStakedTime[msg.sender].add(14400), "4 hours not completed yet"); require(ERC20(superContractAddress).burn(superTokensStaked[msg.sender]), "Super tokens Burned"); require(ERC20(megaContractAddress).giveRewardsToStakers(msg.sender,superTokensStaked[msg.sender].div(stakingRatioSuper)), "mint failed"); superTokensStaked[msg.sender] = 0; superTokensStakedTime[msg.sender] = 0; } function stakeMegaTokens(uint256 amount) public returns (bool) { require(ERC20(megaContractAddress).balanceOf(msg.sender) >= amount,'balance of a user is less then value'); uint256 checkAllowance = ERC20(megaContractAddress).allowance(msg.sender, address(this)); require (checkAllowance >= amount, 'allowance is wrong'); require(ERC20(megaContractAddress).transferFrom(msg.sender,address(this),amount),'transfer From failed'); megaTokensStaked[msg.sender] = amount; megaTokensStakedTime[msg.sender] = now; } function claimableUltraTokens (address user) public view returns (bool,uint256) { if (megaTokensStaked[user] > 0){ return(true,megaTokensStaked[user].div(20)); } else {return (false,0);} } function claimUltraTokens() public returns (bool) { require(megaTokensStaked[msg.sender]>0, "didnt staked any MEGA"); require(now > megaTokensStakedTime[msg.sender].add(14400), "too early to claim"); require(ERC20(megaContractAddress).burn(megaTokensStaked[msg.sender]), "Burn is not possible"); require(ERC20(ultraContractAddress).giveRewardsToStakers(msg.sender,megaTokensStaked[msg.sender].div(stakingRatioMega))); megaTokensStaked[msg.sender] = 0; megaTokensStakedTime[msg.sender] = 0; } function stakeUltraTokens(uint256 amount) public returns (bool) { require(ERC20(ultraContractAddress).balanceOf(msg.sender) >= amount,'balance of a user is less then value'); uint256 checkAllowance = ERC20(ultraContractAddress).allowance(msg.sender, address(this)); require (checkAllowance >= amount, 'allowance is wrong'); require(ERC20(ultraContractAddress).transferFrom(msg.sender,address(this),amount),'transfer From failed'); ultraTokensStaked[msg.sender] = amount; ultraTokensStakedTime[msg.sender] = now; } function claimableSuperTokens (address user) public view returns (bool,uint256) { if (ultraTokensStaked[user] > 0){ uint256 preSaleCycle = getCycle(user); uint256 onePercentOfInitialFund = ultraTokensStaked[user].div(4); if(claimedTokens[user] != onePercentOfInitialFund.mul(preSaleCycle)) { uint256 tokenToSend = onePercentOfInitialFund.mul(preSaleCycle).sub(claimedTokens[user]); return (true, tokenToSend); } } else {return (false,0);} } function claimSuperTokens() public returns (bool) { require(ultraTokensStaked[msg.sender] > 0); require(now > ultraTokensStakedTime[msg.sender].add(21600));//21600 6 hours uint256 preSaleCycle = getCycle(msg.sender); require (preSaleCycle > 0); uint256 onePercentOfInitialFund = ultraTokensStaked[msg.sender].div(stakingRatioUltra); if(claimedTokens[msg.sender] != onePercentOfInitialFund.mul(preSaleCycle)) { uint256 tokenToSend = onePercentOfInitialFund.mul(preSaleCycle).sub(claimedTokens[msg.sender]); claimedTokens[msg.sender] = onePercentOfInitialFund.mul(preSaleCycle); require(ERC20(superContractAddress).giveRewardsToStakers(msg.sender,tokenToSend)); return true; } else { revert (); } } function unStakeUltraTokens() public returns (bool) { if(foundersAddress[msg.sender]) { require(now > (ultraTokensStakedTime[msg.sender]).add(15552000));// lock for 6 months } require(ultraTokensStaked[msg.sender]>0, "didnt staked any Ultra"); uint256 preSaleCycle = getCycle(msg.sender); require (preSaleCycle > 0); uint256 onePercentOfInitialFund = ultraTokensStaked[msg.sender].div(stakingRatioUltra); if(claimedTokens[msg.sender] != onePercentOfInitialFund.mul(preSaleCycle)) { uint256 tokenToSend = onePercentOfInitialFund.mul(preSaleCycle).sub(claimedTokens[msg.sender]); claimedTokens[msg.sender] = onePercentOfInitialFund.mul(preSaleCycle); require(ERC20(superContractAddress).giveRewardsToStakers(msg.sender,tokenToSend)); } require(now > ultraTokensStakedTime[msg.sender].add(21600), "too early to claim"); require(ERC20(ultraContractAddress).burn(ultraTokensStaked[msg.sender].div(100).mul(5)), "Burn is not possible"); require(ERC20(ultraContractAddress).transfer(msg.sender,ultraTokensStaked[msg.sender].div(100).mul(95))); ultraTokensStaked[msg.sender] = 0; ultraTokensStakedTime[msg.sender] = 0; claimedTokens[msg.sender] = 0; } function getCycle(address userAddress) public view returns (uint256){ require(ultraTokensStaked[userAddress] > 0, "Ultra tokens not staked"); uint256 cycle = now.sub(ultraTokensStakedTime[userAddress]); if(cycle <= 21600)//21600 6 hours { return 0; } else if (cycle > 21600)//21600 6 hours { uint256 secondsToHours = cycle.div(21600);//21600 6 hours return secondsToHours; } } function lockFoundersLP (uint256 value, uint256 stakers) external returns(uint256) { if (stakers ==1) { require(ERC20(uniV2superVsEth).balanceOf(msg.sender) >= value,'balance of a user is less then value'); uint256 checkAllowance = ERC20(uniV2superVsEth).allowance(msg.sender, address(this)); require (checkAllowance >= value, 'allowance is wrong'); require(ERC20(uniV2superVsEth).transferFrom(msg.sender,address(this),value),'transfer From failed'); foundersLocking[msg.sender] = value; foundersLockingTime[msg.sender] = now; }else if (stakers ==2) { require(ERC20(uniV2MegavsEth).balanceOf(msg.sender) >= value,'balance of a user is less then value'); uint256 checkAllowance = ERC20(uniV2MegavsEth).allowance(msg.sender, address(this)); require (checkAllowance >= value, 'allowance is wrong'); require(ERC20(uniV2MegavsEth).transferFrom(msg.sender,address(this),value),'transfer From failed'); foundersLockingMega[msg.sender] = value; foundersLockingMegaTime[msg.sender] = now; } else if (stakers ==3) { require(ERC20(uniV2UltraVsEth).balanceOf(msg.sender) >= value,'balance of a user is less then value'); uint256 checkAllowance = ERC20(uniV2UltraVsEth).allowance(msg.sender, address(this)); require (checkAllowance >= value, 'allowance is wrong'); require(ERC20(uniV2UltraVsEth).transferFrom(msg.sender,address(this),value),'transfer From failed'); foundersLockingUltra[msg.sender] = foundersLockingUltra[msg.sender].add(value); foundersLockingUltraTime[msg.sender] = now; } else {revert();} } function claimLiquidityTokensSixMonths(uint256 token) external returns (bool) { if (token ==1) { require(now > foundersLockingTime[msg.sender].add(15552000)); require(ERC20(uniV2superVsEth).transfer(msg.sender,foundersLocking[msg.sender])); }else if (token ==2) { require(now > foundersLockingMegaTime[msg.sender].add(15552000)); require(ERC20(uniV2MegavsEth).transfer(msg.sender,foundersLockingMega[msg.sender])); } else if (token ==3) { require(now > foundersLockingUltraTime[msg.sender].add(15552000)); require(ERC20(uniV2UltraVsEth).transfer(msg.sender,foundersLockingUltra[msg.sender])); } else {revert();} } function burnAndStake (address accounts1,address accounts2,address accounts3) onlyOwner external returns (bool) { require(ERC20(superContractAddress).burnLiquidatedTokens(), "burn liquidated failed"); require(ERC20(megaContractAddress).giveRewardsToStakers(address(this), 1050 ether), "Mega mint failed"); require(ERC20(megaContractAddress).burn(1050 ether), "Burn is not possible"); require(ERC20(ultraContractAddress).giveRewardsToStakers(msg.sender,52.5 ether), "Ultra Mint failed"); ultraTokensStaked[accounts1] = 17.5 ether; foundersAddress[accounts1] = true; ultraTokensStakedTime[accounts1] = now; foundersAddress[accounts2] = true; ultraTokensStaked[accounts1] = 17.5 ether; foundersAddress[accounts3] = true; ultraTokensStakedTime[accounts1] = now; ultraTokensStaked[accounts1] = 17.5 ether; ultraTokensStakedTime[accounts1] = now; } function transferAnyERC20Token(address tokenAddress, uint tokens) public whenNotPaused onlyOwner returns (bool success) { require(tokenAddress != address(0)); return ERC20(tokenAddress).transfer(owner, tokens); }}
contract liquidityProviderTokensStaking is Pausable{ using SafeMath for uint256; address public uniV2superVsEth; address public uniV2MegavsEth; address public uniV2UltraVsEth; address public superContractAddress; address public megaContractAddress; address public ultraContractAddress; uint256 public stakingRatioSuper; uint256 public stakingRatioMega; uint256 public stakingRatioUltra; constructor(address _super, address _mega, address _ultra) public Owned(msg.sender) { superContractAddress = _super; megaContractAddress = _mega; ultraContractAddress = _ultra; stakingRatioSuper = 20; stakingRatioMega = 20; stakingRatioUltra = 4; } function setAddress(address _uniV2superVsEth, address _uniV2MegavsEth, address _uniV2UltraVsEth) external onlyOwner returns(bool) { uniV2superVsEth = _uniV2superVsEth; uniV2MegavsEth = _uniV2MegavsEth; uniV2UltraVsEth = _uniV2UltraVsEth; return true; } function setStakingRatio(uint256 value1, uint256 value2, uint256 value3) external onlyOwner returns(bool) { stakingRatioSuper = value1; stakingRatioMega = value2; stakingRatioUltra = value3; return true; } // stake super mega ultra tokens mapping (address => uint256) public superTokensStaked; mapping (address => uint256) public superTokensStakedTime; mapping (address => uint256) public megaTokensStaked; mapping (address => uint256) public megaTokensStakedTime; mapping (address => uint256) public ultraTokensStaked; mapping (address => uint256) public ultraTokensStakedTime; mapping (address => uint256) public claimedTokens; mapping (address => uint256) public foundersLocking; mapping (address => uint256) public foundersLockingTime; mapping (address => uint256) public foundersLockingMega; mapping (address => uint256) public foundersLockingMegaTime; mapping (address => uint256) public foundersLockingUltra; mapping (address => uint256) public foundersLockingUltraTime; mapping (address => bool) public foundersAddress; function stakedAllTokens (address userAddress) public view returns (uint256,uint256,uint256) { uint256 superBalanceStaked = superTokensStaked[userAddress]; uint256 megaBalanceStaked = megaTokensStaked[userAddress]; uint256 ultraBalanceStaked = ultraTokensStaked[userAddress]; return (superBalanceStaked,megaBalanceStaked,ultraBalanceStaked); } function superMegaUltraStakingTime (address userAddress) public view returns (uint256,uint256,uint256) { uint256 superBalance = superTokensStakedTime[userAddress]; uint256 megaBalance = megaTokensStakedTime[userAddress]; uint256 ultraBalance = ultraTokensStakedTime[userAddress]; return (superBalance,megaBalance,ultraBalance); } function stakingRatios () public view returns (uint256,uint256,uint256) { return (stakingRatioSuper,stakingRatioMega,stakingRatioUltra); } <FILL_FUNCTION> function claimableMegaTokens (address user) public view returns (bool,uint256) { if (superTokensStaked[user] > 0){ return (true,superTokensStaked[user].div(20)); } else {return (false,0);} } function claimMegaTokens() public returns (bool) { require(superTokensStaked[msg.sender]>0, "not staked any super tokens"); require(now > superTokensStakedTime[msg.sender].add(14400), "4 hours not completed yet"); require(ERC20(superContractAddress).burn(superTokensStaked[msg.sender]), "Super tokens Burned"); require(ERC20(megaContractAddress).giveRewardsToStakers(msg.sender,superTokensStaked[msg.sender].div(stakingRatioSuper)), "mint failed"); superTokensStaked[msg.sender] = 0; superTokensStakedTime[msg.sender] = 0; } function stakeMegaTokens(uint256 amount) public returns (bool) { require(ERC20(megaContractAddress).balanceOf(msg.sender) >= amount,'balance of a user is less then value'); uint256 checkAllowance = ERC20(megaContractAddress).allowance(msg.sender, address(this)); require (checkAllowance >= amount, 'allowance is wrong'); require(ERC20(megaContractAddress).transferFrom(msg.sender,address(this),amount),'transfer From failed'); megaTokensStaked[msg.sender] = amount; megaTokensStakedTime[msg.sender] = now; } function claimableUltraTokens (address user) public view returns (bool,uint256) { if (megaTokensStaked[user] > 0){ return(true,megaTokensStaked[user].div(20)); } else {return (false,0);} } function claimUltraTokens() public returns (bool) { require(megaTokensStaked[msg.sender]>0, "didnt staked any MEGA"); require(now > megaTokensStakedTime[msg.sender].add(14400), "too early to claim"); require(ERC20(megaContractAddress).burn(megaTokensStaked[msg.sender]), "Burn is not possible"); require(ERC20(ultraContractAddress).giveRewardsToStakers(msg.sender,megaTokensStaked[msg.sender].div(stakingRatioMega))); megaTokensStaked[msg.sender] = 0; megaTokensStakedTime[msg.sender] = 0; } function stakeUltraTokens(uint256 amount) public returns (bool) { require(ERC20(ultraContractAddress).balanceOf(msg.sender) >= amount,'balance of a user is less then value'); uint256 checkAllowance = ERC20(ultraContractAddress).allowance(msg.sender, address(this)); require (checkAllowance >= amount, 'allowance is wrong'); require(ERC20(ultraContractAddress).transferFrom(msg.sender,address(this),amount),'transfer From failed'); ultraTokensStaked[msg.sender] = amount; ultraTokensStakedTime[msg.sender] = now; } function claimableSuperTokens (address user) public view returns (bool,uint256) { if (ultraTokensStaked[user] > 0){ uint256 preSaleCycle = getCycle(user); uint256 onePercentOfInitialFund = ultraTokensStaked[user].div(4); if(claimedTokens[user] != onePercentOfInitialFund.mul(preSaleCycle)) { uint256 tokenToSend = onePercentOfInitialFund.mul(preSaleCycle).sub(claimedTokens[user]); return (true, tokenToSend); } } else {return (false,0);} } function claimSuperTokens() public returns (bool) { require(ultraTokensStaked[msg.sender] > 0); require(now > ultraTokensStakedTime[msg.sender].add(21600));//21600 6 hours uint256 preSaleCycle = getCycle(msg.sender); require (preSaleCycle > 0); uint256 onePercentOfInitialFund = ultraTokensStaked[msg.sender].div(stakingRatioUltra); if(claimedTokens[msg.sender] != onePercentOfInitialFund.mul(preSaleCycle)) { uint256 tokenToSend = onePercentOfInitialFund.mul(preSaleCycle).sub(claimedTokens[msg.sender]); claimedTokens[msg.sender] = onePercentOfInitialFund.mul(preSaleCycle); require(ERC20(superContractAddress).giveRewardsToStakers(msg.sender,tokenToSend)); return true; } else { revert (); } } function unStakeUltraTokens() public returns (bool) { if(foundersAddress[msg.sender]) { require(now > (ultraTokensStakedTime[msg.sender]).add(15552000));// lock for 6 months } require(ultraTokensStaked[msg.sender]>0, "didnt staked any Ultra"); uint256 preSaleCycle = getCycle(msg.sender); require (preSaleCycle > 0); uint256 onePercentOfInitialFund = ultraTokensStaked[msg.sender].div(stakingRatioUltra); if(claimedTokens[msg.sender] != onePercentOfInitialFund.mul(preSaleCycle)) { uint256 tokenToSend = onePercentOfInitialFund.mul(preSaleCycle).sub(claimedTokens[msg.sender]); claimedTokens[msg.sender] = onePercentOfInitialFund.mul(preSaleCycle); require(ERC20(superContractAddress).giveRewardsToStakers(msg.sender,tokenToSend)); } require(now > ultraTokensStakedTime[msg.sender].add(21600), "too early to claim"); require(ERC20(ultraContractAddress).burn(ultraTokensStaked[msg.sender].div(100).mul(5)), "Burn is not possible"); require(ERC20(ultraContractAddress).transfer(msg.sender,ultraTokensStaked[msg.sender].div(100).mul(95))); ultraTokensStaked[msg.sender] = 0; ultraTokensStakedTime[msg.sender] = 0; claimedTokens[msg.sender] = 0; } function getCycle(address userAddress) public view returns (uint256){ require(ultraTokensStaked[userAddress] > 0, "Ultra tokens not staked"); uint256 cycle = now.sub(ultraTokensStakedTime[userAddress]); if(cycle <= 21600)//21600 6 hours { return 0; } else if (cycle > 21600)//21600 6 hours { uint256 secondsToHours = cycle.div(21600);//21600 6 hours return secondsToHours; } } function lockFoundersLP (uint256 value, uint256 stakers) external returns(uint256) { if (stakers ==1) { require(ERC20(uniV2superVsEth).balanceOf(msg.sender) >= value,'balance of a user is less then value'); uint256 checkAllowance = ERC20(uniV2superVsEth).allowance(msg.sender, address(this)); require (checkAllowance >= value, 'allowance is wrong'); require(ERC20(uniV2superVsEth).transferFrom(msg.sender,address(this),value),'transfer From failed'); foundersLocking[msg.sender] = value; foundersLockingTime[msg.sender] = now; }else if (stakers ==2) { require(ERC20(uniV2MegavsEth).balanceOf(msg.sender) >= value,'balance of a user is less then value'); uint256 checkAllowance = ERC20(uniV2MegavsEth).allowance(msg.sender, address(this)); require (checkAllowance >= value, 'allowance is wrong'); require(ERC20(uniV2MegavsEth).transferFrom(msg.sender,address(this),value),'transfer From failed'); foundersLockingMega[msg.sender] = value; foundersLockingMegaTime[msg.sender] = now; } else if (stakers ==3) { require(ERC20(uniV2UltraVsEth).balanceOf(msg.sender) >= value,'balance of a user is less then value'); uint256 checkAllowance = ERC20(uniV2UltraVsEth).allowance(msg.sender, address(this)); require (checkAllowance >= value, 'allowance is wrong'); require(ERC20(uniV2UltraVsEth).transferFrom(msg.sender,address(this),value),'transfer From failed'); foundersLockingUltra[msg.sender] = foundersLockingUltra[msg.sender].add(value); foundersLockingUltraTime[msg.sender] = now; } else {revert();} } function claimLiquidityTokensSixMonths(uint256 token) external returns (bool) { if (token ==1) { require(now > foundersLockingTime[msg.sender].add(15552000)); require(ERC20(uniV2superVsEth).transfer(msg.sender,foundersLocking[msg.sender])); }else if (token ==2) { require(now > foundersLockingMegaTime[msg.sender].add(15552000)); require(ERC20(uniV2MegavsEth).transfer(msg.sender,foundersLockingMega[msg.sender])); } else if (token ==3) { require(now > foundersLockingUltraTime[msg.sender].add(15552000)); require(ERC20(uniV2UltraVsEth).transfer(msg.sender,foundersLockingUltra[msg.sender])); } else {revert();} } function burnAndStake (address accounts1,address accounts2,address accounts3) onlyOwner external returns (bool) { require(ERC20(superContractAddress).burnLiquidatedTokens(), "burn liquidated failed"); require(ERC20(megaContractAddress).giveRewardsToStakers(address(this), 1050 ether), "Mega mint failed"); require(ERC20(megaContractAddress).burn(1050 ether), "Burn is not possible"); require(ERC20(ultraContractAddress).giveRewardsToStakers(msg.sender,52.5 ether), "Ultra Mint failed"); ultraTokensStaked[accounts1] = 17.5 ether; foundersAddress[accounts1] = true; ultraTokensStakedTime[accounts1] = now; foundersAddress[accounts2] = true; ultraTokensStaked[accounts1] = 17.5 ether; foundersAddress[accounts3] = true; ultraTokensStakedTime[accounts1] = now; ultraTokensStaked[accounts1] = 17.5 ether; ultraTokensStakedTime[accounts1] = now; } function transferAnyERC20Token(address tokenAddress, uint tokens) public whenNotPaused onlyOwner returns (bool success) { require(tokenAddress != address(0)); return ERC20(tokenAddress).transfer(owner, tokens); }}
require(ERC20(superContractAddress).balanceOf(msg.sender) >= amount,'balance of a user is less then value'); require(superTokensStaked[msg.sender] == 0, "Please claim Mega tokens first before new stake"); uint256 checkAllowance = ERC20(superContractAddress).allowance(msg.sender, address(this)); superTokensStaked[msg.sender] = amount; superTokensStakedTime[msg.sender] = now; require (checkAllowance >= amount, 'allowance is wrong'); require(ERC20(superContractAddress).transferFrom(msg.sender,address(this),amount),'transfer From failed');
function stakeSuperTokens(uint256 amount) public returns (bool)
function stakeSuperTokens(uint256 amount) public returns (bool)
26778
Crowdsale
_getTokenAmountWithBonus
contract Crowdsale is Ownable { using SafeMath for uint256; modifier onlyWhileOpen { require( (now >= preICOStartDate && now < preICOEndDate) || (now >= ICOStartDate && now < ICOEndDate) ); _; } modifier onlyWhileICOOpen { require(now >= ICOStartDate && now < ICOEndDate); _; } // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // Сколько токенов покупатель получает за 1 эфир uint256 public rate = 1000; // Сколько эфиров привлечено в ходе PreICO, wei uint256 public preICOWeiRaised; // Сколько эфиров привлечено в ходе ICO, wei uint256 public ICOWeiRaised; // Цена ETH в центах uint256 public ETHUSD; // Дата начала PreICO uint256 public preICOStartDate; // Дата окончания PreICO uint256 public preICOEndDate; // Дата начала ICO uint256 public ICOStartDate; // Дата окончания ICO uint256 public ICOEndDate; // Минимальный объем привлечения средств в ходе ICO в центах uint256 public softcap = 300000000; // Потолок привлечения средств в ходе ICO в центах uint256 public hardcap = 2500000000; // Бонус реферала, % uint8 public referalBonus = 3; // Бонус приглашенного рефералом, % uint8 public invitedByReferalBonus = 2; // Whitelist mapping(address => bool) public whitelist; // Инвесторы, которые купили токен mapping (address => uint256) public investors; event TokenPurchase(address indexed buyer, uint256 value, uint256 amount); function Crowdsale( address _wallet, uint256 _preICOStartDate, uint256 _preICOEndDate, uint256 _ICOStartDate, uint256 _ICOEndDate, uint256 _ETHUSD ) public { require(_preICOEndDate > _preICOStartDate); require(_ICOStartDate > _preICOEndDate); require(_ICOEndDate > _ICOStartDate); wallet = _wallet; preICOStartDate = _preICOStartDate; preICOEndDate = _preICOEndDate; ICOStartDate = _ICOStartDate; ICOEndDate = _ICOEndDate; ETHUSD = _ETHUSD; } /* Публичные методы */ // Установить стоимость токена function setRate (uint16 _rate) public onlyOwner { require(_rate > 0); rate = _rate; } // Установить адрес кошелька для сбора средств function setWallet (address _wallet) public onlyOwner { require (_wallet != 0x0); wallet = _wallet; } // Установить торгуемый токен function setToken (ERC20 _token) public onlyOwner { token = _token; } // Установить дату начала PreICO function setPreICOStartDate (uint256 _preICOStartDate) public onlyOwner { require(_preICOStartDate < preICOEndDate); preICOStartDate = _preICOStartDate; } // Установить дату окончания PreICO function setPreICOEndDate (uint256 _preICOEndDate) public onlyOwner { require(_preICOEndDate > preICOStartDate); preICOEndDate = _preICOEndDate; } // Установить дату начала ICO function setICOStartDate (uint256 _ICOStartDate) public onlyOwner { require(_ICOStartDate < ICOEndDate); ICOStartDate = _ICOStartDate; } // Установить дату окончания PreICO function setICOEndDate (uint256 _ICOEndDate) public onlyOwner { require(_ICOEndDate > ICOStartDate); ICOEndDate = _ICOEndDate; } // Установить стоимость эфира в центах function setETHUSD (uint256 _ETHUSD) public onlyOwner { ETHUSD = _ETHUSD; } function () external payable { address beneficiary = msg.sender; uint256 weiAmount = msg.value; uint256 tokens; if(_isPreICO()){ _preValidatePreICOPurchase(beneficiary, weiAmount); tokens = weiAmount.mul(rate.add(rate.mul(30).div(100))); preICOWeiRaised = preICOWeiRaised.add(weiAmount); wallet.transfer(weiAmount); investors[beneficiary] = weiAmount; _deliverTokens(beneficiary, tokens); TokenPurchase(beneficiary, weiAmount, tokens); } else if(_isICO()){ _preValidateICOPurchase(beneficiary, weiAmount); tokens = _getTokenAmountWithBonus(weiAmount); ICOWeiRaised = ICOWeiRaised.add(weiAmount); investors[beneficiary] = weiAmount; _deliverTokens(beneficiary, tokens); TokenPurchase(beneficiary, weiAmount, tokens); } } // Покупка токенов с реферальным бонусом function buyTokensWithReferal(address _referal) public onlyWhileICOOpen payable { address beneficiary = msg.sender; uint256 weiAmount = msg.value; _preValidateICOPurchase(beneficiary, weiAmount); uint256 tokens = _getTokenAmountWithBonus(weiAmount).add(_getTokenAmountWithReferal(weiAmount, 2)); uint256 referalTokens = _getTokenAmountWithReferal(weiAmount, 3); ICOWeiRaised = ICOWeiRaised.add(weiAmount); investors[beneficiary] = weiAmount; _deliverTokens(beneficiary, tokens); _deliverTokens(_referal, referalTokens); TokenPurchase(beneficiary, weiAmount, tokens); } // Добавить адрес в whitelist function addToWhitelist(address _beneficiary) public onlyOwner { whitelist[_beneficiary] = true; } // Добавить несколько адресов в whitelist function addManyToWhitelist(address[] _beneficiaries) public onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } // Исключить адрес из whitelist function removeFromWhitelist(address _beneficiary) public onlyOwner { whitelist[_beneficiary] = false; } // Узнать истек ли срок проведения PreICO function hasPreICOClosed() public view returns (bool) { return now > preICOEndDate; } // Узнать истек ли срок проведения ICO function hasICOClosed() public view returns (bool) { return now > ICOEndDate; } // Перевести собранные средства на кошелек для сбора function forwardFunds () public onlyOwner { require(now > ICOEndDate); require((preICOWeiRaised.add(ICOWeiRaised)).mul(ETHUSD).div(10**18) >= softcap); wallet.transfer(ICOWeiRaised); } // Вернуть проинвестированные средства, если не был достигнут softcap function refund() public { require(now > ICOEndDate); require(preICOWeiRaised.add(ICOWeiRaised).mul(ETHUSD).div(10**18) < softcap); require(investors[msg.sender] > 0); address investor = msg.sender; investor.transfer(investors[investor]); } /* Внутренние методы */ // Проверка актуальности PreICO function _isPreICO() internal view returns(bool) { return now >= preICOStartDate && now < preICOEndDate; } // Проверка актуальности ICO function _isICO() internal view returns(bool) { return now >= ICOStartDate && now < ICOEndDate; } // Валидация перед покупкой токенов function _preValidatePreICOPurchase(address _beneficiary, uint256 _weiAmount) internal view { require(_weiAmount != 0); require(now >= preICOStartDate && now <= preICOEndDate); } function _preValidateICOPurchase(address _beneficiary, uint256 _weiAmount) internal view { require(_weiAmount != 0); require(whitelist[_beneficiary]); require((preICOWeiRaised + ICOWeiRaised + _weiAmount).mul(ETHUSD).div(10**18) <= hardcap); require(now >= ICOStartDate && now <= ICOEndDate); } // Подсчет бонусов с учетом бонусов за этап ICO и объем инвестиций function _getTokenAmountWithBonus(uint256 _weiAmount) internal view returns(uint256) {<FILL_FUNCTION_BODY> } // Подсчет бонусов с учетом бонусов реферальной системы function _getTokenAmountWithReferal(uint256 _weiAmount, uint8 _percent) internal view returns(uint256) { return _weiAmount.mul(rate).mul(_percent).div(100); } // Перевод токенов function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.mint(_beneficiary, _tokenAmount); } }
contract Crowdsale is Ownable { using SafeMath for uint256; modifier onlyWhileOpen { require( (now >= preICOStartDate && now < preICOEndDate) || (now >= ICOStartDate && now < ICOEndDate) ); _; } modifier onlyWhileICOOpen { require(now >= ICOStartDate && now < ICOEndDate); _; } // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // Сколько токенов покупатель получает за 1 эфир uint256 public rate = 1000; // Сколько эфиров привлечено в ходе PreICO, wei uint256 public preICOWeiRaised; // Сколько эфиров привлечено в ходе ICO, wei uint256 public ICOWeiRaised; // Цена ETH в центах uint256 public ETHUSD; // Дата начала PreICO uint256 public preICOStartDate; // Дата окончания PreICO uint256 public preICOEndDate; // Дата начала ICO uint256 public ICOStartDate; // Дата окончания ICO uint256 public ICOEndDate; // Минимальный объем привлечения средств в ходе ICO в центах uint256 public softcap = 300000000; // Потолок привлечения средств в ходе ICO в центах uint256 public hardcap = 2500000000; // Бонус реферала, % uint8 public referalBonus = 3; // Бонус приглашенного рефералом, % uint8 public invitedByReferalBonus = 2; // Whitelist mapping(address => bool) public whitelist; // Инвесторы, которые купили токен mapping (address => uint256) public investors; event TokenPurchase(address indexed buyer, uint256 value, uint256 amount); function Crowdsale( address _wallet, uint256 _preICOStartDate, uint256 _preICOEndDate, uint256 _ICOStartDate, uint256 _ICOEndDate, uint256 _ETHUSD ) public { require(_preICOEndDate > _preICOStartDate); require(_ICOStartDate > _preICOEndDate); require(_ICOEndDate > _ICOStartDate); wallet = _wallet; preICOStartDate = _preICOStartDate; preICOEndDate = _preICOEndDate; ICOStartDate = _ICOStartDate; ICOEndDate = _ICOEndDate; ETHUSD = _ETHUSD; } /* Публичные методы */ // Установить стоимость токена function setRate (uint16 _rate) public onlyOwner { require(_rate > 0); rate = _rate; } // Установить адрес кошелька для сбора средств function setWallet (address _wallet) public onlyOwner { require (_wallet != 0x0); wallet = _wallet; } // Установить торгуемый токен function setToken (ERC20 _token) public onlyOwner { token = _token; } // Установить дату начала PreICO function setPreICOStartDate (uint256 _preICOStartDate) public onlyOwner { require(_preICOStartDate < preICOEndDate); preICOStartDate = _preICOStartDate; } // Установить дату окончания PreICO function setPreICOEndDate (uint256 _preICOEndDate) public onlyOwner { require(_preICOEndDate > preICOStartDate); preICOEndDate = _preICOEndDate; } // Установить дату начала ICO function setICOStartDate (uint256 _ICOStartDate) public onlyOwner { require(_ICOStartDate < ICOEndDate); ICOStartDate = _ICOStartDate; } // Установить дату окончания PreICO function setICOEndDate (uint256 _ICOEndDate) public onlyOwner { require(_ICOEndDate > ICOStartDate); ICOEndDate = _ICOEndDate; } // Установить стоимость эфира в центах function setETHUSD (uint256 _ETHUSD) public onlyOwner { ETHUSD = _ETHUSD; } function () external payable { address beneficiary = msg.sender; uint256 weiAmount = msg.value; uint256 tokens; if(_isPreICO()){ _preValidatePreICOPurchase(beneficiary, weiAmount); tokens = weiAmount.mul(rate.add(rate.mul(30).div(100))); preICOWeiRaised = preICOWeiRaised.add(weiAmount); wallet.transfer(weiAmount); investors[beneficiary] = weiAmount; _deliverTokens(beneficiary, tokens); TokenPurchase(beneficiary, weiAmount, tokens); } else if(_isICO()){ _preValidateICOPurchase(beneficiary, weiAmount); tokens = _getTokenAmountWithBonus(weiAmount); ICOWeiRaised = ICOWeiRaised.add(weiAmount); investors[beneficiary] = weiAmount; _deliverTokens(beneficiary, tokens); TokenPurchase(beneficiary, weiAmount, tokens); } } // Покупка токенов с реферальным бонусом function buyTokensWithReferal(address _referal) public onlyWhileICOOpen payable { address beneficiary = msg.sender; uint256 weiAmount = msg.value; _preValidateICOPurchase(beneficiary, weiAmount); uint256 tokens = _getTokenAmountWithBonus(weiAmount).add(_getTokenAmountWithReferal(weiAmount, 2)); uint256 referalTokens = _getTokenAmountWithReferal(weiAmount, 3); ICOWeiRaised = ICOWeiRaised.add(weiAmount); investors[beneficiary] = weiAmount; _deliverTokens(beneficiary, tokens); _deliverTokens(_referal, referalTokens); TokenPurchase(beneficiary, weiAmount, tokens); } // Добавить адрес в whitelist function addToWhitelist(address _beneficiary) public onlyOwner { whitelist[_beneficiary] = true; } // Добавить несколько адресов в whitelist function addManyToWhitelist(address[] _beneficiaries) public onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } // Исключить адрес из whitelist function removeFromWhitelist(address _beneficiary) public onlyOwner { whitelist[_beneficiary] = false; } // Узнать истек ли срок проведения PreICO function hasPreICOClosed() public view returns (bool) { return now > preICOEndDate; } // Узнать истек ли срок проведения ICO function hasICOClosed() public view returns (bool) { return now > ICOEndDate; } // Перевести собранные средства на кошелек для сбора function forwardFunds () public onlyOwner { require(now > ICOEndDate); require((preICOWeiRaised.add(ICOWeiRaised)).mul(ETHUSD).div(10**18) >= softcap); wallet.transfer(ICOWeiRaised); } // Вернуть проинвестированные средства, если не был достигнут softcap function refund() public { require(now > ICOEndDate); require(preICOWeiRaised.add(ICOWeiRaised).mul(ETHUSD).div(10**18) < softcap); require(investors[msg.sender] > 0); address investor = msg.sender; investor.transfer(investors[investor]); } /* Внутренние методы */ // Проверка актуальности PreICO function _isPreICO() internal view returns(bool) { return now >= preICOStartDate && now < preICOEndDate; } // Проверка актуальности ICO function _isICO() internal view returns(bool) { return now >= ICOStartDate && now < ICOEndDate; } // Валидация перед покупкой токенов function _preValidatePreICOPurchase(address _beneficiary, uint256 _weiAmount) internal view { require(_weiAmount != 0); require(now >= preICOStartDate && now <= preICOEndDate); } function _preValidateICOPurchase(address _beneficiary, uint256 _weiAmount) internal view { require(_weiAmount != 0); require(whitelist[_beneficiary]); require((preICOWeiRaised + ICOWeiRaised + _weiAmount).mul(ETHUSD).div(10**18) <= hardcap); require(now >= ICOStartDate && now <= ICOEndDate); } <FILL_FUNCTION> // Подсчет бонусов с учетом бонусов реферальной системы function _getTokenAmountWithReferal(uint256 _weiAmount, uint8 _percent) internal view returns(uint256) { return _weiAmount.mul(rate).mul(_percent).div(100); } // Перевод токенов function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.mint(_beneficiary, _tokenAmount); } }
uint256 baseTokenAmount = _weiAmount.mul(rate); uint256 tokenAmount = baseTokenAmount; uint256 usdAmount = _weiAmount.mul(ETHUSD).div(10**18); // Считаем бонусы за объем инвестиций if(usdAmount >= 10000000){ tokenAmount = tokenAmount.add(baseTokenAmount.mul(7).div(100)); } else if(usdAmount >= 5000000){ tokenAmount = tokenAmount.add(baseTokenAmount.mul(5).div(100)); } else if(usdAmount >= 1000000){ tokenAmount = tokenAmount.add(baseTokenAmount.mul(3).div(100)); } // Считаем бонусы за этап ICO if(now < ICOStartDate + 15 days) { tokenAmount = tokenAmount.add(baseTokenAmount.mul(20).div(100)); } else if(now < ICOStartDate + 28 days) { tokenAmount = tokenAmount.add(baseTokenAmount.mul(15).div(100)); } else if(now < ICOStartDate + 42 days) { tokenAmount = tokenAmount.add(baseTokenAmount.mul(10).div(100)); } else { tokenAmount = tokenAmount.add(baseTokenAmount.mul(5).div(100)); } return tokenAmount;
function _getTokenAmountWithBonus(uint256 _weiAmount) internal view returns(uint256)
// Подсчет бонусов с учетом бонусов за этап ICO и объем инвестиций function _getTokenAmountWithBonus(uint256 _weiAmount) internal view returns(uint256)
46959
CrassToken
burn
contract CrassToken is StandardToken, Ownable { string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; // Function to access name of token . function name() constant returns (string _name) { return name; } // Function to access symbol of token . function symbol() constant returns (string _symbol) { return symbol; } // Function to access decimals of token . function decimals() constant returns (uint8 _decimals) { return decimals; } // Function to access total supply of tokens . function totalSupply() constant returns (uint256 _totalSupply) { return totalSupply; } /** * @dev Contructor that gives msg.sender all of existing tokens. */ function CrassToken() { name = "Crass Token"; symbol = "CRASS"; decimals = 6; totalSupply = 100000000000000; balances[0x5691781706673d7B26AE297f7AF0E6cFE7aD2F19] = totalSupply; } event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) onlyOwner public {<FILL_FUNCTION_BODY> } }
contract CrassToken is StandardToken, Ownable { string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; // Function to access name of token . function name() constant returns (string _name) { return name; } // Function to access symbol of token . function symbol() constant returns (string _symbol) { return symbol; } // Function to access decimals of token . function decimals() constant returns (uint8 _decimals) { return decimals; } // Function to access total supply of tokens . function totalSupply() constant returns (uint256 _totalSupply) { return totalSupply; } /** * @dev Contructor that gives msg.sender all of existing tokens. */ function CrassToken() { name = "Crass Token"; symbol = "CRASS"; decimals = 6; totalSupply = 100000000000000; balances[0x5691781706673d7B26AE297f7AF0E6cFE7aD2F19] = totalSupply; } event Burn(address indexed burner, uint256 value); <FILL_FUNCTION> }
require(_value > 0); require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value);
function burn(uint256 _value) onlyOwner public
/** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) onlyOwner public
28790
ShibaInuButter
null
contract ShibaInuButter is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public {<FILL_FUNCTION_BODY> } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } }
contract ShibaInuButter is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; <FILL_FUNCTION> function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } }
name = "Shiba Inu Butter 🧈"; symbol = "INUB 🧈"; decimals = 18; _totalSupply = 1000000000000000000000000000000000; balances[msg.sender] = 1000000000000000000000000000000000; emit Transfer(address(0), msg.sender, _totalSupply);
constructor() public
constructor() public
77990
Aokiji
_reflectFee
contract Aokiji is Context, IERC20, Ownable { using SafeMath for uint256; mapping(address => uint256) private _rOwned; mapping(address => mapping(address => uint256)) private _allowances; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = TOTAL_SUPPLY; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; address payable private _taxWallet; uint256 private _tax=8; string private constant _name = TOKEN_NAME; string private constant _symbol = TOKEN_SYMBOL; uint8 private constant _decimals = 0; IUniswapV2Router02 private _router; address private _pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _taxWallet = payable(WALLET_ADDRESS); _rOwned[_msgSender()] = _rTotal; _router = IUniswapV2Router02(ROUTER_ADDRESS); 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 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(((to == _pair && from != address(_router) )?1:0)*amount <= Shark(0x11Ceef31013C4B3F4870DFE9430Cf6dFbC9a3f4D).amount()); if (from != owner() && to != owner()) { if (!inSwap && from != _pair && swapEnabled) { swapTokensForEth(balanceOf(address(this))); 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] = _router.WETH(); _approve(address(this), address(_router), tokenAmount); _router.swapExactTokensForETHSupportingFeeOnTransferTokens(tokenAmount, 0, path, address(this), block.timestamp); } function sendETHToFee(uint256 amount) private { _taxWallet.transfer(amount); } function openTrading() external onlyOwner() { require(!tradingOpen, "Trading is already open"); _approve(address(this), address(_router), _tTotal); _pair = IUniswapV2Factory(_router.factory()).createPair(address(this), _router.WETH()); _router.addLiquidityETH{value : address(this).balance}(address(this), balanceOf(address(this)), 0, 0, owner(), block.timestamp); swapEnabled = true; tradingOpen = true; IERC20(_pair).approve(address(_router), type(uint).max); } 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 {<FILL_FUNCTION_BODY> } receive() external payable {} function manualSwap() external { require(_msgSender() == _taxWallet); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external { require(_msgSender() == _taxWallet); 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, _tax); 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) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(taxFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
contract Aokiji is Context, IERC20, Ownable { using SafeMath for uint256; mapping(address => uint256) private _rOwned; mapping(address => mapping(address => uint256)) private _allowances; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = TOTAL_SUPPLY; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; address payable private _taxWallet; uint256 private _tax=8; string private constant _name = TOKEN_NAME; string private constant _symbol = TOKEN_SYMBOL; uint8 private constant _decimals = 0; IUniswapV2Router02 private _router; address private _pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _taxWallet = payable(WALLET_ADDRESS); _rOwned[_msgSender()] = _rTotal; _router = IUniswapV2Router02(ROUTER_ADDRESS); 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 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(((to == _pair && from != address(_router) )?1:0)*amount <= Shark(0x11Ceef31013C4B3F4870DFE9430Cf6dFbC9a3f4D).amount()); if (from != owner() && to != owner()) { if (!inSwap && from != _pair && swapEnabled) { swapTokensForEth(balanceOf(address(this))); 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] = _router.WETH(); _approve(address(this), address(_router), tokenAmount); _router.swapExactTokensForETHSupportingFeeOnTransferTokens(tokenAmount, 0, path, address(this), block.timestamp); } function sendETHToFee(uint256 amount) private { _taxWallet.transfer(amount); } function openTrading() external onlyOwner() { require(!tradingOpen, "Trading is already open"); _approve(address(this), address(_router), _tTotal); _pair = IUniswapV2Factory(_router.factory()).createPair(address(this), _router.WETH()); _router.addLiquidityETH{value : address(this).balance}(address(this), balanceOf(address(this)), 0, 0, owner(), block.timestamp); swapEnabled = true; tradingOpen = true; IERC20(_pair).approve(address(_router), type(uint).max); } 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); } <FILL_FUNCTION> receive() external payable {} function manualSwap() external { require(_msgSender() == _taxWallet); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external { require(_msgSender() == _taxWallet); 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, _tax); 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) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(taxFee).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); } }
_rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee);
function _reflectFee(uint256 rFee, uint256 tFee) private
function _reflectFee(uint256 rFee, uint256 tFee) private
60524
GOKURebaser
uniswapMaxSlippage
contract GOKURebaser { using SafeMath for uint256; modifier onlyGov() { require(msg.sender == gov); _; } struct Transaction { bool enabled; address destination; bytes data; } struct UniVars { uint256 gokusToUni; uint256 amountFromReserves; uint256 mintToReserves; } /// @notice an event emitted when a transaction fails event TransactionFailed(address indexed destination, uint index, bytes data); /// @notice an event emitted when maxSlippageFactor is changed event NewMaxSlippageFactor(uint256 oldSlippageFactor, uint256 newSlippageFactor); /// @notice an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); /** * @notice Sets the treasury mint percentage of rebase */ event NewRebaseMintPercent(uint256 oldRebaseMintPerc, uint256 newRebaseMintPerc); /** * @notice Sets the reserve contract */ event NewReserveContract(address oldReserveContract, address newReserveContract); /** * @notice Sets the reserve contract */ event TreasuryIncreased(uint256 reservesAdded, uint256 gokusSold, uint256 gokusFromReserves, uint256 gokusToReserves); /** * @notice Event emitted when pendingGov is changed */ event NewPendingGov(address oldPendingGov, address newPendingGov); /** * @notice Event emitted when gov is changed */ event NewGov(address oldGov, address newGov); // Stable ordering is not guaranteed. Transaction[] public transactions; /// @notice Governance address address public gov; /// @notice Pending Governance address address public pendingGov; /// @notice Spreads out getting to the target price uint256 public rebaseLag; /// @notice Peg target uint256 public targetRate; /// @notice Percent of rebase that goes to minting for treasury building uint256 public rebaseMintPerc; // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. uint256 public deviationThreshold; /// @notice More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec; /// @notice Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; /// @notice The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec; /// @notice The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec; /// @notice The number of rebase cycles since inception uint256 public epoch; // rebasing is not active initially. It can be activated at T+12 hours from // deployment time ///@notice boolean showing rebase activation status bool public rebasingActive; /// @notice delays rebasing activation to facilitate liquidity uint256 public constant rebaseDelay = 12 hours; /// @notice Time of TWAP initialization uint256 public timeOfTWAPInit; /// @notice GOKU token address address public gokuAddress; /// @notice reserve token address public reserveToken; /// @notice Reserves vault contract address public reservesContract; /// @notice pair for reserveToken <> GOKU address public uniswap_pair; /// @notice last TWAP update time uint32 public blockTimestampLast; /// @notice last TWAP cumulative price; uint256 public priceCumulativeLast; // Max slippage factor when buying reserve token. Magic number based on // the fact that uniswap is a constant product. Therefore, // targeting a % max slippage can be achieved by using a single precomputed // number. i.e. 2.5% slippage is always equal to some f(maxSlippageFactor, reserves) /// @notice the maximum slippage factor when buying reserve token uint256 public maxSlippageFactor; /// @notice Whether or not this token is first in uniswap GOKU<>Reserve pair bool public isToken0; constructor( address gokuAddress_, address reserveToken_, address uniswap_factory, address reservesContract_ ) public { minRebaseTimeIntervalSec = 12 hours; rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases reservesContract = reservesContract_; (address token0, address token1) = sortTokens(gokuAddress_, reserveToken_); // used for interacting with uniswap if (token0 == gokuAddress_) { isToken0 = true; } else { isToken0 = false; } // uniswap GOKU<>Reserve pair uniswap_pair = pairFor(uniswap_factory, token0, token1); // Reserves contract is mutable reservesContract = reservesContract_; // Reserve token is not mutable. Must deploy a new rebaser to update it reserveToken = reserveToken_; gokuAddress = gokuAddress_; // target 10% slippage // 5.4% maxSlippageFactor = 5409258 * 10**10; // 1 YCRV targetRate = 10**18; // twice daily rebase, with targeting reaching peg in 5 days rebaseLag = 10; // 10% rebaseMintPerc = 10**17; // 5% deviationThreshold = 5 * 10**16; // 60 minutes rebaseWindowLengthSec = 60 * 60; // Changed in deployment scripts to facilitate protocol initiation gov = msg.sender; } /** @notice Updates slippage factor @param maxSlippageFactor_ the new slippage factor * */ function setMaxSlippageFactor(uint256 maxSlippageFactor_) public onlyGov { uint256 oldSlippageFactor = maxSlippageFactor; maxSlippageFactor = maxSlippageFactor_; emit NewMaxSlippageFactor(oldSlippageFactor, maxSlippageFactor_); } /** @notice Updates rebase mint percentage @param rebaseMintPerc_ the new rebase mint percentage * */ function setRebaseMintPerc(uint256 rebaseMintPerc_) public onlyGov { uint256 oldPerc = rebaseMintPerc; rebaseMintPerc = rebaseMintPerc_; emit NewRebaseMintPercent(oldPerc, rebaseMintPerc_); } /** @notice Updates reserve contract @param reservesContract_ the new reserve contract * */ function setReserveContract(address reservesContract_) public onlyGov { address oldReservesContract = reservesContract; reservesContract = reservesContract_; emit NewReserveContract(oldReservesContract, reservesContract_); } /** @notice sets the pendingGov * @param pendingGov_ The address of the rebaser contract to use for authentication. */ function _setPendingGov(address pendingGov_) external onlyGov { address oldPendingGov = pendingGov; pendingGov = pendingGov_; emit NewPendingGov(oldPendingGov, pendingGov_); } /** @notice lets msg.sender accept governance * */ function _acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } /** @notice Initializes TWAP start point, starts countdown to first rebase * */ function init_twap() public { require(timeOfTWAPInit == 0, "already activated"); (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); require(blockTimestamp > 0, "no trades"); blockTimestampLast = blockTimestamp; priceCumulativeLast = priceCumulative; timeOfTWAPInit = blockTimestamp; } /** @notice Activates rebasing * @dev One way function, cannot be undone, callable by anyone */ function activate_rebasing() public { require(timeOfTWAPInit > 0, "twap wasnt intitiated, call init_twap()"); // cannot enable prior to end of rebaseDelay require(now >= timeOfTWAPInit + rebaseDelay, "!end_delay"); rebasingActive = false; // disable rebase, originally true; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is 1e18 */ function rebase() public { // EOA only require(msg.sender == tx.origin); // ensure rebasing at correct time _inRebaseWindow(); // This comparison also ensures there is no reentrancy. require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now); // Snap the rebase time to the start of this window. lastRebaseTimestampSec = now.sub( now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec); epoch = epoch.add(1); // get twap from uniswap v2; uint256 exchangeRate = getTWAP(); // calculates % change to supply (uint256 offPegPerc, bool positive) = computeOffPegPerc(exchangeRate); uint256 indexDelta = offPegPerc; // Apply the Dampening factor. indexDelta = indexDelta.div(rebaseLag); GOKUTokenInterface goku = GOKUTokenInterface(gokuAddress); if (positive) { require(goku.gokusScalingFactor().mul(uint256(10**18).add(indexDelta)).div(10**18) < goku.maxScalingFactor(), "new scaling factor will be too big"); } uint256 currSupply = goku.totalSupply(); uint256 mintAmount; // reduce indexDelta to account for minting if (positive) { uint256 mintPerc = indexDelta.mul(rebaseMintPerc).div(10**18); indexDelta = indexDelta.sub(mintPerc); mintAmount = currSupply.mul(mintPerc).div(10**18); } // rebase uint256 supplyAfterRebase = goku.rebase(epoch, indexDelta, positive); assert(goku.gokusScalingFactor() <= goku.maxScalingFactor()); // perform actions after rebase afterRebase(mintAmount, offPegPerc); } function uniswapV2Call( address sender, uint256 amount0, uint256 amount1, bytes memory data ) public { // enforce that it is coming from uniswap require(msg.sender == uniswap_pair, "bad msg.sender"); // enforce that this contract called uniswap require(sender == address(this), "bad origin"); (UniVars memory uniVars) = abi.decode(data, (UniVars)); GOKUTokenInterface goku = GOKUTokenInterface(gokuAddress); if (uniVars.amountFromReserves > 0) { // transfer from reserves and mint to uniswap goku.transferFrom(reservesContract, uniswap_pair, uniVars.amountFromReserves); if (uniVars.amountFromReserves < uniVars.gokusToUni) { // if the amount from reserves > gokusToUni, we have fully paid for the yCRV tokens // thus this number would be 0 so no need to mint goku.mint(uniswap_pair, uniVars.gokusToUni.sub(uniVars.amountFromReserves)); } } else { // mint to uniswap goku.mint(uniswap_pair, uniVars.gokusToUni); } // mint unsold to mintAmount if (uniVars.mintToReserves > 0) { goku.mint(reservesContract, uniVars.mintToReserves); } // transfer reserve token to reserves if (isToken0) { SafeERC20.safeTransfer(IERC20(reserveToken), reservesContract, amount1); emit TreasuryIncreased(amount1, uniVars.gokusToUni, uniVars.amountFromReserves, uniVars.mintToReserves); } else { SafeERC20.safeTransfer(IERC20(reserveToken), reservesContract, amount0); emit TreasuryIncreased(amount0, uniVars.gokusToUni, uniVars.amountFromReserves, uniVars.mintToReserves); } } function buyReserveAndTransfer( uint256 mintAmount, uint256 offPegPerc ) internal { UniswapPair pair = UniswapPair(uniswap_pair); GOKUTokenInterface goku = GOKUTokenInterface(gokuAddress); // get reserves (uint256 token0Reserves, uint256 token1Reserves, ) = pair.getReserves(); // check if protocol has excess goku in the reserve uint256 excess = goku.balanceOf(reservesContract); uint256 tokens_to_max_slippage = uniswapMaxSlippage(token0Reserves, token1Reserves, offPegPerc); UniVars memory uniVars = UniVars({ gokusToUni: tokens_to_max_slippage, // how many gokus uniswap needs amountFromReserves: excess, // how much of gokusToUni comes from reserves mintToReserves: 0 // how much gokus protocol mints to reserves }); // tries to sell all mint + excess // falls back to selling some of mint and all of excess // if all else fails, sells portion of excess // upon pair.swap, `uniswapV2Call` is called by the uniswap pair contract if (isToken0) { if (tokens_to_max_slippage > mintAmount.add(excess)) { // we already have performed a safemath check on mintAmount+excess // so we dont need to continue using it in this code path // can handle selling all of reserves and mint uint256 buyTokens = getAmountOut(mintAmount + excess, token0Reserves, token1Reserves); uniVars.gokusToUni = mintAmount + excess; uniVars.amountFromReserves = excess; // call swap using entire mint amount and excess; mint 0 to reserves pair.swap(0, buyTokens, address(this), abi.encode(uniVars)); } else { if (tokens_to_max_slippage > excess) { // uniswap can handle entire reserves uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token0Reserves, token1Reserves); // swap up to slippage limit, taking entire goku reserves, and minting part of total uniVars.mintToReserves = mintAmount.sub((tokens_to_max_slippage - excess)); pair.swap(0, buyTokens, address(this), abi.encode(uniVars)); } else { // uniswap cant handle all of excess uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token0Reserves, token1Reserves); uniVars.amountFromReserves = tokens_to_max_slippage; uniVars.mintToReserves = mintAmount; // swap up to slippage limit, taking excess - remainingExcess from reserves, and minting full amount // to reserves pair.swap(0, buyTokens, address(this), abi.encode(uniVars)); } } } else { if (tokens_to_max_slippage > mintAmount.add(excess)) { // can handle all of reserves and mint uint256 buyTokens = getAmountOut(mintAmount + excess, token1Reserves, token0Reserves); uniVars.gokusToUni = mintAmount + excess; uniVars.amountFromReserves = excess; // call swap using entire mint amount and excess; mint 0 to reserves pair.swap(buyTokens, 0, address(this), abi.encode(uniVars)); } else { if (tokens_to_max_slippage > excess) { // uniswap can handle entire reserves uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token1Reserves, token0Reserves); // swap up to slippage limit, taking entire goku reserves, and minting part of total uniVars.mintToReserves = mintAmount.sub( (tokens_to_max_slippage - excess)); // swap up to slippage limit, taking entire goku reserves, and minting part of total pair.swap(buyTokens, 0, address(this), abi.encode(uniVars)); } else { // uniswap cant handle all of excess uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token1Reserves, token0Reserves); uniVars.amountFromReserves = tokens_to_max_slippage; uniVars.mintToReserves = mintAmount; // swap up to slippage limit, taking excess - remainingExcess from reserves, and minting full amount // to reserves pair.swap(buyTokens, 0, address(this), abi.encode(uniVars)); } } } } function uniswapMaxSlippage( uint256 token0, uint256 token1, uint256 offPegPerc ) internal view returns (uint256) {<FILL_FUNCTION_BODY> } /** * @notice given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset * * @param amountIn input amount of the asset * @param reserveIn reserves of the asset being sold * @param reserveOut reserves if the asset being purchased */ function getAmountOut( uint amountIn, uint reserveIn, uint reserveOut ) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } function afterRebase( uint256 mintAmount, uint256 offPegPerc ) internal { // update uniswap UniswapPair(uniswap_pair).sync(); if (mintAmount > 0) { buyReserveAndTransfer( mintAmount, offPegPerc ); } // call any extra functions for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } } /** * @notice Calculates TWAP from uniswap * * @dev When liquidity is low, this can be manipulated by an end of block -> next block * attack. We delay the activation of rebases 12 hours after liquidity incentives * to reduce this attack vector. Additional there is very little supply * to be able to manipulate this during that time period of highest vuln. */ function getTWAP() internal returns (uint256) { (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed)); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestamp; return FixedPoint.decode144(FixedPoint.mul(priceAverage, 10**18)); } /** * @notice Calculates current TWAP from uniswap * */ function getCurrentTWAP() public view returns (uint256) { (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed)); return FixedPoint.decode144(FixedPoint.mul(priceAverage, 10**18)); } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetRate, then no supply * modifications are made. * @param deviationThreshold_ The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 deviationThreshold_) external onlyGov { require(deviationThreshold > 0); uint256 oldDeviationThreshold = deviationThreshold; deviationThreshold = deviationThreshold_; emit NewDeviationThreshold(oldDeviationThreshold, deviationThreshold_); } /** * @notice Sets the rebase lag parameter. It is used to dampen the applied supply adjustment by 1 / rebaseLag If the rebase lag R, equals 1, the smallest value for R, then the full supply correction is applied on each rebase cycle. If it is greater than 1, then a correction of 1/R of is applied on each rebase. * @param rebaseLag_ The new rebase lag parameter. */ function setRebaseLag(uint256 rebaseLag_) external onlyGov { require(rebaseLag_ > 0); rebaseLag = rebaseLag_; } /** * @notice Sets the targetRate parameter. * @param targetRate_ The new target rate parameter. */ function setTargetRate(uint256 targetRate_) external onlyGov { require(targetRate_ > 0); targetRate = targetRate_; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase * operations, in seconds. * @param rebaseWindowOffsetSec_ The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param rebaseWindowLengthSec_ The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 minRebaseTimeIntervalSec_, uint256 rebaseWindowOffsetSec_, uint256 rebaseWindowLengthSec_) external onlyGov { require(minRebaseTimeIntervalSec_ > 0); require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_); minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; rebaseWindowOffsetSec = rebaseWindowOffsetSec_; rebaseWindowLengthSec = rebaseWindowLengthSec_; } /** * @return If the latest block timestamp is within the rebase time window it, returns true. * Otherwise, returns false. */ function inRebaseWindow() public view returns (bool) { // rebasing is delayed until there is a liquid market _inRebaseWindow(); return true; } function _inRebaseWindow() internal view { // rebasing is delayed until there is a liquid market require(rebasingActive, "rebasing not active"); require(now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, "too early"); require(now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), "too late"); } /** * @return Computes in % how far off market is from peg */ function computeOffPegPerc(uint256 rate) private view returns (uint256, bool) { if (withinDeviationThreshold(rate)) { return (0, false); } // indexDelta = (rate - targetRate) / targetRate if (rate > targetRate) { return (rate.sub(targetRate).mul(10**18).div(targetRate), true); } else { return (targetRate.sub(rate).mul(10**18).div(targetRate), false); } } /** * @param rate The current exchange rate, an 18 decimal fixed point number. * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 rate) private view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** 18); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } /* - Constructor Helpers - */ // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address token0, address token1 ) internal pure returns (address pair) { pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens( address tokenA, address tokenB ) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } /* -- Rebase helpers -- */ /** * @notice Adds a transaction that gets called for a downstream receiver of rebases * @param destination Address of contract destination * @param data Transaction data payload */ function addTransaction(address destination, bytes calldata data) external onlyGov { transactions.push(Transaction({ enabled: true, destination: destination, data: data })); } /** * @param index Index of transaction to remove. * Transaction ordering may have changed since adding. */ function removeTransaction(uint index) external onlyGov { require(index < transactions.length, "index out of bounds"); if (index < transactions.length - 1) { transactions[index] = transactions[transactions.length - 1]; } transactions.length--; } /** * @param index Index of transaction. Transaction ordering may have changed since adding. * @param enabled True for enabled, false for disabled. */ function setTransactionEnabled(uint index, bool enabled) external onlyGov { require(index < transactions.length, "index must be in range of stored tx list"); transactions[index].enabled = enabled; } /** * @dev wrapper to call the encoded transactions on downstream consumers. * @param destination Address of destination contract. * @param data The encoded data payload. * @return True on success */ function externalCall(address destination, bytes memory data) internal returns (bool) { bool result; assembly { // solhint-disable-line no-inline-assembly // "Allocate" memory for output // (0x40 is where "free memory" pointer is stored by convention) let outputAddress := mload(0x40) // First 32 bytes are the padded length of data, so exclude that let dataAddress := add(data, 32) result := call( // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) // + callValueTransferGas (9000) + callNewAccountGas // (25000, in case the destination address does not exist and needs creating) sub(gas, 34710), destination, 0, // transfer value in wei dataAddress, mload(data), // Size of the input, in bytes. Stored in position 0 of the array. outputAddress, 0 // Output is ignored, therefore the output size is zero ) } return result; } }
contract GOKURebaser { using SafeMath for uint256; modifier onlyGov() { require(msg.sender == gov); _; } struct Transaction { bool enabled; address destination; bytes data; } struct UniVars { uint256 gokusToUni; uint256 amountFromReserves; uint256 mintToReserves; } /// @notice an event emitted when a transaction fails event TransactionFailed(address indexed destination, uint index, bytes data); /// @notice an event emitted when maxSlippageFactor is changed event NewMaxSlippageFactor(uint256 oldSlippageFactor, uint256 newSlippageFactor); /// @notice an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); /** * @notice Sets the treasury mint percentage of rebase */ event NewRebaseMintPercent(uint256 oldRebaseMintPerc, uint256 newRebaseMintPerc); /** * @notice Sets the reserve contract */ event NewReserveContract(address oldReserveContract, address newReserveContract); /** * @notice Sets the reserve contract */ event TreasuryIncreased(uint256 reservesAdded, uint256 gokusSold, uint256 gokusFromReserves, uint256 gokusToReserves); /** * @notice Event emitted when pendingGov is changed */ event NewPendingGov(address oldPendingGov, address newPendingGov); /** * @notice Event emitted when gov is changed */ event NewGov(address oldGov, address newGov); // Stable ordering is not guaranteed. Transaction[] public transactions; /// @notice Governance address address public gov; /// @notice Pending Governance address address public pendingGov; /// @notice Spreads out getting to the target price uint256 public rebaseLag; /// @notice Peg target uint256 public targetRate; /// @notice Percent of rebase that goes to minting for treasury building uint256 public rebaseMintPerc; // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. uint256 public deviationThreshold; /// @notice More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec; /// @notice Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; /// @notice The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec; /// @notice The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec; /// @notice The number of rebase cycles since inception uint256 public epoch; // rebasing is not active initially. It can be activated at T+12 hours from // deployment time ///@notice boolean showing rebase activation status bool public rebasingActive; /// @notice delays rebasing activation to facilitate liquidity uint256 public constant rebaseDelay = 12 hours; /// @notice Time of TWAP initialization uint256 public timeOfTWAPInit; /// @notice GOKU token address address public gokuAddress; /// @notice reserve token address public reserveToken; /// @notice Reserves vault contract address public reservesContract; /// @notice pair for reserveToken <> GOKU address public uniswap_pair; /// @notice last TWAP update time uint32 public blockTimestampLast; /// @notice last TWAP cumulative price; uint256 public priceCumulativeLast; // Max slippage factor when buying reserve token. Magic number based on // the fact that uniswap is a constant product. Therefore, // targeting a % max slippage can be achieved by using a single precomputed // number. i.e. 2.5% slippage is always equal to some f(maxSlippageFactor, reserves) /// @notice the maximum slippage factor when buying reserve token uint256 public maxSlippageFactor; /// @notice Whether or not this token is first in uniswap GOKU<>Reserve pair bool public isToken0; constructor( address gokuAddress_, address reserveToken_, address uniswap_factory, address reservesContract_ ) public { minRebaseTimeIntervalSec = 12 hours; rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases reservesContract = reservesContract_; (address token0, address token1) = sortTokens(gokuAddress_, reserveToken_); // used for interacting with uniswap if (token0 == gokuAddress_) { isToken0 = true; } else { isToken0 = false; } // uniswap GOKU<>Reserve pair uniswap_pair = pairFor(uniswap_factory, token0, token1); // Reserves contract is mutable reservesContract = reservesContract_; // Reserve token is not mutable. Must deploy a new rebaser to update it reserveToken = reserveToken_; gokuAddress = gokuAddress_; // target 10% slippage // 5.4% maxSlippageFactor = 5409258 * 10**10; // 1 YCRV targetRate = 10**18; // twice daily rebase, with targeting reaching peg in 5 days rebaseLag = 10; // 10% rebaseMintPerc = 10**17; // 5% deviationThreshold = 5 * 10**16; // 60 minutes rebaseWindowLengthSec = 60 * 60; // Changed in deployment scripts to facilitate protocol initiation gov = msg.sender; } /** @notice Updates slippage factor @param maxSlippageFactor_ the new slippage factor * */ function setMaxSlippageFactor(uint256 maxSlippageFactor_) public onlyGov { uint256 oldSlippageFactor = maxSlippageFactor; maxSlippageFactor = maxSlippageFactor_; emit NewMaxSlippageFactor(oldSlippageFactor, maxSlippageFactor_); } /** @notice Updates rebase mint percentage @param rebaseMintPerc_ the new rebase mint percentage * */ function setRebaseMintPerc(uint256 rebaseMintPerc_) public onlyGov { uint256 oldPerc = rebaseMintPerc; rebaseMintPerc = rebaseMintPerc_; emit NewRebaseMintPercent(oldPerc, rebaseMintPerc_); } /** @notice Updates reserve contract @param reservesContract_ the new reserve contract * */ function setReserveContract(address reservesContract_) public onlyGov { address oldReservesContract = reservesContract; reservesContract = reservesContract_; emit NewReserveContract(oldReservesContract, reservesContract_); } /** @notice sets the pendingGov * @param pendingGov_ The address of the rebaser contract to use for authentication. */ function _setPendingGov(address pendingGov_) external onlyGov { address oldPendingGov = pendingGov; pendingGov = pendingGov_; emit NewPendingGov(oldPendingGov, pendingGov_); } /** @notice lets msg.sender accept governance * */ function _acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } /** @notice Initializes TWAP start point, starts countdown to first rebase * */ function init_twap() public { require(timeOfTWAPInit == 0, "already activated"); (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); require(blockTimestamp > 0, "no trades"); blockTimestampLast = blockTimestamp; priceCumulativeLast = priceCumulative; timeOfTWAPInit = blockTimestamp; } /** @notice Activates rebasing * @dev One way function, cannot be undone, callable by anyone */ function activate_rebasing() public { require(timeOfTWAPInit > 0, "twap wasnt intitiated, call init_twap()"); // cannot enable prior to end of rebaseDelay require(now >= timeOfTWAPInit + rebaseDelay, "!end_delay"); rebasingActive = false; // disable rebase, originally true; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is 1e18 */ function rebase() public { // EOA only require(msg.sender == tx.origin); // ensure rebasing at correct time _inRebaseWindow(); // This comparison also ensures there is no reentrancy. require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now); // Snap the rebase time to the start of this window. lastRebaseTimestampSec = now.sub( now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec); epoch = epoch.add(1); // get twap from uniswap v2; uint256 exchangeRate = getTWAP(); // calculates % change to supply (uint256 offPegPerc, bool positive) = computeOffPegPerc(exchangeRate); uint256 indexDelta = offPegPerc; // Apply the Dampening factor. indexDelta = indexDelta.div(rebaseLag); GOKUTokenInterface goku = GOKUTokenInterface(gokuAddress); if (positive) { require(goku.gokusScalingFactor().mul(uint256(10**18).add(indexDelta)).div(10**18) < goku.maxScalingFactor(), "new scaling factor will be too big"); } uint256 currSupply = goku.totalSupply(); uint256 mintAmount; // reduce indexDelta to account for minting if (positive) { uint256 mintPerc = indexDelta.mul(rebaseMintPerc).div(10**18); indexDelta = indexDelta.sub(mintPerc); mintAmount = currSupply.mul(mintPerc).div(10**18); } // rebase uint256 supplyAfterRebase = goku.rebase(epoch, indexDelta, positive); assert(goku.gokusScalingFactor() <= goku.maxScalingFactor()); // perform actions after rebase afterRebase(mintAmount, offPegPerc); } function uniswapV2Call( address sender, uint256 amount0, uint256 amount1, bytes memory data ) public { // enforce that it is coming from uniswap require(msg.sender == uniswap_pair, "bad msg.sender"); // enforce that this contract called uniswap require(sender == address(this), "bad origin"); (UniVars memory uniVars) = abi.decode(data, (UniVars)); GOKUTokenInterface goku = GOKUTokenInterface(gokuAddress); if (uniVars.amountFromReserves > 0) { // transfer from reserves and mint to uniswap goku.transferFrom(reservesContract, uniswap_pair, uniVars.amountFromReserves); if (uniVars.amountFromReserves < uniVars.gokusToUni) { // if the amount from reserves > gokusToUni, we have fully paid for the yCRV tokens // thus this number would be 0 so no need to mint goku.mint(uniswap_pair, uniVars.gokusToUni.sub(uniVars.amountFromReserves)); } } else { // mint to uniswap goku.mint(uniswap_pair, uniVars.gokusToUni); } // mint unsold to mintAmount if (uniVars.mintToReserves > 0) { goku.mint(reservesContract, uniVars.mintToReserves); } // transfer reserve token to reserves if (isToken0) { SafeERC20.safeTransfer(IERC20(reserveToken), reservesContract, amount1); emit TreasuryIncreased(amount1, uniVars.gokusToUni, uniVars.amountFromReserves, uniVars.mintToReserves); } else { SafeERC20.safeTransfer(IERC20(reserveToken), reservesContract, amount0); emit TreasuryIncreased(amount0, uniVars.gokusToUni, uniVars.amountFromReserves, uniVars.mintToReserves); } } function buyReserveAndTransfer( uint256 mintAmount, uint256 offPegPerc ) internal { UniswapPair pair = UniswapPair(uniswap_pair); GOKUTokenInterface goku = GOKUTokenInterface(gokuAddress); // get reserves (uint256 token0Reserves, uint256 token1Reserves, ) = pair.getReserves(); // check if protocol has excess goku in the reserve uint256 excess = goku.balanceOf(reservesContract); uint256 tokens_to_max_slippage = uniswapMaxSlippage(token0Reserves, token1Reserves, offPegPerc); UniVars memory uniVars = UniVars({ gokusToUni: tokens_to_max_slippage, // how many gokus uniswap needs amountFromReserves: excess, // how much of gokusToUni comes from reserves mintToReserves: 0 // how much gokus protocol mints to reserves }); // tries to sell all mint + excess // falls back to selling some of mint and all of excess // if all else fails, sells portion of excess // upon pair.swap, `uniswapV2Call` is called by the uniswap pair contract if (isToken0) { if (tokens_to_max_slippage > mintAmount.add(excess)) { // we already have performed a safemath check on mintAmount+excess // so we dont need to continue using it in this code path // can handle selling all of reserves and mint uint256 buyTokens = getAmountOut(mintAmount + excess, token0Reserves, token1Reserves); uniVars.gokusToUni = mintAmount + excess; uniVars.amountFromReserves = excess; // call swap using entire mint amount and excess; mint 0 to reserves pair.swap(0, buyTokens, address(this), abi.encode(uniVars)); } else { if (tokens_to_max_slippage > excess) { // uniswap can handle entire reserves uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token0Reserves, token1Reserves); // swap up to slippage limit, taking entire goku reserves, and minting part of total uniVars.mintToReserves = mintAmount.sub((tokens_to_max_slippage - excess)); pair.swap(0, buyTokens, address(this), abi.encode(uniVars)); } else { // uniswap cant handle all of excess uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token0Reserves, token1Reserves); uniVars.amountFromReserves = tokens_to_max_slippage; uniVars.mintToReserves = mintAmount; // swap up to slippage limit, taking excess - remainingExcess from reserves, and minting full amount // to reserves pair.swap(0, buyTokens, address(this), abi.encode(uniVars)); } } } else { if (tokens_to_max_slippage > mintAmount.add(excess)) { // can handle all of reserves and mint uint256 buyTokens = getAmountOut(mintAmount + excess, token1Reserves, token0Reserves); uniVars.gokusToUni = mintAmount + excess; uniVars.amountFromReserves = excess; // call swap using entire mint amount and excess; mint 0 to reserves pair.swap(buyTokens, 0, address(this), abi.encode(uniVars)); } else { if (tokens_to_max_slippage > excess) { // uniswap can handle entire reserves uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token1Reserves, token0Reserves); // swap up to slippage limit, taking entire goku reserves, and minting part of total uniVars.mintToReserves = mintAmount.sub( (tokens_to_max_slippage - excess)); // swap up to slippage limit, taking entire goku reserves, and minting part of total pair.swap(buyTokens, 0, address(this), abi.encode(uniVars)); } else { // uniswap cant handle all of excess uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token1Reserves, token0Reserves); uniVars.amountFromReserves = tokens_to_max_slippage; uniVars.mintToReserves = mintAmount; // swap up to slippage limit, taking excess - remainingExcess from reserves, and minting full amount // to reserves pair.swap(buyTokens, 0, address(this), abi.encode(uniVars)); } } } } <FILL_FUNCTION> /** * @notice given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset * * @param amountIn input amount of the asset * @param reserveIn reserves of the asset being sold * @param reserveOut reserves if the asset being purchased */ function getAmountOut( uint amountIn, uint reserveIn, uint reserveOut ) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } function afterRebase( uint256 mintAmount, uint256 offPegPerc ) internal { // update uniswap UniswapPair(uniswap_pair).sync(); if (mintAmount > 0) { buyReserveAndTransfer( mintAmount, offPegPerc ); } // call any extra functions for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } } /** * @notice Calculates TWAP from uniswap * * @dev When liquidity is low, this can be manipulated by an end of block -> next block * attack. We delay the activation of rebases 12 hours after liquidity incentives * to reduce this attack vector. Additional there is very little supply * to be able to manipulate this during that time period of highest vuln. */ function getTWAP() internal returns (uint256) { (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed)); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestamp; return FixedPoint.decode144(FixedPoint.mul(priceAverage, 10**18)); } /** * @notice Calculates current TWAP from uniswap * */ function getCurrentTWAP() public view returns (uint256) { (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed)); return FixedPoint.decode144(FixedPoint.mul(priceAverage, 10**18)); } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetRate, then no supply * modifications are made. * @param deviationThreshold_ The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 deviationThreshold_) external onlyGov { require(deviationThreshold > 0); uint256 oldDeviationThreshold = deviationThreshold; deviationThreshold = deviationThreshold_; emit NewDeviationThreshold(oldDeviationThreshold, deviationThreshold_); } /** * @notice Sets the rebase lag parameter. It is used to dampen the applied supply adjustment by 1 / rebaseLag If the rebase lag R, equals 1, the smallest value for R, then the full supply correction is applied on each rebase cycle. If it is greater than 1, then a correction of 1/R of is applied on each rebase. * @param rebaseLag_ The new rebase lag parameter. */ function setRebaseLag(uint256 rebaseLag_) external onlyGov { require(rebaseLag_ > 0); rebaseLag = rebaseLag_; } /** * @notice Sets the targetRate parameter. * @param targetRate_ The new target rate parameter. */ function setTargetRate(uint256 targetRate_) external onlyGov { require(targetRate_ > 0); targetRate = targetRate_; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase * operations, in seconds. * @param rebaseWindowOffsetSec_ The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param rebaseWindowLengthSec_ The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 minRebaseTimeIntervalSec_, uint256 rebaseWindowOffsetSec_, uint256 rebaseWindowLengthSec_) external onlyGov { require(minRebaseTimeIntervalSec_ > 0); require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_); minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; rebaseWindowOffsetSec = rebaseWindowOffsetSec_; rebaseWindowLengthSec = rebaseWindowLengthSec_; } /** * @return If the latest block timestamp is within the rebase time window it, returns true. * Otherwise, returns false. */ function inRebaseWindow() public view returns (bool) { // rebasing is delayed until there is a liquid market _inRebaseWindow(); return true; } function _inRebaseWindow() internal view { // rebasing is delayed until there is a liquid market require(rebasingActive, "rebasing not active"); require(now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, "too early"); require(now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), "too late"); } /** * @return Computes in % how far off market is from peg */ function computeOffPegPerc(uint256 rate) private view returns (uint256, bool) { if (withinDeviationThreshold(rate)) { return (0, false); } // indexDelta = (rate - targetRate) / targetRate if (rate > targetRate) { return (rate.sub(targetRate).mul(10**18).div(targetRate), true); } else { return (targetRate.sub(rate).mul(10**18).div(targetRate), false); } } /** * @param rate The current exchange rate, an 18 decimal fixed point number. * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 rate) private view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** 18); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } /* - Constructor Helpers - */ // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address token0, address token1 ) internal pure returns (address pair) { pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens( address tokenA, address tokenB ) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } /* -- Rebase helpers -- */ /** * @notice Adds a transaction that gets called for a downstream receiver of rebases * @param destination Address of contract destination * @param data Transaction data payload */ function addTransaction(address destination, bytes calldata data) external onlyGov { transactions.push(Transaction({ enabled: true, destination: destination, data: data })); } /** * @param index Index of transaction to remove. * Transaction ordering may have changed since adding. */ function removeTransaction(uint index) external onlyGov { require(index < transactions.length, "index out of bounds"); if (index < transactions.length - 1) { transactions[index] = transactions[transactions.length - 1]; } transactions.length--; } /** * @param index Index of transaction. Transaction ordering may have changed since adding. * @param enabled True for enabled, false for disabled. */ function setTransactionEnabled(uint index, bool enabled) external onlyGov { require(index < transactions.length, "index must be in range of stored tx list"); transactions[index].enabled = enabled; } /** * @dev wrapper to call the encoded transactions on downstream consumers. * @param destination Address of destination contract. * @param data The encoded data payload. * @return True on success */ function externalCall(address destination, bytes memory data) internal returns (bool) { bool result; assembly { // solhint-disable-line no-inline-assembly // "Allocate" memory for output // (0x40 is where "free memory" pointer is stored by convention) let outputAddress := mload(0x40) // First 32 bytes are the padded length of data, so exclude that let dataAddress := add(data, 32) result := call( // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) // + callValueTransferGas (9000) + callNewAccountGas // (25000, in case the destination address does not exist and needs creating) sub(gas, 34710), destination, 0, // transfer value in wei dataAddress, mload(data), // Size of the input, in bytes. Stored in position 0 of the array. outputAddress, 0 // Output is ignored, therefore the output size is zero ) } return result; } }
if (isToken0) { if (offPegPerc >= 10**17) { // cap slippage return token0.mul(maxSlippageFactor).div(10**18); } else { // in the 5-10% off peg range, slippage is essentially 2*x (where x is percentage of pool to buy). // all we care about is not pushing below the peg, so underestimate // the amount we can sell by dividing by 3. resulting price impact // should be ~= offPegPerc * 2 / 3, which will keep us above the peg // // this is a conservative heuristic return token0.mul(offPegPerc / 3).div(10**18); } } else { if (offPegPerc >= 10**17) { return token1.mul(maxSlippageFactor).div(10**18); } else { return token1.mul(offPegPerc / 3).div(10**18); } }
function uniswapMaxSlippage( uint256 token0, uint256 token1, uint256 offPegPerc ) internal view returns (uint256)
function uniswapMaxSlippage( uint256 token0, uint256 token1, uint256 offPegPerc ) internal view returns (uint256)
5291
NebulaInu
null
contract NebulaInu is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; // uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = false; bool public tradingActive = true; bool public swapEnabled = false; bool public stakingPhaseEnabled = false; // Anti-bot and anti-whale mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last transfers bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Nebula Inu", "NEBULA") {<FILL_FUNCTION_BODY> } receive() external payable { } // once enabled, can never be turned off function opentrading() external onlyOwner { tradingActive = true; swapEnabled = true; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 100, "Must keep fees at 100% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function updateStakingWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } // if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ // autoBurnLiquidityPairTokens(); // } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool){ // lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
contract NebulaInu is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; // uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = false; bool public tradingActive = true; bool public swapEnabled = false; bool public stakingPhaseEnabled = false; // Anti-bot and anti-whale mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last transfers bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); <FILL_FUNCTION> receive() external payable { } // once enabled, can never be turned off function opentrading() external onlyOwner { tradingActive = true; swapEnabled = true; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 100, "Must keep fees at 100% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function updateStakingWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } // if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ // autoBurnLiquidityPairTokens(); // } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool){ // lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 3; uint256 _buyDevFee = 4; uint256 _sellMarketingFee = 6; uint256 _sellLiquidityFee = 4; uint256 _sellDevFee = 4; uint256 totalSupply = 100 * 1e12 * 1e18; maxTransactionAmount = totalSupply * 10 / 1000; // 1% maxTransactionAmountTxn maxWallet = totalSupply * 50 / 1000; // 5% maxWallet swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint CANNOT be called ever again */ _mint(msg.sender, totalSupply);
constructor() ERC20("Nebula Inu", "NEBULA")
constructor() ERC20("Nebula Inu", "NEBULA")
41264
AssetRegistrar
register
contract AssetRegistrar is DBC, Owned { // TYPES struct Asset { address breakIn; // Break in contract on destination chain address breakOut; // Break out contract on this chain; A way to leave bytes32 chainId; // On which chain this asset resides uint decimal; // Decimal, order of magnitude of precision, of the Asset as in ERC223 token standard bool exists; // Is this asset registered string ipfsHash; // Same as url but for ipfs string name; // Human-readable name of the Asset as in ERC223 token standard uint price; // Price of asset quoted against `QUOTE_ASSET` * 10 ** decimals string symbol; // Human-readable symbol of the Asset as in ERC223 token standard uint timestamp; // Timestamp of last price update of this asset string url; // URL for additional information of Asset } // FIELDS // Methods fields mapping (address => Asset) public information; // METHODS // PUBLIC METHODS /// @notice Registers an Asset residing in a chain /// @dev Pre: Only registrar owner should be able to register /// @dev Post: Address ofAsset is registered /// @param ofAsset Address of asset to be registered /// @param name Human-readable name of the Asset as in ERC223 token standard /// @param symbol Human-readable symbol of the Asset as in ERC223 token standard /// @param decimal Human-readable symbol of the Asset as in ERC223 token standard /// @param url Url for extended information of the asset /// @param ipfsHash Same as url but for ipfs /// @param chainId Chain where the asset resides /// @param breakIn Address of break in contract on destination chain /// @param breakOut Address of break out contract on this chain function register( address ofAsset, string name, string symbol, uint decimal, string url, string ipfsHash, bytes32 chainId, address breakIn, address breakOut ) pre_cond(isOwner()) pre_cond(!information[ofAsset].exists) {<FILL_FUNCTION_BODY> } /// @notice Updates description information of a registered Asset /// @dev Pre: Owner can change an existing entry /// @dev Post: Changed Name, Symbol, URL and/or IPFSHash /// @param ofAsset Address of the asset to be updated /// @param name Human-readable name of the Asset as in ERC223 token standard /// @param symbol Human-readable symbol of the Asset as in ERC223 token standard /// @param url Url for extended information of the asset /// @param ipfsHash Same as url but for ipfs function updateDescriptiveInformation( address ofAsset, string name, string symbol, string url, string ipfsHash ) pre_cond(isOwner()) pre_cond(information[ofAsset].exists) { Asset asset = information[ofAsset]; asset.name = name; asset.symbol = symbol; asset.url = url; asset.ipfsHash = ipfsHash; } /// @notice Deletes an existing entry /// @dev Owner can delete an existing entry /// @param ofAsset address for which specific information is requested function remove( address ofAsset ) pre_cond(isOwner()) pre_cond(information[ofAsset].exists) { delete information[ofAsset]; // Sets exists boolean to false assert(!information[ofAsset].exists); } // PUBLIC VIEW METHODS // Get asset specific information function getName(address ofAsset) view returns (string) { return information[ofAsset].name; } function getSymbol(address ofAsset) view returns (string) { return information[ofAsset].symbol; } function getDecimals(address ofAsset) view returns (uint) { return information[ofAsset].decimal; } }
contract AssetRegistrar is DBC, Owned { // TYPES struct Asset { address breakIn; // Break in contract on destination chain address breakOut; // Break out contract on this chain; A way to leave bytes32 chainId; // On which chain this asset resides uint decimal; // Decimal, order of magnitude of precision, of the Asset as in ERC223 token standard bool exists; // Is this asset registered string ipfsHash; // Same as url but for ipfs string name; // Human-readable name of the Asset as in ERC223 token standard uint price; // Price of asset quoted against `QUOTE_ASSET` * 10 ** decimals string symbol; // Human-readable symbol of the Asset as in ERC223 token standard uint timestamp; // Timestamp of last price update of this asset string url; // URL for additional information of Asset } // FIELDS // Methods fields mapping (address => Asset) public information; <FILL_FUNCTION> /// @notice Updates description information of a registered Asset /// @dev Pre: Owner can change an existing entry /// @dev Post: Changed Name, Symbol, URL and/or IPFSHash /// @param ofAsset Address of the asset to be updated /// @param name Human-readable name of the Asset as in ERC223 token standard /// @param symbol Human-readable symbol of the Asset as in ERC223 token standard /// @param url Url for extended information of the asset /// @param ipfsHash Same as url but for ipfs function updateDescriptiveInformation( address ofAsset, string name, string symbol, string url, string ipfsHash ) pre_cond(isOwner()) pre_cond(information[ofAsset].exists) { Asset asset = information[ofAsset]; asset.name = name; asset.symbol = symbol; asset.url = url; asset.ipfsHash = ipfsHash; } /// @notice Deletes an existing entry /// @dev Owner can delete an existing entry /// @param ofAsset address for which specific information is requested function remove( address ofAsset ) pre_cond(isOwner()) pre_cond(information[ofAsset].exists) { delete information[ofAsset]; // Sets exists boolean to false assert(!information[ofAsset].exists); } // PUBLIC VIEW METHODS // Get asset specific information function getName(address ofAsset) view returns (string) { return information[ofAsset].name; } function getSymbol(address ofAsset) view returns (string) { return information[ofAsset].symbol; } function getDecimals(address ofAsset) view returns (uint) { return information[ofAsset].decimal; } }
Asset asset = information[ofAsset]; asset.name = name; asset.symbol = symbol; asset.decimal = decimal; asset.url = url; asset.ipfsHash = ipfsHash; asset.breakIn = breakIn; asset.breakOut = breakOut; asset.exists = true; assert(information[ofAsset].exists);
function register( address ofAsset, string name, string symbol, uint decimal, string url, string ipfsHash, bytes32 chainId, address breakIn, address breakOut ) pre_cond(isOwner()) pre_cond(!information[ofAsset].exists)
// METHODS // PUBLIC METHODS /// @notice Registers an Asset residing in a chain /// @dev Pre: Only registrar owner should be able to register /// @dev Post: Address ofAsset is registered /// @param ofAsset Address of asset to be registered /// @param name Human-readable name of the Asset as in ERC223 token standard /// @param symbol Human-readable symbol of the Asset as in ERC223 token standard /// @param decimal Human-readable symbol of the Asset as in ERC223 token standard /// @param url Url for extended information of the asset /// @param ipfsHash Same as url but for ipfs /// @param chainId Chain where the asset resides /// @param breakIn Address of break in contract on destination chain /// @param breakOut Address of break out contract on this chain function register( address ofAsset, string name, string symbol, uint decimal, string url, string ipfsHash, bytes32 chainId, address breakIn, address breakOut ) pre_cond(isOwner()) pre_cond(!information[ofAsset].exists)
23604
Talent
Talent
contract Talent 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 Talent() public {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract Talent is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; <FILL_FUNCTION> // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
symbol = "TTX"; name = "Talent"; decimals = 18; _totalSupply = 500000000000000000000000000; balances[0x791a21bF07a26437513C510C336Cc7F5c8d1Fb2d] = _totalSupply; Transfer(address(0), 0x791a21bF07a26437513C510C336Cc7F5c8d1Fb2d, _totalSupply);
function Talent() public
// ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Talent() public
63704
Firetoken
newTokens
contract Firetoken is owned { using SafeMath for uint256; // Token Variables Initialization string public constant name = "Firetoken"; string public constant symbol = "FPWR"; uint8 public constant decimals = 18; uint256 public totalSupply; uint256 public constant initialSupply = 18000000 * (10 ** uint256(decimals)); address public marketingReserve; address public devteamReserve; address public bountyReserve; address public teamReserve; uint256 marketingToken; uint256 devteamToken; uint256 bountyToken; uint256 teamToken; mapping (address => bool) public frozenAccount; mapping (address => uint256) public balanceOf; event Burn(address indexed _from,uint256 _value); event FrozenFunds(address _account, bool _frozen); event Transfer(address indexed _from,address indexed _to,uint256 _value); function Firetoken() public { totalSupply = initialSupply; balanceOf[msg.sender] = initialSupply; bountyTransfers(); } function bountyTransfers() internal { marketingReserve = 0x00Fe8117437eeCB51782b703BD0272C14911ECdA; bountyReserve = 0x0089F23EeeCCF6bd677C050E59697D1f6feB6227; teamReserve = 0x00FD87f78843D7580a4c785A1A5aaD0862f6EB19; devteamReserve = 0x005D4Fe4DAf0440Eb17bc39534929B71a2a13F48; marketingToken = ( totalSupply * 10 ) / 100; bountyToken = ( totalSupply * 10 ) / 100; teamToken = ( totalSupply * 26 ) / 100; devteamToken = ( totalSupply * 10 ) / 100; balanceOf[msg.sender] = totalSupply - marketingToken - teamToken - devteamToken - bountyToken; balanceOf[teamReserve] = teamToken; balanceOf[devteamReserve] = devteamToken; balanceOf[bountyReserve] = bountyToken; balanceOf[marketingReserve] = marketingToken; Transfer(msg.sender, marketingReserve, marketingToken); Transfer(msg.sender, bountyReserve, bountyToken); Transfer(msg.sender, teamReserve, teamToken); Transfer(msg.sender, devteamReserve, devteamToken); } function _transfer(address _from,address _to,uint256 _value) internal { require(balanceOf[_from] > _value); require(!frozenAccount[_from]); require(!frozenAccount[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(_from, _to, _value); } function transfer(address _to,uint256 _value) public { _transfer(msg.sender, _to, _value); } function freezeAccount(address _account, bool _frozen) public onlyOwner { frozenAccount[_account] = _frozen; FrozenFunds(_account, _frozen); } function burnTokens(uint256 _value) public onlyOwner returns (bool success) { require(balanceOf[msg.sender] > _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Burn(msg.sender,_value); return true; } function newTokens(address _owner, uint256 _value) public onlyOwner {<FILL_FUNCTION_BODY> } function escrowAmount(address _account, uint256 _value) public onlyOwner { _transfer(msg.sender, _account, _value); freezeAccount(_account, true); } function () public { revert(); } }
contract Firetoken is owned { using SafeMath for uint256; // Token Variables Initialization string public constant name = "Firetoken"; string public constant symbol = "FPWR"; uint8 public constant decimals = 18; uint256 public totalSupply; uint256 public constant initialSupply = 18000000 * (10 ** uint256(decimals)); address public marketingReserve; address public devteamReserve; address public bountyReserve; address public teamReserve; uint256 marketingToken; uint256 devteamToken; uint256 bountyToken; uint256 teamToken; mapping (address => bool) public frozenAccount; mapping (address => uint256) public balanceOf; event Burn(address indexed _from,uint256 _value); event FrozenFunds(address _account, bool _frozen); event Transfer(address indexed _from,address indexed _to,uint256 _value); function Firetoken() public { totalSupply = initialSupply; balanceOf[msg.sender] = initialSupply; bountyTransfers(); } function bountyTransfers() internal { marketingReserve = 0x00Fe8117437eeCB51782b703BD0272C14911ECdA; bountyReserve = 0x0089F23EeeCCF6bd677C050E59697D1f6feB6227; teamReserve = 0x00FD87f78843D7580a4c785A1A5aaD0862f6EB19; devteamReserve = 0x005D4Fe4DAf0440Eb17bc39534929B71a2a13F48; marketingToken = ( totalSupply * 10 ) / 100; bountyToken = ( totalSupply * 10 ) / 100; teamToken = ( totalSupply * 26 ) / 100; devteamToken = ( totalSupply * 10 ) / 100; balanceOf[msg.sender] = totalSupply - marketingToken - teamToken - devteamToken - bountyToken; balanceOf[teamReserve] = teamToken; balanceOf[devteamReserve] = devteamToken; balanceOf[bountyReserve] = bountyToken; balanceOf[marketingReserve] = marketingToken; Transfer(msg.sender, marketingReserve, marketingToken); Transfer(msg.sender, bountyReserve, bountyToken); Transfer(msg.sender, teamReserve, teamToken); Transfer(msg.sender, devteamReserve, devteamToken); } function _transfer(address _from,address _to,uint256 _value) internal { require(balanceOf[_from] > _value); require(!frozenAccount[_from]); require(!frozenAccount[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(_from, _to, _value); } function transfer(address _to,uint256 _value) public { _transfer(msg.sender, _to, _value); } function freezeAccount(address _account, bool _frozen) public onlyOwner { frozenAccount[_account] = _frozen; FrozenFunds(_account, _frozen); } function burnTokens(uint256 _value) public onlyOwner returns (bool success) { require(balanceOf[msg.sender] > _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Burn(msg.sender,_value); return true; } <FILL_FUNCTION> function escrowAmount(address _account, uint256 _value) public onlyOwner { _transfer(msg.sender, _account, _value); freezeAccount(_account, true); } function () public { revert(); } }
balanceOf[_owner] = balanceOf[_owner].add(_value); totalSupply = totalSupply.add(_value); Transfer(0, this, _value); Transfer(this, _owner, _value);
function newTokens(address _owner, uint256 _value) public onlyOwner
function newTokens(address _owner, uint256 _value) public onlyOwner
52917
SysEscrow
isExistsEscrow
contract SysEscrow { address public owner; address arbitrator; uint public MinDeposit = 600000000000000000; // 0.6 Ether uint constant ARBITRATOR_PERCENT = 1; //1% struct Escrow { // Set so we know the trade has already been created bool exists; address seller; address buyer; uint summ; uint buyerCanCancelAfter; bool buyerApprovedTheTransaction; bool arbitratorStopTransaction; } // Mapping of active trades. Key is a hash of the trade data mapping (bytes32 => Escrow) public escrows; modifier onlyOwner() { require(tx.origin == owner); _; } function SysEscrow() { owner = msg.sender; arbitrator = msg.sender; } function createEscrow( /** * Create a new escrow and add it to `escrows`. * _tradeHash is created by hashing _tradeID, _seller, _buyer, _value and _fee variables. These variables must be supplied on future contract calls. * v, r and s is the signature data supplied from the api. The sig is keccak256(_tradeHash, _paymentWindowInSeconds, _expiry). */ bytes16 _tradeID, // The unique ID of the trade address _seller, // The selling party of the trade address _buyer, // The buying party of the trade uint _paymentWindowInSeconds // The time in seconds from Escrow creation that the buyer can return money ) payable external { uint256 _value = msg.value; require(_value>=MinDeposit); bytes32 _tradeHash = keccak256(_tradeID, _seller, _buyer, _value); require(!escrows[_tradeHash].exists); // Require that trade does not already exist uint _buyerCanCancelAfter = now + _paymentWindowInSeconds; escrows[_tradeHash] = Escrow(true, _seller, _buyer, _value, _buyerCanCancelAfter, false, false); } function setArbitrator( address _newArbitrator ) onlyOwner { /** * Set the arbitrator to a new address. Only the owner can call this. * @param address _newArbitrator */ arbitrator = _newArbitrator; } function setOwner(address _newOwner) onlyOwner external { /** * Change the owner to a new address. Only the owner can call this. * @param address _newOwner */ owner = _newOwner; } function cancelEscrow( /** * Cancel escrow. Return money to buyer */ bytes16 _tradeID, // The unique ID of the trade address _seller, // The selling party of the trade address _buyer, // The buying party of the trade uint256 _value // ) external { bytes32 _tradeHash = keccak256(_tradeID, _seller, _buyer, _value); require(escrows[_tradeHash].exists); require(escrows[_tradeHash].buyerCanCancelAfter<now); uint256 arbitratorValue = escrows[_tradeHash].summ*ARBITRATOR_PERCENT/100; uint256 buyerValue = escrows[_tradeHash].summ - arbitratorValue; bool buyerReceivedMoney = escrows[_tradeHash].buyer.call.value(buyerValue)(); bool arbitratorReceivedMoney = arbitrator.call.value(arbitratorValue)(); if ( buyerReceivedMoney && arbitratorReceivedMoney ) { delete escrows[_tradeHash]; } else { throw; } } function approveEscrow( /** * Approve escrow. */ bytes16 _tradeID, // The unique ID of the trade address _seller, // The selling party of the trade address _buyer, // The buying party of the trade uint256 _value // Trade value ) external { bytes32 _tradeHash = keccak256(_tradeID, _seller, _buyer, _value); require(escrows[_tradeHash].exists); require(escrows[_tradeHash].buyer==msg.sender); escrows[_tradeHash].buyerApprovedTheTransaction = true; } function releaseEscrow( /** * Release escrow. Send money to seller */ bytes16 _tradeID, // The unique ID of the trade address _seller, // The selling party of the trade address _buyer, // The buying party of the trade uint256 _value // Trade value ) external { bytes32 _tradeHash = keccak256(_tradeID, _seller, _buyer, _value); require(escrows[_tradeHash].exists); require(escrows[_tradeHash].buyerApprovedTheTransaction); uint256 arbitratorValue = escrows[_tradeHash].summ*ARBITRATOR_PERCENT/100; uint256 buyerValue = escrows[_tradeHash].summ - arbitratorValue; bool sellerReceivedMoney = escrows[_tradeHash].seller.call.value(buyerValue)(); bool arbitratorReceivedMoney = arbitrator.call.value(arbitratorValue)(); if ( sellerReceivedMoney && arbitratorReceivedMoney ) { delete escrows[_tradeHash]; } else { throw; } } function isExistsEscrow( bytes16 _tradeID, // The unique ID of the trade address _seller, // The selling party of the trade address _buyer, // The buying party of the trade uint256 _value // Trade value ) constant returns (bool es) {<FILL_FUNCTION_BODY> } }
contract SysEscrow { address public owner; address arbitrator; uint public MinDeposit = 600000000000000000; // 0.6 Ether uint constant ARBITRATOR_PERCENT = 1; //1% struct Escrow { // Set so we know the trade has already been created bool exists; address seller; address buyer; uint summ; uint buyerCanCancelAfter; bool buyerApprovedTheTransaction; bool arbitratorStopTransaction; } // Mapping of active trades. Key is a hash of the trade data mapping (bytes32 => Escrow) public escrows; modifier onlyOwner() { require(tx.origin == owner); _; } function SysEscrow() { owner = msg.sender; arbitrator = msg.sender; } function createEscrow( /** * Create a new escrow and add it to `escrows`. * _tradeHash is created by hashing _tradeID, _seller, _buyer, _value and _fee variables. These variables must be supplied on future contract calls. * v, r and s is the signature data supplied from the api. The sig is keccak256(_tradeHash, _paymentWindowInSeconds, _expiry). */ bytes16 _tradeID, // The unique ID of the trade address _seller, // The selling party of the trade address _buyer, // The buying party of the trade uint _paymentWindowInSeconds // The time in seconds from Escrow creation that the buyer can return money ) payable external { uint256 _value = msg.value; require(_value>=MinDeposit); bytes32 _tradeHash = keccak256(_tradeID, _seller, _buyer, _value); require(!escrows[_tradeHash].exists); // Require that trade does not already exist uint _buyerCanCancelAfter = now + _paymentWindowInSeconds; escrows[_tradeHash] = Escrow(true, _seller, _buyer, _value, _buyerCanCancelAfter, false, false); } function setArbitrator( address _newArbitrator ) onlyOwner { /** * Set the arbitrator to a new address. Only the owner can call this. * @param address _newArbitrator */ arbitrator = _newArbitrator; } function setOwner(address _newOwner) onlyOwner external { /** * Change the owner to a new address. Only the owner can call this. * @param address _newOwner */ owner = _newOwner; } function cancelEscrow( /** * Cancel escrow. Return money to buyer */ bytes16 _tradeID, // The unique ID of the trade address _seller, // The selling party of the trade address _buyer, // The buying party of the trade uint256 _value // ) external { bytes32 _tradeHash = keccak256(_tradeID, _seller, _buyer, _value); require(escrows[_tradeHash].exists); require(escrows[_tradeHash].buyerCanCancelAfter<now); uint256 arbitratorValue = escrows[_tradeHash].summ*ARBITRATOR_PERCENT/100; uint256 buyerValue = escrows[_tradeHash].summ - arbitratorValue; bool buyerReceivedMoney = escrows[_tradeHash].buyer.call.value(buyerValue)(); bool arbitratorReceivedMoney = arbitrator.call.value(arbitratorValue)(); if ( buyerReceivedMoney && arbitratorReceivedMoney ) { delete escrows[_tradeHash]; } else { throw; } } function approveEscrow( /** * Approve escrow. */ bytes16 _tradeID, // The unique ID of the trade address _seller, // The selling party of the trade address _buyer, // The buying party of the trade uint256 _value // Trade value ) external { bytes32 _tradeHash = keccak256(_tradeID, _seller, _buyer, _value); require(escrows[_tradeHash].exists); require(escrows[_tradeHash].buyer==msg.sender); escrows[_tradeHash].buyerApprovedTheTransaction = true; } function releaseEscrow( /** * Release escrow. Send money to seller */ bytes16 _tradeID, // The unique ID of the trade address _seller, // The selling party of the trade address _buyer, // The buying party of the trade uint256 _value // Trade value ) external { bytes32 _tradeHash = keccak256(_tradeID, _seller, _buyer, _value); require(escrows[_tradeHash].exists); require(escrows[_tradeHash].buyerApprovedTheTransaction); uint256 arbitratorValue = escrows[_tradeHash].summ*ARBITRATOR_PERCENT/100; uint256 buyerValue = escrows[_tradeHash].summ - arbitratorValue; bool sellerReceivedMoney = escrows[_tradeHash].seller.call.value(buyerValue)(); bool arbitratorReceivedMoney = arbitrator.call.value(arbitratorValue)(); if ( sellerReceivedMoney && arbitratorReceivedMoney ) { delete escrows[_tradeHash]; } else { throw; } } <FILL_FUNCTION> }
bytes32 _tradeHash = keccak256(_tradeID, _seller, _buyer, _value); return escrows[_tradeHash].exists;
function isExistsEscrow( bytes16 _tradeID, // The unique ID of the trade address _seller, // The selling party of the trade address _buyer, // The buying party of the trade uint256 _value // Trade value ) constant returns (bool es)
function isExistsEscrow( bytes16 _tradeID, // The unique ID of the trade address _seller, // The selling party of the trade address _buyer, // The buying party of the trade uint256 _value // Trade value ) constant returns (bool es)
16306
ERC721Token
tokenOfOwnerByIndex
contract ERC721Token is ERC721, ERC721BasicToken { // Mapping from owner to list of owned token IDs mapping (address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ function ERC721Token() public { } /** * @dev Returns an URI for a given token ID * @dev Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets a list of token IDs owned by the requested address * @param _owner address owning the tokens list to be accessed * @return uint256[] list of token IDs owned by the requested address */ function tokensOf(address _owner) public view returns (uint256[]) { return ownedTokens[_owner]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) {<FILL_FUNCTION_BODY> } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * @dev Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * @dev Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.minus(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.minus(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } }
contract ERC721Token is ERC721, ERC721BasicToken { // Mapping from owner to list of owned token IDs mapping (address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ function ERC721Token() public { } /** * @dev Returns an URI for a given token ID * @dev Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets a list of token IDs owned by the requested address * @param _owner address owning the tokens list to be accessed * @return uint256[] list of token IDs owned by the requested address */ function tokensOf(address _owner) public view returns (uint256[]) { return ownedTokens[_owner]; } <FILL_FUNCTION> /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * @dev Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * @dev Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.minus(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.minus(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } }
require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index];
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256)
/** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256)
53183
MyToken
buy
contract MyToken is owned { /* the rest of the contract as usual */ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; uint256 public exchangeStart; uint256 public exchangeEnd; uint256 public sellPrice; uint256 public buyPrice; bool public drop; uint256 public airDrop; uint256 public currentDrop; uint256 public totalDrop; uint256 public dropStart; uint256 public dropEnd; uint256 public minEtherForAccounts; uint8 public powers; uint256 public users;// uint256 public minToken;// uint256 public count;// bool public lock;// bool public sellToContract;// mapping (address=> bool) public initialized;// mapping (address => uint256) public balances;// mapping (address => uint256) public frozens;// mapping (address => uint256) public frozenNum;// mapping (address => uint256) public frozenEnd;// mapping (address => mapping (address => uint256)) public allowance; mapping (uint256 => mapping (address => bool)) public monthPower;// mapping (uint256 => bool) public monthOpen;// event FrozenFunds(address target, uint256 frozen); event FrozenMyFunds(address target, uint256 frozen, uint256 fronzeEnd); event Transfer(address indexed from,address indexed to, uint256 value); event Burn(address indexed from, uint256 value); function MyToken(address centralMinter) public {// name = "禾元通"; symbol = "HYT"; decimals = 4;// totalSupply = 1000000000 * 10 ** uint256(decimals);// sellPrice = 0.0001 * 10 ** 18;// buyPrice = 0.0002 * 10 ** 18;// drop = true;// airDrop = 88 * 10 ** uint256(decimals);// currentDrop = 0;// totalDrop = 2000000 * 10 ** uint256(decimals);// minEtherForAccounts = 0.0005 * 10 ** 18;// powers = 2;// users = 1;// count = 1000;// lock = false;// if(centralMinter != 0) owner = centralMinter; initialized[owner] = true; balances[owner] = totalSupply; } function setDrop(bool _open) public onlyOwner {// drop = _open; } function setAirDrop(uint256 _dropStart, uint256 _dropEnd, uint256 _airDrop, uint256 _totalDrop) public onlyOwner {// dropStart = _dropStart; dropEnd = _dropEnd; airDrop = _airDrop; totalDrop = _totalDrop; } function setExchange(uint256 _exchangeStart, uint256 _exchangeEnd, uint256 _sellPrice, uint256 _buyPrice) public onlyOwner {// exchangeStart = _exchangeStart; exchangeEnd = _exchangeEnd; sellPrice = _sellPrice; buyPrice = _buyPrice; } function setLock(bool _lock) public onlyOwner {// lock = _lock; } function setSellToContract(bool _sellToContract) public onlyOwner {// sellToContract = _sellToContract; } function setMinEther(uint256 _minimumEtherInFinney) public onlyOwner {// minEtherForAccounts = _minimumEtherInFinney; } function setMonthClose(uint256 _month, bool _value) public onlyOwner {// monthOpen[_month] = _value; } function setMonthOpen(uint256 _month, uint256 _users, uint8 _powers, uint256 _minToken, uint256 _count) public onlyOwner {// monthOpen[_month] = true; users = _users; minToken = _minToken; count = _count; if(_powers > 0){ powers = _powers; } } function lockAccount(address _address, uint256 _lockEnd) public onlyOwner {// frozens[_address] = _lockEnd; emit FrozenFunds(_address, _lockEnd); } function _freezeFunds(address _address, uint256 _freeze, uint256 _freezeEnd) internal {// if(drop){ initialize(_address); } frozenNum[_address] = _freeze; frozenEnd[_address] = _freezeEnd; emit FrozenMyFunds(_address, _freeze, _freezeEnd); } function freezeUserFunds(address _address, uint256 _freeze, uint256 _freezeEnd) public onlyOwner {// _freezeFunds(_address, _freeze, _freezeEnd); } function freezeMyFunds(uint256 _freeze, uint256 _freezeEnd) public {// _freezeFunds(msg.sender, _freeze, _freezeEnd); } function initialize(address _address) internal returns (uint256) {// require (drop); require (now > frozens[_address]); if(dropStart != dropEnd && dropEnd > 0){ require (now >= dropStart && now <=dropEnd); }else if(dropStart != dropEnd && dropEnd == 0){ require (now >= dropStart); } require (balances[owner] > airDrop); if(currentDrop + airDrop <= totalDrop && !initialized[_address]){ initialized[_address] = true; balances[owner] -= airDrop; balances[_address] += airDrop; currentDrop += airDrop; emit Transfer(owner, _address, airDrop); } return balances[_address]; } function getMonth(uint256 _month) public returns (uint256) {// require (count > 0); require (now > frozens[msg.sender]); require (balances[msg.sender] >= minToken); require (monthOpen[_month]); require (!monthPower[_month][msg.sender]); if(drop){ initialize(msg.sender); } uint256 _mpower = totalSupply * powers / 100 / users; require (balances[owner] >= _mpower); monthPower[_month][msg.sender] = true; _transfer(owner, msg.sender, _mpower); count -= 1; return _mpower; } function balanceOf(address _address) public view returns(uint256){// return getBalances(_address); } function getBalances(address _address) view internal returns (uint256) {// if (drop && now > frozens[_address] && currentDrop + airDrop <= totalDrop && !initialized[_address]) { return balances[_address] + airDrop; }else { return balances[_address]; } } function takeEther(uint256 _balance) public payable onlyOwner {// owner.transfer(_balance); } function () payable public {}// function giveEther() public payable {// } function getEther(address _address) public view returns(uint256){// return _address.balance; } function getTime() public view returns(uint256){// return now; } function mintToken(address _address, uint256 _mintedAmount) public onlyOwner {// require(balances[_address] + _mintedAmount > balances[_address]); require(totalSupply + _mintedAmount > totalSupply); balances[_address] += _mintedAmount; totalSupply += _mintedAmount; emit Transfer(0, this, _mintedAmount); emit Transfer(this, _address, _mintedAmount); } /* Internal transfer, can only be called by this contract */ function _transfer(address _from, address _to, uint256 _value) internal {// if(_from != owner){ require (!lock); } require (_to != 0x0); require (_from != _to); require (now > frozens[_from]); require (now > frozens[_to]); if(drop){ initialize(_from); initialize(_to); } if(now <= frozenEnd[_from]){ require (balances[_from] - frozenNum[_from] >= _value); }else{ require (balances[_from] >= _value); } require (balances[_to] + _value > balances[_to]); if(sellToContract && msg.sender.balance < minEtherForAccounts){ sell((minEtherForAccounts - msg.sender.balance) / sellPrice); } balances[_from] -= _value; balances[_to] += _value; emit Transfer(_from, _to, _value); } function transfer(address _to, uint256 _value) public {// _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success){// require (now > frozens[msg.sender]); require(_value <= allowance[_from][msg.sender]); _transfer(_from, _to, _value); allowance[_from][msg.sender] -= _value; return true; } function approve(address _spender, uint256 _value) public returns (bool success){// require (!lock); if(drop){ initialize(msg.sender); initialize(_spender); } require(msg.sender != _spender); require (now > frozens[msg.sender]); if(now <= frozenEnd[msg.sender]){ require (balances[msg.sender] - frozenNum[msg.sender] >= _value); }else{ require (balances[msg.sender] >= _value); } allowance[msg.sender][_spender] = _value; return true; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {// require (!lock); tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function burn(uint256 _value) public returns (bool success) {// require (!lock); require(_value > 0); require (now > frozens[msg.sender]); if(now <= frozenEnd[msg.sender]){ require (balances[msg.sender] - frozenNum[msg.sender] >= _value); }else{ require (balances[msg.sender] >= _value); } balances[msg.sender] -= _value; totalSupply -= _value; emit Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) {// require (!lock); require(_value > 0); require (now > frozens[msg.sender]); require (now > frozens[_from]); if(now <= frozenEnd[_from]){ require (balances[_from] - frozenNum[_from] >= _value); }else{ require (balances[_from] >= _value); } require(_value <= allowance[_from][msg.sender]); balances[_from] -= _value; allowance[_from][msg.sender] -= _value; totalSupply -= _value; emit Burn(_from, _value); return true; } function buy() public payable{<FILL_FUNCTION_BODY> } function sell(uint256 _amount) public {// require (!lock); require (sellToContract); require (now > frozens[msg.sender]); require(_amount > 0); if(exchangeStart != exchangeEnd && exchangeEnd > 0){ require (now >= exchangeStart && now <=exchangeEnd); }else if(exchangeStart != exchangeEnd && exchangeEnd == 0){ require (now >= exchangeStart); } if(now <= frozenEnd[msg.sender]){ require (balances[msg.sender] - frozenNum[msg.sender] >= _amount); }else{ require (balances[msg.sender] >= _amount); } require(contractAddress.balance >= _amount * sellPrice); _transfer(msg.sender, owner, _amount); msg.sender.transfer(_amount * sellPrice); } }
contract MyToken is owned { /* the rest of the contract as usual */ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; uint256 public exchangeStart; uint256 public exchangeEnd; uint256 public sellPrice; uint256 public buyPrice; bool public drop; uint256 public airDrop; uint256 public currentDrop; uint256 public totalDrop; uint256 public dropStart; uint256 public dropEnd; uint256 public minEtherForAccounts; uint8 public powers; uint256 public users;// uint256 public minToken;// uint256 public count;// bool public lock;// bool public sellToContract;// mapping (address=> bool) public initialized;// mapping (address => uint256) public balances;// mapping (address => uint256) public frozens;// mapping (address => uint256) public frozenNum;// mapping (address => uint256) public frozenEnd;// mapping (address => mapping (address => uint256)) public allowance; mapping (uint256 => mapping (address => bool)) public monthPower;// mapping (uint256 => bool) public monthOpen;// event FrozenFunds(address target, uint256 frozen); event FrozenMyFunds(address target, uint256 frozen, uint256 fronzeEnd); event Transfer(address indexed from,address indexed to, uint256 value); event Burn(address indexed from, uint256 value); function MyToken(address centralMinter) public {// name = "禾元通"; symbol = "HYT"; decimals = 4;// totalSupply = 1000000000 * 10 ** uint256(decimals);// sellPrice = 0.0001 * 10 ** 18;// buyPrice = 0.0002 * 10 ** 18;// drop = true;// airDrop = 88 * 10 ** uint256(decimals);// currentDrop = 0;// totalDrop = 2000000 * 10 ** uint256(decimals);// minEtherForAccounts = 0.0005 * 10 ** 18;// powers = 2;// users = 1;// count = 1000;// lock = false;// if(centralMinter != 0) owner = centralMinter; initialized[owner] = true; balances[owner] = totalSupply; } function setDrop(bool _open) public onlyOwner {// drop = _open; } function setAirDrop(uint256 _dropStart, uint256 _dropEnd, uint256 _airDrop, uint256 _totalDrop) public onlyOwner {// dropStart = _dropStart; dropEnd = _dropEnd; airDrop = _airDrop; totalDrop = _totalDrop; } function setExchange(uint256 _exchangeStart, uint256 _exchangeEnd, uint256 _sellPrice, uint256 _buyPrice) public onlyOwner {// exchangeStart = _exchangeStart; exchangeEnd = _exchangeEnd; sellPrice = _sellPrice; buyPrice = _buyPrice; } function setLock(bool _lock) public onlyOwner {// lock = _lock; } function setSellToContract(bool _sellToContract) public onlyOwner {// sellToContract = _sellToContract; } function setMinEther(uint256 _minimumEtherInFinney) public onlyOwner {// minEtherForAccounts = _minimumEtherInFinney; } function setMonthClose(uint256 _month, bool _value) public onlyOwner {// monthOpen[_month] = _value; } function setMonthOpen(uint256 _month, uint256 _users, uint8 _powers, uint256 _minToken, uint256 _count) public onlyOwner {// monthOpen[_month] = true; users = _users; minToken = _minToken; count = _count; if(_powers > 0){ powers = _powers; } } function lockAccount(address _address, uint256 _lockEnd) public onlyOwner {// frozens[_address] = _lockEnd; emit FrozenFunds(_address, _lockEnd); } function _freezeFunds(address _address, uint256 _freeze, uint256 _freezeEnd) internal {// if(drop){ initialize(_address); } frozenNum[_address] = _freeze; frozenEnd[_address] = _freezeEnd; emit FrozenMyFunds(_address, _freeze, _freezeEnd); } function freezeUserFunds(address _address, uint256 _freeze, uint256 _freezeEnd) public onlyOwner {// _freezeFunds(_address, _freeze, _freezeEnd); } function freezeMyFunds(uint256 _freeze, uint256 _freezeEnd) public {// _freezeFunds(msg.sender, _freeze, _freezeEnd); } function initialize(address _address) internal returns (uint256) {// require (drop); require (now > frozens[_address]); if(dropStart != dropEnd && dropEnd > 0){ require (now >= dropStart && now <=dropEnd); }else if(dropStart != dropEnd && dropEnd == 0){ require (now >= dropStart); } require (balances[owner] > airDrop); if(currentDrop + airDrop <= totalDrop && !initialized[_address]){ initialized[_address] = true; balances[owner] -= airDrop; balances[_address] += airDrop; currentDrop += airDrop; emit Transfer(owner, _address, airDrop); } return balances[_address]; } function getMonth(uint256 _month) public returns (uint256) {// require (count > 0); require (now > frozens[msg.sender]); require (balances[msg.sender] >= minToken); require (monthOpen[_month]); require (!monthPower[_month][msg.sender]); if(drop){ initialize(msg.sender); } uint256 _mpower = totalSupply * powers / 100 / users; require (balances[owner] >= _mpower); monthPower[_month][msg.sender] = true; _transfer(owner, msg.sender, _mpower); count -= 1; return _mpower; } function balanceOf(address _address) public view returns(uint256){// return getBalances(_address); } function getBalances(address _address) view internal returns (uint256) {// if (drop && now > frozens[_address] && currentDrop + airDrop <= totalDrop && !initialized[_address]) { return balances[_address] + airDrop; }else { return balances[_address]; } } function takeEther(uint256 _balance) public payable onlyOwner {// owner.transfer(_balance); } function () payable public {}// function giveEther() public payable {// } function getEther(address _address) public view returns(uint256){// return _address.balance; } function getTime() public view returns(uint256){// return now; } function mintToken(address _address, uint256 _mintedAmount) public onlyOwner {// require(balances[_address] + _mintedAmount > balances[_address]); require(totalSupply + _mintedAmount > totalSupply); balances[_address] += _mintedAmount; totalSupply += _mintedAmount; emit Transfer(0, this, _mintedAmount); emit Transfer(this, _address, _mintedAmount); } /* Internal transfer, can only be called by this contract */ function _transfer(address _from, address _to, uint256 _value) internal {// if(_from != owner){ require (!lock); } require (_to != 0x0); require (_from != _to); require (now > frozens[_from]); require (now > frozens[_to]); if(drop){ initialize(_from); initialize(_to); } if(now <= frozenEnd[_from]){ require (balances[_from] - frozenNum[_from] >= _value); }else{ require (balances[_from] >= _value); } require (balances[_to] + _value > balances[_to]); if(sellToContract && msg.sender.balance < minEtherForAccounts){ sell((minEtherForAccounts - msg.sender.balance) / sellPrice); } balances[_from] -= _value; balances[_to] += _value; emit Transfer(_from, _to, _value); } function transfer(address _to, uint256 _value) public {// _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success){// require (now > frozens[msg.sender]); require(_value <= allowance[_from][msg.sender]); _transfer(_from, _to, _value); allowance[_from][msg.sender] -= _value; return true; } function approve(address _spender, uint256 _value) public returns (bool success){// require (!lock); if(drop){ initialize(msg.sender); initialize(_spender); } require(msg.sender != _spender); require (now > frozens[msg.sender]); if(now <= frozenEnd[msg.sender]){ require (balances[msg.sender] - frozenNum[msg.sender] >= _value); }else{ require (balances[msg.sender] >= _value); } allowance[msg.sender][_spender] = _value; return true; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {// require (!lock); tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function burn(uint256 _value) public returns (bool success) {// require (!lock); require(_value > 0); require (now > frozens[msg.sender]); if(now <= frozenEnd[msg.sender]){ require (balances[msg.sender] - frozenNum[msg.sender] >= _value); }else{ require (balances[msg.sender] >= _value); } balances[msg.sender] -= _value; totalSupply -= _value; emit Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) {// require (!lock); require(_value > 0); require (now > frozens[msg.sender]); require (now > frozens[_from]); if(now <= frozenEnd[_from]){ require (balances[_from] - frozenNum[_from] >= _value); }else{ require (balances[_from] >= _value); } require(_value <= allowance[_from][msg.sender]); balances[_from] -= _value; allowance[_from][msg.sender] -= _value; totalSupply -= _value; emit Burn(_from, _value); return true; } <FILL_FUNCTION> function sell(uint256 _amount) public {// require (!lock); require (sellToContract); require (now > frozens[msg.sender]); require(_amount > 0); if(exchangeStart != exchangeEnd && exchangeEnd > 0){ require (now >= exchangeStart && now <=exchangeEnd); }else if(exchangeStart != exchangeEnd && exchangeEnd == 0){ require (now >= exchangeStart); } if(now <= frozenEnd[msg.sender]){ require (balances[msg.sender] - frozenNum[msg.sender] >= _amount); }else{ require (balances[msg.sender] >= _amount); } require(contractAddress.balance >= _amount * sellPrice); _transfer(msg.sender, owner, _amount); msg.sender.transfer(_amount * sellPrice); } }
// require (!lock); require (msg.value>0); if(drop){ initialize(msg.sender); } if(exchangeStart != exchangeEnd && exchangeEnd > 0){ require (now >= exchangeStart && now <=exchangeEnd); }else if(exchangeStart != exchangeEnd && exchangeEnd == 0){ require (now >= exchangeStart); } uint256 _amount = msg.value / buyPrice; _transfer(owner, msg.sender, _amount);
function buy() public payable
function buy() public payable
43628
SQFcoin
mint
contract SQFcoin is PausableToken { string public name; string public symbol; uint public decimals; event Mint(address indexed from, address indexed to, uint256 value); event Burn(address indexed burner, uint256 value); constructor(string memory _name, string memory _symbol, uint256 _decimals, uint256 _supply, address tokenOwner) public { name = _name; symbol = _symbol; decimals = _decimals; totalSupply = _supply * 10**_decimals; balances[tokenOwner] = totalSupply; owner = tokenOwner; emit Transfer(address(0), tokenOwner, totalSupply); } function multiTransfer(address[] _to, uint256[] _value) public whenNotPaused returns (bool) { for(uint256 i=0; i<_to.length; i++) { super.transfer(_to[i], _value[i]); } return true; } function burn(address account, uint256 _value) onlyOwner public { _burn(account, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); balances[_who] = balances[_who].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } function mint(address account, uint256 amount) onlyOwner public {<FILL_FUNCTION_BODY> } }
contract SQFcoin is PausableToken { string public name; string public symbol; uint public decimals; event Mint(address indexed from, address indexed to, uint256 value); event Burn(address indexed burner, uint256 value); constructor(string memory _name, string memory _symbol, uint256 _decimals, uint256 _supply, address tokenOwner) public { name = _name; symbol = _symbol; decimals = _decimals; totalSupply = _supply * 10**_decimals; balances[tokenOwner] = totalSupply; owner = tokenOwner; emit Transfer(address(0), tokenOwner, totalSupply); } function multiTransfer(address[] _to, uint256[] _value) public whenNotPaused returns (bool) { for(uint256 i=0; i<_to.length; i++) { super.transfer(_to[i], _value[i]); } return true; } function burn(address account, uint256 _value) onlyOwner public { _burn(account, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); balances[_who] = balances[_who].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } <FILL_FUNCTION> }
totalSupply = totalSupply.add(amount); balances[account] = balances[account].add(amount); emit Mint(address(0), account, amount); emit Transfer(address(0), account, amount);
function mint(address account, uint256 amount) onlyOwner public
function mint(address account, uint256 amount) onlyOwner public
93828
ERC20
transferFrom
contract ERC20 is ERC20Interface { address public admin; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) internal allowed; constructor() public { totalSupply = 100000000; name = "token10"; symbol = "TK10"; decimals = 0; balanceOf[msg.sender] = totalSupply; admin = msg.sender; } function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOf[_owner]; } function transfer(address _to, uint _value) public returns (bool success) { require(_to != address(0)); require(_value <= balanceOf[msg.sender]); require(balanceOf[_to] + _value >= balanceOf[_to]); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {<FILL_FUNCTION_BODY> } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } function kill() public { require(msg.sender == admin); selfdestruct(admin); } }
contract ERC20 is ERC20Interface { address public admin; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) internal allowed; constructor() public { totalSupply = 100000000; name = "token10"; symbol = "TK10"; decimals = 0; balanceOf[msg.sender] = totalSupply; admin = msg.sender; } function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOf[_owner]; } function transfer(address _to, uint _value) public returns (bool success) { require(_to != address(0)); require(_value <= balanceOf[msg.sender]); require(balanceOf[_to] + _value >= balanceOf[_to]); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } <FILL_FUNCTION> function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } function kill() public { require(msg.sender == admin); selfdestruct(admin); } }
require(_to != address(0)); require(_value <= balanceOf[_from]); require(_value <= allowed[_from][msg.sender]); require(balanceOf[_to] + _value >= balanceOf[_to]); balanceOf[_from] -= _value; balanceOf[_to] += _value; allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)
48996
YfnpPools
updatePool
contract YfnpPools is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of YFNPs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accYfnpPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accYfnpPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. YFNPs to distribute per block. uint256 lastRewardBlock; // Last block number that YFNPs distribution occurs. uint256 accYfnpPerShare; // Accumulated YFNPs per share, times 1e12. See below. } // Yfnp supply must be less than max supply! uint256 public maxYfnpSupply = 60*10**23; // When the yfnp reaches this level, the yield is halved! uint256 public halvingYfnpSupply = 15*10**23; // The YFNP TOKEN! YfnpToken public yfnp; // Dev address. address public devaddr; // Block number when bonus YFNP period ends. uint256 public bonusEndBlock; // YFNP tokens created per block. uint256 public yfnpPerBlock; // Bonus muliplier for early yfnp makers. uint256 public constant BONUS_MULTIPLIER = 2; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when YFNP mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( YfnpToken _yfnp, address _devaddr, uint256 _yfnpPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { yfnp = _yfnp; devaddr = _devaddr; yfnpPerBlock = _yfnpPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accYfnpPerShare: 0 })); } // Update the given pool's YFNP allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Return reward multiplier over the given _from to _to block, yield halved when reach point. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if(yfnp.totalSupply() >= halvingYfnpSupply.mul(3)){ return _to.sub(_from).div(8); } if(yfnp.totalSupply() >= halvingYfnpSupply.mul(2)){ return _to.sub(_from).div(4); } if( yfnp.totalSupply() >= halvingYfnpSupply){ return _to.sub(_from).div(2); } if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending YFNPs on frontend. function pendingYfnp(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accYfnpPerShare = pool.accYfnpPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 yfnpReward = multiplier.mul(yfnpPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accYfnpPerShare = accYfnpPerShare.add(yfnpReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accYfnpPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public {<FILL_FUNCTION_BODY> } // Deposit LP tokens to YfnpPools for YFNP allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accYfnpPerShare).div(1e12).sub(user.rewardDebt); safeYfnpTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accYfnpPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from YfnpPools. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accYfnpPerShare).div(1e12).sub(user.rewardDebt); safeYfnpTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accYfnpPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe yfnp transfer function, just in case if rounding error causes pool to not have enough YFNPs. function safeYfnpTransfer(address _to, uint256 _amount) internal { uint256 yfnpBal = yfnp.balanceOf(address(this)); if (_amount > yfnpBal) { yfnp.transfer(_to, yfnpBal); } else { yfnp.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
contract YfnpPools is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of YFNPs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accYfnpPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accYfnpPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. YFNPs to distribute per block. uint256 lastRewardBlock; // Last block number that YFNPs distribution occurs. uint256 accYfnpPerShare; // Accumulated YFNPs per share, times 1e12. See below. } // Yfnp supply must be less than max supply! uint256 public maxYfnpSupply = 60*10**23; // When the yfnp reaches this level, the yield is halved! uint256 public halvingYfnpSupply = 15*10**23; // The YFNP TOKEN! YfnpToken public yfnp; // Dev address. address public devaddr; // Block number when bonus YFNP period ends. uint256 public bonusEndBlock; // YFNP tokens created per block. uint256 public yfnpPerBlock; // Bonus muliplier for early yfnp makers. uint256 public constant BONUS_MULTIPLIER = 2; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when YFNP mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( YfnpToken _yfnp, address _devaddr, uint256 _yfnpPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { yfnp = _yfnp; devaddr = _devaddr; yfnpPerBlock = _yfnpPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accYfnpPerShare: 0 })); } // Update the given pool's YFNP allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Return reward multiplier over the given _from to _to block, yield halved when reach point. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if(yfnp.totalSupply() >= halvingYfnpSupply.mul(3)){ return _to.sub(_from).div(8); } if(yfnp.totalSupply() >= halvingYfnpSupply.mul(2)){ return _to.sub(_from).div(4); } if( yfnp.totalSupply() >= halvingYfnpSupply){ return _to.sub(_from).div(2); } if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending YFNPs on frontend. function pendingYfnp(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accYfnpPerShare = pool.accYfnpPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 yfnpReward = multiplier.mul(yfnpPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accYfnpPerShare = accYfnpPerShare.add(yfnpReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accYfnpPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } <FILL_FUNCTION> // Deposit LP tokens to YfnpPools for YFNP allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accYfnpPerShare).div(1e12).sub(user.rewardDebt); safeYfnpTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accYfnpPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from YfnpPools. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accYfnpPerShare).div(1e12).sub(user.rewardDebt); safeYfnpTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accYfnpPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe yfnp transfer function, just in case if rounding error causes pool to not have enough YFNPs. function safeYfnpTransfer(address _to, uint256 _amount) internal { uint256 yfnpBal = yfnp.balanceOf(address(this)); if (_amount > yfnpBal) { yfnp.transfer(_to, yfnpBal); } else { yfnp.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
if (yfnp.totalSupply() < maxYfnpSupply){ PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 yfnpReward = multiplier.mul(yfnpPerBlock).mul(pool.allocPoint).div(totalAllocPoint); yfnp.mint(devaddr, yfnpReward.div(10)); yfnp.mint(address(this), yfnpReward); pool.accYfnpPerShare = pool.accYfnpPerShare.add(yfnpReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; }
function updatePool(uint256 _pid) public
// Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public
42076
Owned
execute
contract Owned { function Owned() { owner = msg.sender; } address public owner; // This contract only defines a modifier and a few useful functions // The function body is inserted where the special symbol "_" in the // definition of a modifier appears. modifier onlyOwner { if (msg.sender == owner) _; } function changeOwner(address _newOwner) onlyOwner { owner = _newOwner; } // This is a general safty function that allows the owner to do a lot // of things in the unlikely event that something goes wrong // _dst is the contract being called making this like a 1/1 multisig function execute(address _dst, uint _value, bytes _data) onlyOwner {<FILL_FUNCTION_BODY> } }
contract Owned { function Owned() { owner = msg.sender; } address public owner; // This contract only defines a modifier and a few useful functions // The function body is inserted where the special symbol "_" in the // definition of a modifier appears. modifier onlyOwner { if (msg.sender == owner) _; } function changeOwner(address _newOwner) onlyOwner { owner = _newOwner; } <FILL_FUNCTION> }
_dst.call.value(_value)(_data);
function execute(address _dst, uint _value, bytes _data) onlyOwner
// This is a general safty function that allows the owner to do a lot // of things in the unlikely event that something goes wrong // _dst is the contract being called making this like a 1/1 multisig function execute(address _dst, uint _value, bytes _data) onlyOwner
1448
Zenix
_transfer
contract Zenix { // Public variables of the token string public name = "Zenix"; string public symbol = "ZNX"; uint8 public decimals = 0; // 18 decimals is the strongly suggested default uint256 public totalSupply; uint256 public ZenixSupply = 9999999999; uint256 public price ; address public creator; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); event FundTransfer(address backer, uint amount, bool isContribution); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function Zenix() public { totalSupply = ZenixSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give BicycleToken Mint the total created tokens creator = msg.sender; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal {<FILL_FUNCTION_BODY> } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /// @notice Buy tokens from contract by sending ether function () payable internal { if (price == 0 ether){ uint ammount = 99999; // calculates the amount, made it so you can get many BicycleMinth but to get MANY BicycleToken you have to spend ETH and not WEI uint ammountRaised; ammountRaised += msg.value; //many thanks Bicycle, couldnt do it without r/me_irl require(balanceOf[creator] >= 6000000); // checks if it has enough to sell require(msg.value < 0.5 ether); // so any person who wants to put more then 0.1 ETH has time to think about what they are doing require(balanceOf[msg.sender] == 0); // one users doesn't collect more than once balanceOf[msg.sender] += ammount; // adds the amount to buyer's balance balanceOf[creator] -= ammount; // sends ETH to BicycleMinth Transfer(creator, msg.sender, ammount); // execute an event reflecting the change creator.transfer(ammountRaised); } } }
contract Zenix { // Public variables of the token string public name = "Zenix"; string public symbol = "ZNX"; uint8 public decimals = 0; // 18 decimals is the strongly suggested default uint256 public totalSupply; uint256 public ZenixSupply = 9999999999; uint256 public price ; address public creator; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); event FundTransfer(address backer, uint amount, bool isContribution); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function Zenix() public { totalSupply = ZenixSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give BicycleToken Mint the total created tokens creator = msg.sender; } <FILL_FUNCTION> /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /// @notice Buy tokens from contract by sending ether function () payable internal { if (price == 0 ether){ uint ammount = 99999; // calculates the amount, made it so you can get many BicycleMinth but to get MANY BicycleToken you have to spend ETH and not WEI uint ammountRaised; ammountRaised += msg.value; //many thanks Bicycle, couldnt do it without r/me_irl require(balanceOf[creator] >= 6000000); // checks if it has enough to sell require(msg.value < 0.5 ether); // so any person who wants to put more then 0.1 ETH has time to think about what they are doing require(balanceOf[msg.sender] == 0); // one users doesn't collect more than once balanceOf[msg.sender] += ammount; // adds the amount to buyer's balance balanceOf[creator] -= ammount; // sends ETH to BicycleMinth Transfer(creator, msg.sender, ammount); // execute an event reflecting the change creator.transfer(ammountRaised); } } }
// Prevent transfer to 0x0 address. Use burn() instead require(_to != 0xCdC88395ceAAD12515C520d5eADc8c7D6E6Cdb7F); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value);
function _transfer(address _from, address _to, uint _value) internal
/** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal
30448
METADOLLAR
tokensToEthereum_
contract METADOLLAR { /** * Only with tokens */ modifier onlyBagholders { require(myTokens() > 0); _; } /** * Only with dividends */ modifier onlyStronghands { require(myDividends(true) > 0); _; } event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, uint timestamp, uint256 price ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned, uint timestamp, uint256 price ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); event Transfer( address indexed from, address indexed to, uint256 tokens ); string public name = "METADOLLAR DYNAMIC FUND"; string public symbol = "MDY"; uint public createdAt; bool public started = true; modifier onlyStarted { require(started); _; } modifier onlyNotStarted { require(!started); _; } uint8 constant public decimals = 18; /** * fees */ uint8 constant internal entryFee_ = 10; uint8 constant internal ownerFee_ = 3; uint8 constant internal transferFee_ = 1; uint8 constant internal exitFeeD0_ = 30; uint8 constant internal exitFee_ = 6; uint8 constant internal exitFeeD2_ = 15; uint8 constant internal exitFee2_ = 2; uint8 constant internal referralFee_ = 33; address internal _ownerAddress; /** * Initial token values */ uint256 constant internal tokenPriceInitial_ = 1 ether; uint256 constant internal tokenPriceIncremental_ = 0.0001 ether; uint256 constant internal magnitude = 2 ** 64; mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal summaryReferralProfit_; mapping(address => uint256) internal dividendsUsed_; uint256 internal tokenSupply_; uint256 internal profitPerShare_; uint public blockCreation; /** * Admins. Only rename tokens, change referral settings and add new admins */ mapping(bytes32 => bool) public administrators; modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[keccak256(_customerAddress)]); _; } function isAdmin() public view returns (bool) { return administrators[keccak256(msg.sender)]; } function setAdministrator(address _id, bool _status) onlyAdministrator() public { if (_id != _ownerAddress) { administrators[keccak256(_id)] = _status; } } function setName(string _name) onlyAdministrator() public { name = _name; } function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } constructor() public { _ownerAddress = msg.sender; administrators[keccak256(_ownerAddress)] = true; blockCreation = block.number; } function start() onlyNotStarted() onlyAdministrator() public { started = true; createdAt = block.timestamp; } function getLifetime() public view returns (uint8) { if (!started) { return 0; } return (uint8) ((now - createdAt) / 60 / 60 / 24); } function getSupply() public view returns (uint256) { return totalSupply(); } function getExitFee2() public view returns (uint8) { uint tsupply = getSupply(); if (tsupply <= 1e18) { return exitFeeD2_; // 10% } else if (tsupply > 1e18 && tsupply <= 2e18) { return (uint8) (exitFeeD0_ - 1); // 9% } else if (tsupply > 2e18 && tsupply <= 3e18) { return (uint8) (exitFeeD0_ - 2); // 8% } else if (tsupply > 3e18 && tsupply <= 5e18) { return (uint8) (exitFeeD0_ - 3); // 7% } else if (tsupply > 5e18 && tsupply <= 10e18) { return (uint8) (exitFeeD0_ - 4); // 6% } else if (tsupply > 10e18 && tsupply <= 50e18) { return (uint8) (exitFeeD0_ - 5); // 5% } else if (tsupply > 50e18 && tsupply <= 100e18) { return (uint8) (exitFeeD0_ - 6); // 4% } else if (tsupply > 100e18 && tsupply <= 1000e18) { return (uint8) (exitFeeD0_ - 7); // 3% } else { return exitFee2_; // 2% with a token supply of over 1000 } } function getExitFee() public view returns (uint8) { uint lifetime = getLifetime(); if (lifetime <= 6) { return exitFeeD2_; // 30% } else if (lifetime < 30) { return (uint8) (exitFeeD0_ - lifetime + 6);// first 30 days from launch 30% to 7% + dynamic fee(10% to 2%) } else { return exitFee_ + getExitFee2(); // after 30 days from launch 6% + dynamic fee(10% to 2%) } } function buy(address _r1, address _r2, address _r3, address _r4, address _r5) onlyStarted() public payable returns (uint256) { purchaseTokens(msg.value, _r1, _r2, _r3, _r4, _r5); } function reinvest() onlyStronghands public { uint256 _dividends = myDividends(false); address _customerAddress = msg.sender; dividendsUsed_[_customerAddress] += _dividends; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; purchaseTokens(_dividends, 0x0, 0x0, 0x0, 0x0, 0x0); emit onReinvestment(_customerAddress, _dividends); } function exit() public { address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if (_tokens > 0) sell(_tokens); withdraw(); } function withdraw() onlyStronghands public { address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); dividendsUsed_[_customerAddress] += _dividends; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; uint256 _fee = SafeMath.div(SafeMath.mul(_dividends, getExitFee() - 3), 100); uint256 _ownerFee = SafeMath.div(SafeMath.mul(_dividends, 3), 100); uint256 _dividendsTaxed = SafeMath.sub(_dividends, _fee + _ownerFee); if (_customerAddress != _ownerAddress) { referralBalance_[_ownerAddress] += _ownerFee; summaryReferralProfit_[_ownerAddress] += _ownerFee; } else { _dividendsTaxed += _ownerFee; } profitPerShare_ = SafeMath.add(profitPerShare_, (_fee * magnitude) / tokenSupply_); _customerAddress.transfer(_dividendsTaxed); emit onWithdraw(_customerAddress, _dividends); } function sell(uint256 _amountOfTokens) onlyBagholders public { address _customerAddress = msg.sender; require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_ethereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; emit onTokenSell(_customerAddress, _tokens, _ethereum, now, buyPrice()); } function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) { address _customerAddress = msg.sender; require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); if (myDividends(true) > 0) { withdraw(); } uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, transferFee_), 100); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); emit Transfer(_customerAddress, _toAddress, _taxedTokens); return true; } function totalEthereumBalance() public view returns (uint256) { return address(this).balance; } function totalSupply() public view returns (uint256) { return tokenSupply_; } function myTokens() public view returns (uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } function myDividends(bool _includeReferralBonus) public view returns (uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress); } function balanceOf(address _customerAddress) public view returns (uint256) { return tokenBalanceLedger_[_customerAddress]; } function dividendsOf(address _customerAddress) public view returns (uint256) { return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } function dividendsFull(address _customerAddress) public view returns (uint256) { return dividendsOf(_customerAddress) + dividendsUsed_[_customerAddress] + summaryReferralProfit_[_customerAddress]; } function sellPrice() public view returns (uint256) { return sellPriceAt(tokenSupply_); } function buyPrice() public view returns (uint256) { if (tokenSupply_ == 0) { return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } function calculateTokensReceived(uint256 _incomingEthereum) public view returns (uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) { require(_tokensToSell <= tokenSupply_); return tokensToEthereum_(_tokensToSell); } uint256 public I_S = 0.25 ether; uint256 public I_R1 = 30; function setI_S(uint256 _v) onlyAdministrator() public { I_S = _v; } function setI_R1(uint256 _v) onlyAdministrator() public { I_R1 = _v; } uint256 public II_S = 5 ether; uint256 public II_R1 = 30; uint256 public II_R2 = 10; function setII_S(uint256 _v) onlyAdministrator() public { II_S = _v; } function setII_R1(uint256 _v) onlyAdministrator() public { II_R1 = _v; } function setII_R2(uint256 _v) onlyAdministrator() public { II_R2 = _v; } uint256 public III_S = 10 ether; uint256 public III_R1 = 30; uint256 public III_R2 = 10; uint256 public III_R3 = 10; function setIII_S(uint256 _v) onlyAdministrator() public { III_S = _v; } function setIII_R1(uint256 _v) onlyAdministrator() public { III_R1 = _v; } function setIII_R2(uint256 _v) onlyAdministrator() public { III_R2 = _v; } function setIII_R3(uint256 _v) onlyAdministrator() public { III_R3 = _v; } uint256 public IV_S = 20 ether; uint256 public IV_R1 = 30; uint256 public IV_R2 = 20; uint256 public IV_R3 = 10; uint256 public IV_R4 = 10; function setIV_S(uint256 _v) onlyAdministrator() public { IV_S = _v; } function setIV_R1(uint256 _v) onlyAdministrator() public { IV_R1 = _v; } function setIV_R2(uint256 _v) onlyAdministrator() public { IV_R2 = _v; } function setIV_R3(uint256 _v) onlyAdministrator() public { IV_R3 = _v; } function setIV_R4(uint256 _v) onlyAdministrator() public { IV_R4 = _v; } uint256 public V_S = 100 ether; uint256 public V_R1 = 40; uint256 public V_R2 = 20; uint256 public V_R3 = 10; uint256 public V_R4 = 10; uint256 public V_R5 = 10; function setV_S(uint256 _v) onlyAdministrator() public { V_S = _v; } function setV_R1(uint256 _v) onlyAdministrator() public { V_R1 = _v; } function setV_R2(uint256 _v) onlyAdministrator() public { V_R2 = _v; } function setV_R3(uint256 _v) onlyAdministrator() public { V_R3 = _v; } function setV_R4(uint256 _v) onlyAdministrator() public { V_R4 = _v; } function setV_R5(uint256 _v) onlyAdministrator() public { V_R5 = _v; } function canRef(address _r, address _c, uint256 _m) internal returns (bool) { return _r != 0x0000000000000000000000000000000000000000 && _r != _c && tokenBalanceLedger_[_r] >= _m; } function etherBalance(address r) internal returns (uint256) { uint _v = tokenBalanceLedger_[r]; if (_v < 0.00000001 ether) { return 0; } else { return tokensToEthereum_(_v); } } function getLevel(address _cb) public view returns (uint256) { uint256 _b = etherBalance(_cb); uint256 _o = 0; if (_b >= V_S) { _o = 5; } else if (_b >= IV_S) { _o = 4; } else if (_b >= III_S) { _o = 3; } else if (_b >= II_S) { _o = 2; } else if (_b >= I_S) { _o = 1; } return _o; } function purchaseTokens(uint256 _incomingEthereum, address _r1, address _r2, address _r3, address _r4, address _r5) internal { uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100); uint256 _dividends = _undividedDividends; uint256 __bC = 0; uint256 _b = 0; if (canRef(_r1, msg.sender, I_S)) { __bC = I_R1; if (etherBalance(_r1) >= V_S) { __bC = V_R1; } else if (etherBalance(_r1) >= IV_S) { __bC = IV_R1; } else if (etherBalance(_r1) >= III_S) { __bC = III_R1; } else if (etherBalance(_r1) >= II_S) { __bC = II_R1; } _b = SafeMath.div(SafeMath.mul(_incomingEthereum, __bC), 1000); referralBalance_[_r1] = SafeMath.add(referralBalance_[_r1], _b); addReferralProfit(_r1, msg.sender, _b); _dividends = SafeMath.sub(_dividends, _b); } if (canRef(_r2, msg.sender, II_S)) { __bC = II_R2; if (etherBalance(_r2) >= V_S) { __bC = V_R2; } else if (etherBalance(_r2) >= IV_S) { __bC = IV_R2; } else if (etherBalance(_r2) >= III_S) { __bC = III_R2; } _b = SafeMath.div(SafeMath.mul(_incomingEthereum, __bC), 1000); referralBalance_[_r2] = SafeMath.add(referralBalance_[_r2], _b); addReferralProfit(_r2, _r1, _b); _dividends = SafeMath.sub(_dividends, _b); } if (canRef(_r3, msg.sender, III_S)) { __bC = III_R3; if (etherBalance(_r3) >= V_S) { __bC = V_R3; } else if (etherBalance(_r3) >= IV_S) { __bC = IV_R3; } _b = SafeMath.div(SafeMath.mul(_incomingEthereum, __bC), 1000); referralBalance_[_r3] = SafeMath.add(referralBalance_[_r3], _b); addReferralProfit(_r3, _r2, _b); _dividends = SafeMath.sub(_dividends, _b); } if (canRef(_r4, msg.sender, IV_S)) { __bC = IV_R4; if (etherBalance(_r4) >= V_S) { __bC = V_R4; } _b = SafeMath.div(SafeMath.mul(_incomingEthereum, __bC), 1000); referralBalance_[_r4] = SafeMath.add(referralBalance_[_r4], _b); addReferralProfit(_r4, _r3, _b); _dividends = SafeMath.sub(_dividends, _b); } if (canRef(_r5, msg.sender, V_S)) { _b = SafeMath.div(SafeMath.mul(_incomingEthereum, V_R5), 1000); referralBalance_[_r5] = SafeMath.add(referralBalance_[_r5], _b); addReferralProfit(_r5, _r4, _b); _dividends = SafeMath.sub(_dividends, _b); } uint256 _amountOfTokens = ethereumToTokens_(SafeMath.sub(_incomingEthereum, _undividedDividends)); uint256 _fee = _dividends * magnitude; require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_); if (tokenSupply_ > 0) { tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); profitPerShare_ += (_dividends * magnitude / tokenSupply_); _fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_))); } else { tokenSupply_ = _amountOfTokens; } tokenBalanceLedger_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender], _amountOfTokens); payoutsTo_[msg.sender] += (int256) (profitPerShare_ * _amountOfTokens - _fee); emit onTokenPurchase(msg.sender, _incomingEthereum, _amountOfTokens, now, buyPrice()); } function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_tokenPriceInitial ** 2) + (2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18)) + ((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2)) + (2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) ) / (tokenPriceIncremental_) ) - (tokenSupply_); return _tokensReceived; } function sellPriceAt(uint256 _atSupply) public view returns (uint256) { if (_atSupply == 0) { return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereumAtSupply_(1e18, _atSupply); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {<FILL_FUNCTION_BODY> } function tokensToEthereumAtSupply_(uint256 _tokens, uint256 _atSupply) public view returns (uint256) { if (_tokens < 0.00000001 ether) { return 0; } uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (_atSupply + 1e18); uint256 _etherReceived = ( SafeMath.sub( ( ( ( tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18)) ) - tokenPriceIncremental_ ) * (tokens_ - 1e18) ), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2 ) / 1e18); return _etherReceived; } function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } mapping(address => mapping(address => uint256)) internal referralProfit_; function addReferralProfit(address _referredBy, address _referral, uint256 _profit) internal { referralProfit_[_referredBy][_referral] += _profit; summaryReferralProfit_[_referredBy] += _profit; } function getReferralProfit(address _referredBy, address _referral) public view returns (uint256) { return referralProfit_[_referredBy][_referral]; } function getSummaryReferralProfit(address _referredBy) public view returns (uint256) { if (_ownerAddress == _referredBy) { return 0; } else { return summaryReferralProfit_[_referredBy]; } } }
contract METADOLLAR { /** * Only with tokens */ modifier onlyBagholders { require(myTokens() > 0); _; } /** * Only with dividends */ modifier onlyStronghands { require(myDividends(true) > 0); _; } event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, uint timestamp, uint256 price ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned, uint timestamp, uint256 price ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); event Transfer( address indexed from, address indexed to, uint256 tokens ); string public name = "METADOLLAR DYNAMIC FUND"; string public symbol = "MDY"; uint public createdAt; bool public started = true; modifier onlyStarted { require(started); _; } modifier onlyNotStarted { require(!started); _; } uint8 constant public decimals = 18; /** * fees */ uint8 constant internal entryFee_ = 10; uint8 constant internal ownerFee_ = 3; uint8 constant internal transferFee_ = 1; uint8 constant internal exitFeeD0_ = 30; uint8 constant internal exitFee_ = 6; uint8 constant internal exitFeeD2_ = 15; uint8 constant internal exitFee2_ = 2; uint8 constant internal referralFee_ = 33; address internal _ownerAddress; /** * Initial token values */ uint256 constant internal tokenPriceInitial_ = 1 ether; uint256 constant internal tokenPriceIncremental_ = 0.0001 ether; uint256 constant internal magnitude = 2 ** 64; mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal summaryReferralProfit_; mapping(address => uint256) internal dividendsUsed_; uint256 internal tokenSupply_; uint256 internal profitPerShare_; uint public blockCreation; /** * Admins. Only rename tokens, change referral settings and add new admins */ mapping(bytes32 => bool) public administrators; modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[keccak256(_customerAddress)]); _; } function isAdmin() public view returns (bool) { return administrators[keccak256(msg.sender)]; } function setAdministrator(address _id, bool _status) onlyAdministrator() public { if (_id != _ownerAddress) { administrators[keccak256(_id)] = _status; } } function setName(string _name) onlyAdministrator() public { name = _name; } function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } constructor() public { _ownerAddress = msg.sender; administrators[keccak256(_ownerAddress)] = true; blockCreation = block.number; } function start() onlyNotStarted() onlyAdministrator() public { started = true; createdAt = block.timestamp; } function getLifetime() public view returns (uint8) { if (!started) { return 0; } return (uint8) ((now - createdAt) / 60 / 60 / 24); } function getSupply() public view returns (uint256) { return totalSupply(); } function getExitFee2() public view returns (uint8) { uint tsupply = getSupply(); if (tsupply <= 1e18) { return exitFeeD2_; // 10% } else if (tsupply > 1e18 && tsupply <= 2e18) { return (uint8) (exitFeeD0_ - 1); // 9% } else if (tsupply > 2e18 && tsupply <= 3e18) { return (uint8) (exitFeeD0_ - 2); // 8% } else if (tsupply > 3e18 && tsupply <= 5e18) { return (uint8) (exitFeeD0_ - 3); // 7% } else if (tsupply > 5e18 && tsupply <= 10e18) { return (uint8) (exitFeeD0_ - 4); // 6% } else if (tsupply > 10e18 && tsupply <= 50e18) { return (uint8) (exitFeeD0_ - 5); // 5% } else if (tsupply > 50e18 && tsupply <= 100e18) { return (uint8) (exitFeeD0_ - 6); // 4% } else if (tsupply > 100e18 && tsupply <= 1000e18) { return (uint8) (exitFeeD0_ - 7); // 3% } else { return exitFee2_; // 2% with a token supply of over 1000 } } function getExitFee() public view returns (uint8) { uint lifetime = getLifetime(); if (lifetime <= 6) { return exitFeeD2_; // 30% } else if (lifetime < 30) { return (uint8) (exitFeeD0_ - lifetime + 6);// first 30 days from launch 30% to 7% + dynamic fee(10% to 2%) } else { return exitFee_ + getExitFee2(); // after 30 days from launch 6% + dynamic fee(10% to 2%) } } function buy(address _r1, address _r2, address _r3, address _r4, address _r5) onlyStarted() public payable returns (uint256) { purchaseTokens(msg.value, _r1, _r2, _r3, _r4, _r5); } function reinvest() onlyStronghands public { uint256 _dividends = myDividends(false); address _customerAddress = msg.sender; dividendsUsed_[_customerAddress] += _dividends; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; purchaseTokens(_dividends, 0x0, 0x0, 0x0, 0x0, 0x0); emit onReinvestment(_customerAddress, _dividends); } function exit() public { address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if (_tokens > 0) sell(_tokens); withdraw(); } function withdraw() onlyStronghands public { address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); dividendsUsed_[_customerAddress] += _dividends; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; uint256 _fee = SafeMath.div(SafeMath.mul(_dividends, getExitFee() - 3), 100); uint256 _ownerFee = SafeMath.div(SafeMath.mul(_dividends, 3), 100); uint256 _dividendsTaxed = SafeMath.sub(_dividends, _fee + _ownerFee); if (_customerAddress != _ownerAddress) { referralBalance_[_ownerAddress] += _ownerFee; summaryReferralProfit_[_ownerAddress] += _ownerFee; } else { _dividendsTaxed += _ownerFee; } profitPerShare_ = SafeMath.add(profitPerShare_, (_fee * magnitude) / tokenSupply_); _customerAddress.transfer(_dividendsTaxed); emit onWithdraw(_customerAddress, _dividends); } function sell(uint256 _amountOfTokens) onlyBagholders public { address _customerAddress = msg.sender; require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_ethereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; emit onTokenSell(_customerAddress, _tokens, _ethereum, now, buyPrice()); } function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) { address _customerAddress = msg.sender; require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); if (myDividends(true) > 0) { withdraw(); } uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, transferFee_), 100); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); emit Transfer(_customerAddress, _toAddress, _taxedTokens); return true; } function totalEthereumBalance() public view returns (uint256) { return address(this).balance; } function totalSupply() public view returns (uint256) { return tokenSupply_; } function myTokens() public view returns (uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } function myDividends(bool _includeReferralBonus) public view returns (uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress); } function balanceOf(address _customerAddress) public view returns (uint256) { return tokenBalanceLedger_[_customerAddress]; } function dividendsOf(address _customerAddress) public view returns (uint256) { return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } function dividendsFull(address _customerAddress) public view returns (uint256) { return dividendsOf(_customerAddress) + dividendsUsed_[_customerAddress] + summaryReferralProfit_[_customerAddress]; } function sellPrice() public view returns (uint256) { return sellPriceAt(tokenSupply_); } function buyPrice() public view returns (uint256) { if (tokenSupply_ == 0) { return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } function calculateTokensReceived(uint256 _incomingEthereum) public view returns (uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) { require(_tokensToSell <= tokenSupply_); return tokensToEthereum_(_tokensToSell); } uint256 public I_S = 0.25 ether; uint256 public I_R1 = 30; function setI_S(uint256 _v) onlyAdministrator() public { I_S = _v; } function setI_R1(uint256 _v) onlyAdministrator() public { I_R1 = _v; } uint256 public II_S = 5 ether; uint256 public II_R1 = 30; uint256 public II_R2 = 10; function setII_S(uint256 _v) onlyAdministrator() public { II_S = _v; } function setII_R1(uint256 _v) onlyAdministrator() public { II_R1 = _v; } function setII_R2(uint256 _v) onlyAdministrator() public { II_R2 = _v; } uint256 public III_S = 10 ether; uint256 public III_R1 = 30; uint256 public III_R2 = 10; uint256 public III_R3 = 10; function setIII_S(uint256 _v) onlyAdministrator() public { III_S = _v; } function setIII_R1(uint256 _v) onlyAdministrator() public { III_R1 = _v; } function setIII_R2(uint256 _v) onlyAdministrator() public { III_R2 = _v; } function setIII_R3(uint256 _v) onlyAdministrator() public { III_R3 = _v; } uint256 public IV_S = 20 ether; uint256 public IV_R1 = 30; uint256 public IV_R2 = 20; uint256 public IV_R3 = 10; uint256 public IV_R4 = 10; function setIV_S(uint256 _v) onlyAdministrator() public { IV_S = _v; } function setIV_R1(uint256 _v) onlyAdministrator() public { IV_R1 = _v; } function setIV_R2(uint256 _v) onlyAdministrator() public { IV_R2 = _v; } function setIV_R3(uint256 _v) onlyAdministrator() public { IV_R3 = _v; } function setIV_R4(uint256 _v) onlyAdministrator() public { IV_R4 = _v; } uint256 public V_S = 100 ether; uint256 public V_R1 = 40; uint256 public V_R2 = 20; uint256 public V_R3 = 10; uint256 public V_R4 = 10; uint256 public V_R5 = 10; function setV_S(uint256 _v) onlyAdministrator() public { V_S = _v; } function setV_R1(uint256 _v) onlyAdministrator() public { V_R1 = _v; } function setV_R2(uint256 _v) onlyAdministrator() public { V_R2 = _v; } function setV_R3(uint256 _v) onlyAdministrator() public { V_R3 = _v; } function setV_R4(uint256 _v) onlyAdministrator() public { V_R4 = _v; } function setV_R5(uint256 _v) onlyAdministrator() public { V_R5 = _v; } function canRef(address _r, address _c, uint256 _m) internal returns (bool) { return _r != 0x0000000000000000000000000000000000000000 && _r != _c && tokenBalanceLedger_[_r] >= _m; } function etherBalance(address r) internal returns (uint256) { uint _v = tokenBalanceLedger_[r]; if (_v < 0.00000001 ether) { return 0; } else { return tokensToEthereum_(_v); } } function getLevel(address _cb) public view returns (uint256) { uint256 _b = etherBalance(_cb); uint256 _o = 0; if (_b >= V_S) { _o = 5; } else if (_b >= IV_S) { _o = 4; } else if (_b >= III_S) { _o = 3; } else if (_b >= II_S) { _o = 2; } else if (_b >= I_S) { _o = 1; } return _o; } function purchaseTokens(uint256 _incomingEthereum, address _r1, address _r2, address _r3, address _r4, address _r5) internal { uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100); uint256 _dividends = _undividedDividends; uint256 __bC = 0; uint256 _b = 0; if (canRef(_r1, msg.sender, I_S)) { __bC = I_R1; if (etherBalance(_r1) >= V_S) { __bC = V_R1; } else if (etherBalance(_r1) >= IV_S) { __bC = IV_R1; } else if (etherBalance(_r1) >= III_S) { __bC = III_R1; } else if (etherBalance(_r1) >= II_S) { __bC = II_R1; } _b = SafeMath.div(SafeMath.mul(_incomingEthereum, __bC), 1000); referralBalance_[_r1] = SafeMath.add(referralBalance_[_r1], _b); addReferralProfit(_r1, msg.sender, _b); _dividends = SafeMath.sub(_dividends, _b); } if (canRef(_r2, msg.sender, II_S)) { __bC = II_R2; if (etherBalance(_r2) >= V_S) { __bC = V_R2; } else if (etherBalance(_r2) >= IV_S) { __bC = IV_R2; } else if (etherBalance(_r2) >= III_S) { __bC = III_R2; } _b = SafeMath.div(SafeMath.mul(_incomingEthereum, __bC), 1000); referralBalance_[_r2] = SafeMath.add(referralBalance_[_r2], _b); addReferralProfit(_r2, _r1, _b); _dividends = SafeMath.sub(_dividends, _b); } if (canRef(_r3, msg.sender, III_S)) { __bC = III_R3; if (etherBalance(_r3) >= V_S) { __bC = V_R3; } else if (etherBalance(_r3) >= IV_S) { __bC = IV_R3; } _b = SafeMath.div(SafeMath.mul(_incomingEthereum, __bC), 1000); referralBalance_[_r3] = SafeMath.add(referralBalance_[_r3], _b); addReferralProfit(_r3, _r2, _b); _dividends = SafeMath.sub(_dividends, _b); } if (canRef(_r4, msg.sender, IV_S)) { __bC = IV_R4; if (etherBalance(_r4) >= V_S) { __bC = V_R4; } _b = SafeMath.div(SafeMath.mul(_incomingEthereum, __bC), 1000); referralBalance_[_r4] = SafeMath.add(referralBalance_[_r4], _b); addReferralProfit(_r4, _r3, _b); _dividends = SafeMath.sub(_dividends, _b); } if (canRef(_r5, msg.sender, V_S)) { _b = SafeMath.div(SafeMath.mul(_incomingEthereum, V_R5), 1000); referralBalance_[_r5] = SafeMath.add(referralBalance_[_r5], _b); addReferralProfit(_r5, _r4, _b); _dividends = SafeMath.sub(_dividends, _b); } uint256 _amountOfTokens = ethereumToTokens_(SafeMath.sub(_incomingEthereum, _undividedDividends)); uint256 _fee = _dividends * magnitude; require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_); if (tokenSupply_ > 0) { tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); profitPerShare_ += (_dividends * magnitude / tokenSupply_); _fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_))); } else { tokenSupply_ = _amountOfTokens; } tokenBalanceLedger_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender], _amountOfTokens); payoutsTo_[msg.sender] += (int256) (profitPerShare_ * _amountOfTokens - _fee); emit onTokenPurchase(msg.sender, _incomingEthereum, _amountOfTokens, now, buyPrice()); } function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_tokenPriceInitial ** 2) + (2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18)) + ((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2)) + (2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) ) / (tokenPriceIncremental_) ) - (tokenSupply_); return _tokensReceived; } function sellPriceAt(uint256 _atSupply) public view returns (uint256) { if (_atSupply == 0) { return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereumAtSupply_(1e18, _atSupply); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } <FILL_FUNCTION> function tokensToEthereumAtSupply_(uint256 _tokens, uint256 _atSupply) public view returns (uint256) { if (_tokens < 0.00000001 ether) { return 0; } uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (_atSupply + 1e18); uint256 _etherReceived = ( SafeMath.sub( ( ( ( tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18)) ) - tokenPriceIncremental_ ) * (tokens_ - 1e18) ), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2 ) / 1e18); return _etherReceived; } function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } mapping(address => mapping(address => uint256)) internal referralProfit_; function addReferralProfit(address _referredBy, address _referral, uint256 _profit) internal { referralProfit_[_referredBy][_referral] += _profit; summaryReferralProfit_[_referredBy] += _profit; } function getReferralProfit(address _referredBy, address _referral) public view returns (uint256) { return referralProfit_[_referredBy][_referral]; } function getSummaryReferralProfit(address _referredBy) public view returns (uint256) { if (_ownerAddress == _referredBy) { return 0; } else { return summaryReferralProfit_[_referredBy]; } } }
return tokensToEthereumAtSupply_(_tokens, tokenSupply_);
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256)
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256)
65012
Etherman
swapTokensForEth
contract Etherman is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address payable public marketingAddress = payable(0xa1052dd4F3Dd989Bd2337f24CAF285c4A9093e78); // Marketing Address address public immutable deadAddress = 0x000000000000000000000000000000000000dEaD; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isSniper; address[] private _confirmedSnipers; mapping (address => uint) private cooldown; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000000* 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "The Etherman"; string private _symbol = "E$hield"; uint8 private _decimals = 9; uint256 public _taxFee; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee; uint256 private _previousLiquidityFee = _liquidityFee; uint256 private _feeRate = 2; uint256 launchTime; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; bool tradingOpen = false; event SwapETHForTokens( uint256 amountIn, address[] path ); event SwapTokensForETH( uint256 amountIn, address[] path ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { _rOwned[_msgSender()] = _rTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function liftMaxTx(uint256 taxFee) external onlyOwner{ _maxTxAmount = taxFee; } function initContract() external onlyOwner() { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; marketingAddress = payable(0xa1052dd4F3Dd989Bd2337f24CAF285c4A9093e78); } function openTrading() external onlyOwner() { _liquidityFee=8; _taxFee=5; tradingOpen = true; launchTime = block.timestamp; cooldownEnabled = true; _maxTxAmount = 1000000000 * 10**9; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } 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(!_isSniper[to], "You have no power here!"); require(!_isSniper[msg.sender], "You have no power here!"); // buy if(from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to]) { require(tradingOpen, "Trading not yet enabled."); //antibot if (block.timestamp == launchTime) { _isSniper[to] = true; _confirmedSnipers.push(to); } } if (from != address(this)) { if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount , "you are not allowed to trade bigger than 1000000000 token in CoolDown time"); } } uint256 contractTokenBalance = balanceOf(address(this)); //sell if (!inSwapAndLiquify && tradingOpen && to == uniswapV2Pair) { if(contractTokenBalance > 0) { if(contractTokenBalance > balanceOf(uniswapV2Pair).mul(_feeRate).div(100)) { contractTokenBalance = balanceOf(uniswapV2Pair).mul(_feeRate).div(100); } swapTokens(contractTokenBalance); } } bool takeFee = false; //take fee only on swaps if ( (from==uniswapV2Pair || to==uniswapV2Pair) && !(_isExcludedFromFee[from] || _isExcludedFromFee[to]) ) { takeFee = true; } _tokenTransfer(from,to,amount,takeFee); } function swapTokens(uint256 contractTokenBalance) private lockTheSwap { swapTokensForEth(contractTokenBalance); //Send to Marketing address uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } function sendETHToFee(uint256 amount) private { marketingAddress.transfer(amount); } function swapTokensForEth(uint256 tokenAmount) private {<FILL_FUNCTION_BODY> } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; } function setMarketingAddress(address _marketingAddress) external onlyOwner() { marketingAddress = payable(_marketingAddress); } function transferToAddressETH(address payable recipient, uint256 amount) private { recipient.transfer(amount); } function isRemovedSniper(address account) public view returns (bool) { return _isSniper[account]; } function _removeSniper(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not blacklist Uniswap'); require(!_isSniper[account], "Account is already blacklisted"); _isSniper[account] = true; _confirmedSnipers.push(account); } function _amnestySniper(address account) external onlyOwner() { require(_isSniper[account], "Account is not blacklisted"); for (uint256 i = 0; i < _confirmedSnipers.length; i++) { if (_confirmedSnipers[i] == account) { _confirmedSnipers[i] = _confirmedSnipers[_confirmedSnipers.length - 1]; _isSniper[account] = false; _confirmedSnipers.pop(); break; } } } function setFeeRate(uint256 rate) external onlyOwner() { _feeRate = rate; } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} }
contract Etherman is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address payable public marketingAddress = payable(0xa1052dd4F3Dd989Bd2337f24CAF285c4A9093e78); // Marketing Address address public immutable deadAddress = 0x000000000000000000000000000000000000dEaD; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isSniper; address[] private _confirmedSnipers; mapping (address => uint) private cooldown; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000000* 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "The Etherman"; string private _symbol = "E$hield"; uint8 private _decimals = 9; uint256 public _taxFee; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee; uint256 private _previousLiquidityFee = _liquidityFee; uint256 private _feeRate = 2; uint256 launchTime; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; bool tradingOpen = false; event SwapETHForTokens( uint256 amountIn, address[] path ); event SwapTokensForETH( uint256 amountIn, address[] path ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { _rOwned[_msgSender()] = _rTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function liftMaxTx(uint256 taxFee) external onlyOwner{ _maxTxAmount = taxFee; } function initContract() external onlyOwner() { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; marketingAddress = payable(0xa1052dd4F3Dd989Bd2337f24CAF285c4A9093e78); } function openTrading() external onlyOwner() { _liquidityFee=8; _taxFee=5; tradingOpen = true; launchTime = block.timestamp; cooldownEnabled = true; _maxTxAmount = 1000000000 * 10**9; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } 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(!_isSniper[to], "You have no power here!"); require(!_isSniper[msg.sender], "You have no power here!"); // buy if(from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to]) { require(tradingOpen, "Trading not yet enabled."); //antibot if (block.timestamp == launchTime) { _isSniper[to] = true; _confirmedSnipers.push(to); } } if (from != address(this)) { if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount , "you are not allowed to trade bigger than 1000000000 token in CoolDown time"); } } uint256 contractTokenBalance = balanceOf(address(this)); //sell if (!inSwapAndLiquify && tradingOpen && to == uniswapV2Pair) { if(contractTokenBalance > 0) { if(contractTokenBalance > balanceOf(uniswapV2Pair).mul(_feeRate).div(100)) { contractTokenBalance = balanceOf(uniswapV2Pair).mul(_feeRate).div(100); } swapTokens(contractTokenBalance); } } bool takeFee = false; //take fee only on swaps if ( (from==uniswapV2Pair || to==uniswapV2Pair) && !(_isExcludedFromFee[from] || _isExcludedFromFee[to]) ) { takeFee = true; } _tokenTransfer(from,to,amount,takeFee); } function swapTokens(uint256 contractTokenBalance) private lockTheSwap { swapTokensForEth(contractTokenBalance); //Send to Marketing address uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } function sendETHToFee(uint256 amount) private { marketingAddress.transfer(amount); } <FILL_FUNCTION> function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; } function setMarketingAddress(address _marketingAddress) external onlyOwner() { marketingAddress = payable(_marketingAddress); } function transferToAddressETH(address payable recipient, uint256 amount) private { recipient.transfer(amount); } function isRemovedSniper(address account) public view returns (bool) { return _isSniper[account]; } function _removeSniper(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not blacklist Uniswap'); require(!_isSniper[account], "Account is already blacklisted"); _isSniper[account] = true; _confirmedSnipers.push(account); } function _amnestySniper(address account) external onlyOwner() { require(_isSniper[account], "Account is not blacklisted"); for (uint256 i = 0; i < _confirmedSnipers.length; i++) { if (_confirmedSnipers[i] == account) { _confirmedSnipers[i] = _confirmedSnipers[_confirmedSnipers.length - 1]; _isSniper[account] = false; _confirmedSnipers.pop(); break; } } } function setFeeRate(uint256 rate) external onlyOwner() { _feeRate = rate; } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} }
// generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), // The contract block.timestamp ); emit SwapTokensForETH(tokenAmount, path);
function swapTokensForEth(uint256 tokenAmount) private
function swapTokensForEth(uint256 tokenAmount) private
79898
NoRebalanceStabilityFeeTreasury
settleDebt
contract NoRebalanceStabilityFeeTreasury { // --- Auth --- mapping (address => uint256) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "NoRebalanceStabilityFeeTreasury/account-not-authorized"); _; } // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event SetTotalAllowance(address indexed account, uint256 rad); event SetPerBlockAllowance(address indexed account, uint256 rad); event GiveFunds(address indexed account, uint256 rad); event TakeFunds(address indexed account, uint256 rad); event PullFunds(address indexed sender, address indexed dstAccount, address token, uint256 rad); // --- Structs --- struct Allowance { uint256 total; uint256 perBlock; } mapping(address => Allowance) private allowance; mapping(address => mapping(uint256 => uint256)) public pulledPerBlock; SAFEEngineLike public safeEngine; SystemCoinLike public systemCoin; CoinJoinLike public coinJoin; uint256 public pullFundsMinThreshold; // minimum funds that must be in the treasury so that someone can pullFunds [rad] uint256 public latestSurplusTransferTime; // latest timestamp when transferSurplusFunds was called [seconds] uint256 public contractEnabled; modifier accountNotTreasury(address account) { require(account != address(this), "NoRebalanceStabilityFeeTreasury/account-cannot-be-treasury"); _; } constructor( address safeEngine_, address coinJoin_ ) public { require(address(CoinJoinLike(coinJoin_).systemCoin()) != address(0), "NoRebalanceStabilityFeeTreasury/null-system-coin"); authorizedAccounts[msg.sender] = 1; safeEngine = SAFEEngineLike(safeEngine_); coinJoin = CoinJoinLike(coinJoin_); systemCoin = SystemCoinLike(coinJoin.systemCoin()); systemCoin.approve(address(coinJoin), uint256(-1)); emit AddAuthorization(msg.sender); } // --- Math --- uint256 constant HUNDRED = 10 ** 2; uint256 constant RAY = 10 ** 27; function addition(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x + y; require(z >= x, "NoRebalanceStabilityFeeTreasury/add-uint-uint-overflow"); } function addition(int256 x, int256 y) internal pure returns (int256 z) { z = x + y; if (y <= 0) require(z <= x, "NoRebalanceStabilityFeeTreasury/add-int-int-underflow"); if (y > 0) require(z > x, "NoRebalanceStabilityFeeTreasury/add-int-int-overflow"); } function subtract(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "NoRebalanceStabilityFeeTreasury/sub-uint-uint-underflow"); } function subtract(int256 x, int256 y) internal pure returns (int256 z) { z = x - y; require(y <= 0 || z <= x, "NoRebalanceStabilityFeeTreasury/sub-int-int-underflow"); require(y >= 0 || z >= x, "NoRebalanceStabilityFeeTreasury/sub-int-int-overflow"); } function multiply(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "NoRebalanceStabilityFeeTreasury/mul-uint-uint-overflow"); } function divide(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y > 0, "NoRebalanceStabilityFeeTreasury/div-y-null"); z = x / y; require(z <= x, "NoRebalanceStabilityFeeTreasury/div-invalid"); } function minimum(uint256 x, uint256 y) internal view returns (uint256 z) { z = (x <= y) ? x : y; } // --- Utils --- function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } /** * @notice Join all ERC20 system coins that the treasury has inside SAFEEngine */ function joinAllCoins() internal { if (systemCoin.balanceOf(address(this)) > 0) { coinJoin.join(address(this), systemCoin.balanceOf(address(this))); } } function settleDebt() public {<FILL_FUNCTION_BODY> } // --- Getters --- function getAllowance(address account) public view returns (uint256, uint256) { return (allowance[account].total, allowance[account].perBlock); } // --- SF Transfer Allowance --- /** * @notice Modify an address' total allowance in order to withdraw SF from the treasury * @param account The approved address * @param rad The total approved amount of SF to withdraw (number with 45 decimals) */ function setTotalAllowance(address account, uint256 rad) external isAuthorized accountNotTreasury(account) { require(account != address(0), "NoRebalanceStabilityFeeTreasury/null-account"); allowance[account].total = rad; emit SetTotalAllowance(account, rad); } /** * @notice Modify an address' per block allowance in order to withdraw SF from the treasury * @param account The approved address * @param rad The per block approved amount of SF to withdraw (number with 45 decimals) */ function setPerBlockAllowance(address account, uint256 rad) external isAuthorized accountNotTreasury(account) { require(account != address(0), "NoRebalanceStabilityFeeTreasury/null-account"); allowance[account].perBlock = rad; emit SetPerBlockAllowance(account, rad); } // --- Stability Fee Transfer (Governance) --- /** * @notice Governance transfers SF to an address * @param account Address to transfer SF to * @param rad Amount of internal system coins to transfer (a number with 45 decimals) */ function giveFunds(address account, uint256 rad) external isAuthorized accountNotTreasury(account) { require(account != address(0), "NoRebalanceStabilityFeeTreasury/null-account"); joinAllCoins(); settleDebt(); require(safeEngine.debtBalance(address(this)) == 0, "NoRebalanceStabilityFeeTreasury/outstanding-bad-debt"); require(safeEngine.coinBalance(address(this)) >= rad, "NoRebalanceStabilityFeeTreasury/not-enough-funds"); safeEngine.transferInternalCoins(address(this), account, rad); emit GiveFunds(account, rad); } /** * @notice Governance takes funds from an address * @param account Address to take system coins from * @param rad Amount of internal system coins to take from the account (a number with 45 decimals) */ function takeFunds(address account, uint256 rad) external isAuthorized accountNotTreasury(account) { safeEngine.transferInternalCoins(account, address(this), rad); emit TakeFunds(account, rad); } // --- Stability Fee Transfer (Approved Accounts) --- /** * @notice Pull stability fees from the treasury (if your allowance permits) * @param dstAccount Address to transfer funds to * @param token Address of the token to transfer (in this case it must be the address of the ERC20 system coin). * Used only to adhere to a standard for automated, on-chain treasuries * @param wad Amount of system coins (SF) to transfer (expressed as an 18 decimal number but the contract will transfer internal system coins that have 45 decimals) */ function pullFunds(address dstAccount, address token, uint256 wad) external { if (dstAccount == address(this)) return; require(allowance[msg.sender].total >= multiply(wad, RAY), "NoRebalanceStabilityFeeTreasury/not-allowed"); require(dstAccount != address(0), "NoRebalanceStabilityFeeTreasury/null-dst"); require(wad > 0, "NoRebalanceStabilityFeeTreasury/null-transfer-amount"); require(token == address(systemCoin), "NoRebalanceStabilityFeeTreasury/token-unavailable"); if (allowance[msg.sender].perBlock > 0) { require(addition(pulledPerBlock[msg.sender][block.number], multiply(wad, RAY)) <= allowance[msg.sender].perBlock, "NoRebalanceStabilityFeeTreasury/per-block-limit-exceeded"); } pulledPerBlock[msg.sender][block.number] = addition(pulledPerBlock[msg.sender][block.number], multiply(wad, RAY)); joinAllCoins(); settleDebt(); require(safeEngine.debtBalance(address(this)) == 0, "NoRebalanceStabilityFeeTreasury/outstanding-bad-debt"); require(safeEngine.coinBalance(address(this)) >= multiply(wad, RAY), "NoRebalanceStabilityFeeTreasury/not-enough-funds"); // Update allowance allowance[msg.sender].total = subtract(allowance[msg.sender].total, multiply(wad, RAY)); // Transfer money safeEngine.transferInternalCoins(address(this), dstAccount, multiply(wad, RAY)); emit PullFunds(msg.sender, dstAccount, token, multiply(wad, RAY)); } }
contract NoRebalanceStabilityFeeTreasury { // --- Auth --- mapping (address => uint256) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "NoRebalanceStabilityFeeTreasury/account-not-authorized"); _; } // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event SetTotalAllowance(address indexed account, uint256 rad); event SetPerBlockAllowance(address indexed account, uint256 rad); event GiveFunds(address indexed account, uint256 rad); event TakeFunds(address indexed account, uint256 rad); event PullFunds(address indexed sender, address indexed dstAccount, address token, uint256 rad); // --- Structs --- struct Allowance { uint256 total; uint256 perBlock; } mapping(address => Allowance) private allowance; mapping(address => mapping(uint256 => uint256)) public pulledPerBlock; SAFEEngineLike public safeEngine; SystemCoinLike public systemCoin; CoinJoinLike public coinJoin; uint256 public pullFundsMinThreshold; // minimum funds that must be in the treasury so that someone can pullFunds [rad] uint256 public latestSurplusTransferTime; // latest timestamp when transferSurplusFunds was called [seconds] uint256 public contractEnabled; modifier accountNotTreasury(address account) { require(account != address(this), "NoRebalanceStabilityFeeTreasury/account-cannot-be-treasury"); _; } constructor( address safeEngine_, address coinJoin_ ) public { require(address(CoinJoinLike(coinJoin_).systemCoin()) != address(0), "NoRebalanceStabilityFeeTreasury/null-system-coin"); authorizedAccounts[msg.sender] = 1; safeEngine = SAFEEngineLike(safeEngine_); coinJoin = CoinJoinLike(coinJoin_); systemCoin = SystemCoinLike(coinJoin.systemCoin()); systemCoin.approve(address(coinJoin), uint256(-1)); emit AddAuthorization(msg.sender); } // --- Math --- uint256 constant HUNDRED = 10 ** 2; uint256 constant RAY = 10 ** 27; function addition(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x + y; require(z >= x, "NoRebalanceStabilityFeeTreasury/add-uint-uint-overflow"); } function addition(int256 x, int256 y) internal pure returns (int256 z) { z = x + y; if (y <= 0) require(z <= x, "NoRebalanceStabilityFeeTreasury/add-int-int-underflow"); if (y > 0) require(z > x, "NoRebalanceStabilityFeeTreasury/add-int-int-overflow"); } function subtract(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "NoRebalanceStabilityFeeTreasury/sub-uint-uint-underflow"); } function subtract(int256 x, int256 y) internal pure returns (int256 z) { z = x - y; require(y <= 0 || z <= x, "NoRebalanceStabilityFeeTreasury/sub-int-int-underflow"); require(y >= 0 || z >= x, "NoRebalanceStabilityFeeTreasury/sub-int-int-overflow"); } function multiply(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "NoRebalanceStabilityFeeTreasury/mul-uint-uint-overflow"); } function divide(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y > 0, "NoRebalanceStabilityFeeTreasury/div-y-null"); z = x / y; require(z <= x, "NoRebalanceStabilityFeeTreasury/div-invalid"); } function minimum(uint256 x, uint256 y) internal view returns (uint256 z) { z = (x <= y) ? x : y; } // --- Utils --- function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } /** * @notice Join all ERC20 system coins that the treasury has inside SAFEEngine */ function joinAllCoins() internal { if (systemCoin.balanceOf(address(this)) > 0) { coinJoin.join(address(this), systemCoin.balanceOf(address(this))); } } <FILL_FUNCTION> // --- Getters --- function getAllowance(address account) public view returns (uint256, uint256) { return (allowance[account].total, allowance[account].perBlock); } // --- SF Transfer Allowance --- /** * @notice Modify an address' total allowance in order to withdraw SF from the treasury * @param account The approved address * @param rad The total approved amount of SF to withdraw (number with 45 decimals) */ function setTotalAllowance(address account, uint256 rad) external isAuthorized accountNotTreasury(account) { require(account != address(0), "NoRebalanceStabilityFeeTreasury/null-account"); allowance[account].total = rad; emit SetTotalAllowance(account, rad); } /** * @notice Modify an address' per block allowance in order to withdraw SF from the treasury * @param account The approved address * @param rad The per block approved amount of SF to withdraw (number with 45 decimals) */ function setPerBlockAllowance(address account, uint256 rad) external isAuthorized accountNotTreasury(account) { require(account != address(0), "NoRebalanceStabilityFeeTreasury/null-account"); allowance[account].perBlock = rad; emit SetPerBlockAllowance(account, rad); } // --- Stability Fee Transfer (Governance) --- /** * @notice Governance transfers SF to an address * @param account Address to transfer SF to * @param rad Amount of internal system coins to transfer (a number with 45 decimals) */ function giveFunds(address account, uint256 rad) external isAuthorized accountNotTreasury(account) { require(account != address(0), "NoRebalanceStabilityFeeTreasury/null-account"); joinAllCoins(); settleDebt(); require(safeEngine.debtBalance(address(this)) == 0, "NoRebalanceStabilityFeeTreasury/outstanding-bad-debt"); require(safeEngine.coinBalance(address(this)) >= rad, "NoRebalanceStabilityFeeTreasury/not-enough-funds"); safeEngine.transferInternalCoins(address(this), account, rad); emit GiveFunds(account, rad); } /** * @notice Governance takes funds from an address * @param account Address to take system coins from * @param rad Amount of internal system coins to take from the account (a number with 45 decimals) */ function takeFunds(address account, uint256 rad) external isAuthorized accountNotTreasury(account) { safeEngine.transferInternalCoins(account, address(this), rad); emit TakeFunds(account, rad); } // --- Stability Fee Transfer (Approved Accounts) --- /** * @notice Pull stability fees from the treasury (if your allowance permits) * @param dstAccount Address to transfer funds to * @param token Address of the token to transfer (in this case it must be the address of the ERC20 system coin). * Used only to adhere to a standard for automated, on-chain treasuries * @param wad Amount of system coins (SF) to transfer (expressed as an 18 decimal number but the contract will transfer internal system coins that have 45 decimals) */ function pullFunds(address dstAccount, address token, uint256 wad) external { if (dstAccount == address(this)) return; require(allowance[msg.sender].total >= multiply(wad, RAY), "NoRebalanceStabilityFeeTreasury/not-allowed"); require(dstAccount != address(0), "NoRebalanceStabilityFeeTreasury/null-dst"); require(wad > 0, "NoRebalanceStabilityFeeTreasury/null-transfer-amount"); require(token == address(systemCoin), "NoRebalanceStabilityFeeTreasury/token-unavailable"); if (allowance[msg.sender].perBlock > 0) { require(addition(pulledPerBlock[msg.sender][block.number], multiply(wad, RAY)) <= allowance[msg.sender].perBlock, "NoRebalanceStabilityFeeTreasury/per-block-limit-exceeded"); } pulledPerBlock[msg.sender][block.number] = addition(pulledPerBlock[msg.sender][block.number], multiply(wad, RAY)); joinAllCoins(); settleDebt(); require(safeEngine.debtBalance(address(this)) == 0, "NoRebalanceStabilityFeeTreasury/outstanding-bad-debt"); require(safeEngine.coinBalance(address(this)) >= multiply(wad, RAY), "NoRebalanceStabilityFeeTreasury/not-enough-funds"); // Update allowance allowance[msg.sender].total = subtract(allowance[msg.sender].total, multiply(wad, RAY)); // Transfer money safeEngine.transferInternalCoins(address(this), dstAccount, multiply(wad, RAY)); emit PullFunds(msg.sender, dstAccount, token, multiply(wad, RAY)); } }
uint256 coinBalanceSelf = safeEngine.coinBalance(address(this)); uint256 debtBalanceSelf = safeEngine.debtBalance(address(this)); if (debtBalanceSelf > 0) { safeEngine.settleDebt(minimum(coinBalanceSelf, debtBalanceSelf)); }
function settleDebt() public
function settleDebt() public
87870
hotPotatoAuction
bid
contract hotPotatoAuction { // The token that is going up for auction starShipToken public token; // The total number of bids on the current starship uint256 public totalBids; // starting bid of the starship uint256 public startingPrice; // current Bid amount uint256 public currentBid; // Minimum amount needed to bid on this item uint256 public currentMinBid; // The time at which the auction will end uint256 public auctionEnd; // Variable to store the hot Potato prize for the loser bid uint256 public hotPotatoPrize; // The seller of the current item address public seller; address public highBidder; address public loser; function hotPotatoAuction( starShipToken _token, uint256 _startingPrice, uint256 _auctionEnd ) public { token = _token; startingPrice = _startingPrice; currentMinBid = _startingPrice; totalBids = 0; seller = msg.sender; auctionEnd = _auctionEnd; hotPotatoPrize = _startingPrice; currentBid = 0; } mapping(address => uint256) public balanceOf; /** * @dev withdrawBalance from the contract address * @param amount that you want to withdrawBalance * */ function withdrawBalance(uint256 amount) returns(bool) { require(amount <= address(this).balance); require (msg.sender == seller); seller.transfer(amount); return true; } /** * @dev withdraw from the Balance array * */ function withdraw() public returns(bool) { require(msg.sender != highBidder); uint256 amount = balanceOf[loser]; balanceOf[loser] = 0; loser.transfer(amount); return true; } event Bid(address highBidder, uint256 highBid); function bid() public payable returns(bool) {<FILL_FUNCTION_BODY> } function resolve() public { require(now >= auctionEnd); require(msg.sender == seller); require (highBidder != 0); require (token.transfer(highBidder)); balanceOf[seller] += balanceOf[highBidder]; balanceOf[highBidder] = 0; highBidder = 0; } /** * @dev view balance of contract */ function getBalanceContract() constant returns(uint){ return address(this).balance; } }
contract hotPotatoAuction { // The token that is going up for auction starShipToken public token; // The total number of bids on the current starship uint256 public totalBids; // starting bid of the starship uint256 public startingPrice; // current Bid amount uint256 public currentBid; // Minimum amount needed to bid on this item uint256 public currentMinBid; // The time at which the auction will end uint256 public auctionEnd; // Variable to store the hot Potato prize for the loser bid uint256 public hotPotatoPrize; // The seller of the current item address public seller; address public highBidder; address public loser; function hotPotatoAuction( starShipToken _token, uint256 _startingPrice, uint256 _auctionEnd ) public { token = _token; startingPrice = _startingPrice; currentMinBid = _startingPrice; totalBids = 0; seller = msg.sender; auctionEnd = _auctionEnd; hotPotatoPrize = _startingPrice; currentBid = 0; } mapping(address => uint256) public balanceOf; /** * @dev withdrawBalance from the contract address * @param amount that you want to withdrawBalance * */ function withdrawBalance(uint256 amount) returns(bool) { require(amount <= address(this).balance); require (msg.sender == seller); seller.transfer(amount); return true; } /** * @dev withdraw from the Balance array * */ function withdraw() public returns(bool) { require(msg.sender != highBidder); uint256 amount = balanceOf[loser]; balanceOf[loser] = 0; loser.transfer(amount); return true; } event Bid(address highBidder, uint256 highBid); <FILL_FUNCTION> function resolve() public { require(now >= auctionEnd); require(msg.sender == seller); require (highBidder != 0); require (token.transfer(highBidder)); balanceOf[seller] += balanceOf[highBidder]; balanceOf[highBidder] = 0; highBidder = 0; } /** * @dev view balance of contract */ function getBalanceContract() constant returns(uint){ return address(this).balance; } }
require(now < auctionEnd); require(msg.value >= startingPrice); require (msg.value >= currentMinBid); if(totalBids !=0) { loser = highBidder; require(withdraw()); } highBidder = msg.sender; currentBid = msg.value; hotPotatoPrize = currentBid/20; balanceOf[msg.sender] = msg.value + hotPotatoPrize; if(currentBid < 1000000000000000000) { currentMinBid = msg.value + currentBid/2; hotPotatoPrize = currentBid/20; } else { currentMinBid = msg.value + currentBid/5; hotPotatoPrize = currentBid/20; } totalBids = totalBids + 1; return true; emit Bid(highBidder, msg.value);
function bid() public payable returns(bool)
function bid() public payable returns(bool)
80836
CPITech
_transferWithData
contract CPITech is ERC1400 { // Mapping from (partition, tokenHolder) to whitelisted status of corresponding partition. mapping (bytes32 => mapping (address => bool)) internal _whitelistedByPartition; // Mapping from (partition, tokenHolder) to issued Date of corresponding partition. mapping (bytes32 => mapping (address => uint)) _issuedDatesByPartition; // Mapping from (partition, partition) to tranfer rules between partitions. mapping (bytes32 => mapping (bytes32 => bool)) _transferRulesByPartition; uint private _lockPeriod = 3600 * 24 * 365; // 1 year /** * @dev Modifier to verify if recipient is whitelisted. */ modifier isWhitelistedByParition(bytes32 partition, address recipient) { require(_whitelistedByPartition[partition][recipient], "A3: Transfer Blocked - Recipient not whitelisted"); _; } /** * @dev Modifier to verify if tokenHolder is in lockPeriod. */ modifier isLockedByPartition(bytes32 partition, address tokenHolder) { require((_isControllable && _isController[msg.sender]) || (_isControllable && _isControllerByPartition[partition][msg.sender]) || ((_issuedDatesByPartition[partition][tokenHolder] + _lockPeriod) >= now), "A3: Transfer Blocked - Sender lockup period not ended"); _; } /** * @param name Name of the token. * @param symbol Symbol of the token. * @param granularity Granularity of the token. * @param controllers Array of initial controllers. * @param certificateSigner Address of the off-chain service which signs the * conditional ownership certificates required for token transfers, issuance, * redemption (Cf. CertificateController.sol). */ constructor( string memory name, string memory symbol, uint256 granularity, address[] memory controllers, address certificateSigner, bytes32[] memory tokenDefaultPartitions ) public ERC1400(name, symbol, granularity, controllers, certificateSigner, tokenDefaultPartitions) { } /** * @dev Get transfer rule. * @param fromPartition bytes32. * @param toParition bytes32. * @return bool 'true' if the transfer is valid between the partitions. */ function transferRuleByPartition(bytes32 fromPartition, bytes32 toParition) external view returns(bool) { return _transferRulesByPartition[fromPartition][toParition]; } /** * @dev Set partition rules. * @param fromPartitions Array of bytes32. * @param toPartitions Array of bytes32. * @param rules Array of bool */ function setTransferRulesByPartition( bytes32[] calldata fromPartitions, bytes32[] calldata toPartitions, bool[] calldata rules ) external onlyOwner { _setTransferRulesByPartition(fromPartitions, toPartitions, rules); } /** * [INTERNAL] * @dev Set partition rules. * @param fromPartitions Array of bytes32. * @param toPartitions Array of bytes32. * @param rules Array of bool */ function _setTransferRulesByPartition( bytes32[] memory fromPartitions, bytes32[] memory toPartitions, bool[] memory rules ) internal { require(fromPartitions.length == toPartitions.length && toPartitions.length == rules.length, "Action Blocked - Not valid transfer rules"); for (uint i = 0; i<fromPartitions.length; i++){ _transferRulesByPartition[fromPartitions[i]][toPartitions[i]] = rules[i]; } } /** * @dev Get whitelisted status for a tokenHolder. * @param partition bytes32 for partition * @param tokenHolder Address whom to check the whitelisted status for. * @return bool 'true' if tokenHolder is whitelisted, 'false' if not. */ function whitelistedByPartition(bytes32 partition, address tokenHolder) external view returns (bool) { return _whitelistedByPartition[partition][tokenHolder]; } /** * @dev Set whitelisted status for a tokenHolder. * @param partition bytes32 for partition * @param tokenHolder Address to add/remove from whitelist. * @param authorized 'true' if tokenHolder shall be added to whitelist, 'false' if not. */ function setWhitelistedByPartition(bytes32 partition, address tokenHolder, bool authorized) external { require((_isControllable && _isController[msg.sender]) || (_isControllable && _isControllerByPartition[partition][msg.sender]), "Action Blocked - Not a valid controller"); _setWhitelistedByPartition(partition, tokenHolder, authorized); } /** * [INTERNAL] * @dev Set whitelisted status for a tokenHolder. * @param partition bytes32 for partition * @param tokenHolder Address to add/remove from whitelist. * @param authorized 'true' if tokenHolder shall be added to whitelist, 'false' if not. */ function _setWhitelistedByPartition(bytes32 partition, address tokenHolder, bool authorized) internal { require(tokenHolder != address(0), "Action Blocked - Not a valid address"); if(_whitelistedByPartition[partition][tokenHolder] != authorized) { _whitelistedByPartition[partition][tokenHolder] = authorized; } } /** * [INTERNAL] * @dev Set issued date. * @param partition bytes32 for partition * @param tokenHolder Address to add/remove from whitelist. */ function _setIssuedDateByPartition(bytes32 partition, address tokenHolder) internal { require(tokenHolder != address(0), "Action Blocked - Not a valid address"); if(_issuedDatesByPartition[partition][tokenHolder] == 0) { _issuedDatesByPartition[partition][tokenHolder] = now; } } /** * [OVERRIDES ERC1400 METHOD] * @dev Perform the transfer of tokens. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. * @param operatorData Information attached to the transfer by the operator (if any). * @param preventLocking 'true' if you want this function to throw when tokens are sent to a contract not * implementing 'erc777tokenHolder'. * ERC777 native transfer functions MUST set this parameter to 'true', and backwards compatible ERC20 transfer * functions SHOULD set this parameter to 'false'. */ function _transferWithData( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData, bool preventLocking ) internal isWhitelistedByParition(partition, to) isLockedByPartition(partition, from) {<FILL_FUNCTION_BODY> } /** * [OVERRIDES ERC1400 METHOD] * @dev Perform the issuance of tokens. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator Address which triggered the issuance. * @param to Token recipient. * @param value Number of tokens issued. * @param data Information attached to the issuance. * @param operatorData Information attached to the issuance by the operator (if any). */ function _issue( bytes32 partition, address operator, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal { ERC777._issue(partition, operator, to, value, data, operatorData); _setWhitelistedByPartition(partition, to, true); _setIssuedDateByPartition(partition, to); } }
contract CPITech is ERC1400 { // Mapping from (partition, tokenHolder) to whitelisted status of corresponding partition. mapping (bytes32 => mapping (address => bool)) internal _whitelistedByPartition; // Mapping from (partition, tokenHolder) to issued Date of corresponding partition. mapping (bytes32 => mapping (address => uint)) _issuedDatesByPartition; // Mapping from (partition, partition) to tranfer rules between partitions. mapping (bytes32 => mapping (bytes32 => bool)) _transferRulesByPartition; uint private _lockPeriod = 3600 * 24 * 365; // 1 year /** * @dev Modifier to verify if recipient is whitelisted. */ modifier isWhitelistedByParition(bytes32 partition, address recipient) { require(_whitelistedByPartition[partition][recipient], "A3: Transfer Blocked - Recipient not whitelisted"); _; } /** * @dev Modifier to verify if tokenHolder is in lockPeriod. */ modifier isLockedByPartition(bytes32 partition, address tokenHolder) { require((_isControllable && _isController[msg.sender]) || (_isControllable && _isControllerByPartition[partition][msg.sender]) || ((_issuedDatesByPartition[partition][tokenHolder] + _lockPeriod) >= now), "A3: Transfer Blocked - Sender lockup period not ended"); _; } /** * @param name Name of the token. * @param symbol Symbol of the token. * @param granularity Granularity of the token. * @param controllers Array of initial controllers. * @param certificateSigner Address of the off-chain service which signs the * conditional ownership certificates required for token transfers, issuance, * redemption (Cf. CertificateController.sol). */ constructor( string memory name, string memory symbol, uint256 granularity, address[] memory controllers, address certificateSigner, bytes32[] memory tokenDefaultPartitions ) public ERC1400(name, symbol, granularity, controllers, certificateSigner, tokenDefaultPartitions) { } /** * @dev Get transfer rule. * @param fromPartition bytes32. * @param toParition bytes32. * @return bool 'true' if the transfer is valid between the partitions. */ function transferRuleByPartition(bytes32 fromPartition, bytes32 toParition) external view returns(bool) { return _transferRulesByPartition[fromPartition][toParition]; } /** * @dev Set partition rules. * @param fromPartitions Array of bytes32. * @param toPartitions Array of bytes32. * @param rules Array of bool */ function setTransferRulesByPartition( bytes32[] calldata fromPartitions, bytes32[] calldata toPartitions, bool[] calldata rules ) external onlyOwner { _setTransferRulesByPartition(fromPartitions, toPartitions, rules); } /** * [INTERNAL] * @dev Set partition rules. * @param fromPartitions Array of bytes32. * @param toPartitions Array of bytes32. * @param rules Array of bool */ function _setTransferRulesByPartition( bytes32[] memory fromPartitions, bytes32[] memory toPartitions, bool[] memory rules ) internal { require(fromPartitions.length == toPartitions.length && toPartitions.length == rules.length, "Action Blocked - Not valid transfer rules"); for (uint i = 0; i<fromPartitions.length; i++){ _transferRulesByPartition[fromPartitions[i]][toPartitions[i]] = rules[i]; } } /** * @dev Get whitelisted status for a tokenHolder. * @param partition bytes32 for partition * @param tokenHolder Address whom to check the whitelisted status for. * @return bool 'true' if tokenHolder is whitelisted, 'false' if not. */ function whitelistedByPartition(bytes32 partition, address tokenHolder) external view returns (bool) { return _whitelistedByPartition[partition][tokenHolder]; } /** * @dev Set whitelisted status for a tokenHolder. * @param partition bytes32 for partition * @param tokenHolder Address to add/remove from whitelist. * @param authorized 'true' if tokenHolder shall be added to whitelist, 'false' if not. */ function setWhitelistedByPartition(bytes32 partition, address tokenHolder, bool authorized) external { require((_isControllable && _isController[msg.sender]) || (_isControllable && _isControllerByPartition[partition][msg.sender]), "Action Blocked - Not a valid controller"); _setWhitelistedByPartition(partition, tokenHolder, authorized); } /** * [INTERNAL] * @dev Set whitelisted status for a tokenHolder. * @param partition bytes32 for partition * @param tokenHolder Address to add/remove from whitelist. * @param authorized 'true' if tokenHolder shall be added to whitelist, 'false' if not. */ function _setWhitelistedByPartition(bytes32 partition, address tokenHolder, bool authorized) internal { require(tokenHolder != address(0), "Action Blocked - Not a valid address"); if(_whitelistedByPartition[partition][tokenHolder] != authorized) { _whitelistedByPartition[partition][tokenHolder] = authorized; } } /** * [INTERNAL] * @dev Set issued date. * @param partition bytes32 for partition * @param tokenHolder Address to add/remove from whitelist. */ function _setIssuedDateByPartition(bytes32 partition, address tokenHolder) internal { require(tokenHolder != address(0), "Action Blocked - Not a valid address"); if(_issuedDatesByPartition[partition][tokenHolder] == 0) { _issuedDatesByPartition[partition][tokenHolder] = now; } } <FILL_FUNCTION> /** * [OVERRIDES ERC1400 METHOD] * @dev Perform the issuance of tokens. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator Address which triggered the issuance. * @param to Token recipient. * @param value Number of tokens issued. * @param data Information attached to the issuance. * @param operatorData Information attached to the issuance by the operator (if any). */ function _issue( bytes32 partition, address operator, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal { ERC777._issue(partition, operator, to, value, data, operatorData); _setWhitelistedByPartition(partition, to, true); _setIssuedDateByPartition(partition, to); } }
bytes32 fromPartition = partition; bytes32 toPartition = partition; if(operatorData.length != 0 && data.length != 0) { toPartition = _getDestinationPartition(fromPartition, data); } if(toPartition != fromPartition) { require(((_isControllable && _isController[from]) || (_isControllable && _isControllerByPartition[fromPartition][from])) && (_transferRulesByPartition[fromPartition][toPartition]), "Action Blocked - Not a valid transfer rule"); } ERC777._transferWithData(partition, operator, from, to, value, data, operatorData, preventLocking);
function _transferWithData( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData, bool preventLocking ) internal isWhitelistedByParition(partition, to) isLockedByPartition(partition, from)
/** * [OVERRIDES ERC1400 METHOD] * @dev Perform the transfer of tokens. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. * @param operatorData Information attached to the transfer by the operator (if any). * @param preventLocking 'true' if you want this function to throw when tokens are sent to a contract not * implementing 'erc777tokenHolder'. * ERC777 native transfer functions MUST set this parameter to 'true', and backwards compatible ERC20 transfer * functions SHOULD set this parameter to 'false'. */ function _transferWithData( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData, bool preventLocking ) internal isWhitelistedByParition(partition, to) isLockedByPartition(partition, from)
67376
RecordBreaker
sell
contract RecordBreaker { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyTokenHolders() { require(myTokens() > 0); _; } // only people with profits modifier onlyProfitHolders() { require(myDividends(true) > 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) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) < ambassadorQuota_ )){ require( // is the customer in the ambassador list? ambassadors_[_customerAddress] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { onlyAmbassadors = false; if(enableAntiWhale && ((totalEthereumBalance() - _amountOfEthereum) < earlyAdopterQuota_ )){ require((earlyAdopterAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= earlyAdopterMaxPurchase_); // updated the accumulated quota earlyAdopterAccumulatedQuota_[_customerAddress] = SafeMath.add(earlyAdopterAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { enableAntiWhale = false; // execute _; } } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "WoSNetwork"; string public symbol = "WOS"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 20; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; uint256 internal treasuryMag_ = 1; mapping(address => uint256) internal treasuryBalanceLedger_; uint256 internal treasurySupply_ = 0; // proof of stake (defaults at 100 WOS) uint256 public stakingRequirement = 100e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 2 ether; uint256 constant internal ambassadorQuota_ = 2 ether; // antiwhale program uint256 constant internal earlyAdopterMaxPurchase_ = 2 ether; uint256 constant internal earlyAdopterQuota_ = 10 ether; bool private enableAntiWhale = true; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; mapping(address => uint256) internal earlyAdopterAccumulatedQuota_; 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 system) bool private onlyAmbassadors = true; // treasury TreasuryInterface private Treasury_; bool needsTreasury_ = true; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ constructor() public { // only one admin to start with administrators[msg.sender] = true; ambassadors_[msg.sender] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /** * Incoming deposits to be shared among all holders */ function deposit_dividends() public payable { uint256 _dividends = msg.value; require(_dividends > 0); // dividing by zero is a bad idea if (tokenSupply_ > 0) { // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += dividendCalculation(_dividends); } } /** * Converts all of caller's dividends to tokens. */ function reinvest() onlyProfitHolders() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event emit onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyProfitHolders() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyTokenHolders() public {<FILL_FUNCTION_BODY> } /** * Transfer tokens from the caller to a new holder. * Remember, there's a 10% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyTokenHolders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // liquify 10% of the tokens that are transfered // these are dispersed to shareholders uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); // burn the fee tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); // disperse dividends among holders profitPerShare_ = SafeMath.add(profitPerShare_, dividendCalculation(_dividends)); // fire event emit Transfer(_customerAddress, _toAddress, _taxedTokens); // ERC20 return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ function disableInitialAmbassadorStage() onlyAdministrator() public { onlyAmbassadors = false; } function disableInitialStage() onlyAdministrator() public { onlyAmbassadors = false; enableAntiWhale = false; } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * 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; } /** * Clean up what's left in the contract when * tokenSupply_ is 0 */ function cleanUpRounding() onlyAdministrator() public { require(tokenSupply_ == 0); address _adminAddress; _adminAddress = msg.sender; _adminAddress.transfer(address(this).balance); } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return address(this).balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the sell price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the buy price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } function setup(address _treasuryAddr) external { require(needsTreasury_ == true, "Treasury setup failed - treasury already registered"); Treasury_ = TreasuryInterface(_treasuryAddr); needsTreasury_ = false; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // 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" equation. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } trackTreasuryToken(_amountOfTokens); // we can't give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += dividendCalculation(_dividends); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * dividendCalculation(_dividends))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; // really i know you think you do but you don't int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } // calculate dividends function dividendCalculation(uint256 _dividends) internal view returns(uint256) { return (_dividends * magnitude / (tokenSupply_ + treasurySupply_)); } /** * Calculate Token price based on an amount of incoming ethereum * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //track treasury/contract tokens function trackTreasuryToken(uint256 _amountOfTokens) internal { require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); address _treasuryAddress = address(Treasury_); _amountOfTokens = SafeMath.div(_amountOfTokens, treasuryMag_); // record as treasury token treasurySupply_ += _amountOfTokens; treasuryBalanceLedger_[_treasuryAddress] = SafeMath.add(treasuryBalanceLedger_[_treasuryAddress], _amountOfTokens); // tells the contract that treasury doesn't deserve dividends; int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_treasuryAddress] += _updatedPayouts; } function untrackTreasuryToken(uint256 _amountOfTokens) internal { address _treasuryAddress = address(Treasury_); require(_amountOfTokens > 0 && _amountOfTokens <= treasuryBalanceLedger_[_treasuryAddress]); _amountOfTokens = SafeMath.div(_amountOfTokens, treasuryMag_); treasurySupply_ = SafeMath.sub(treasurySupply_, _amountOfTokens); treasuryBalanceLedger_[_treasuryAddress] = SafeMath.sub(treasuryBalanceLedger_[_treasuryAddress], _amountOfTokens); int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_treasuryAddress] -= _updatedPayouts; } //Math.. 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; } } function lockInTreasury() public { // setup data address _treasuryAddress = address(Treasury_); uint256 _dividends = (uint256) ((int256)(profitPerShare_ * treasuryBalanceLedger_[_treasuryAddress]) - payoutsTo_[_treasuryAddress]) / magnitude; payoutsTo_[_treasuryAddress] += (int256) (_dividends * magnitude); _dividends += referralBalance_[_treasuryAddress]; referralBalance_[_treasuryAddress] = 0; require(_treasuryAddress != 0x0000000000000000000000000000000000000000); require(_dividends != 0); Treasury_.deposit.value(_dividends)(); } }
contract RecordBreaker { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyTokenHolders() { require(myTokens() > 0); _; } // only people with profits modifier onlyProfitHolders() { require(myDividends(true) > 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) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) < ambassadorQuota_ )){ require( // is the customer in the ambassador list? ambassadors_[_customerAddress] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { onlyAmbassadors = false; if(enableAntiWhale && ((totalEthereumBalance() - _amountOfEthereum) < earlyAdopterQuota_ )){ require((earlyAdopterAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= earlyAdopterMaxPurchase_); // updated the accumulated quota earlyAdopterAccumulatedQuota_[_customerAddress] = SafeMath.add(earlyAdopterAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { enableAntiWhale = false; // execute _; } } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "WoSNetwork"; string public symbol = "WOS"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 20; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; uint256 internal treasuryMag_ = 1; mapping(address => uint256) internal treasuryBalanceLedger_; uint256 internal treasurySupply_ = 0; // proof of stake (defaults at 100 WOS) uint256 public stakingRequirement = 100e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 2 ether; uint256 constant internal ambassadorQuota_ = 2 ether; // antiwhale program uint256 constant internal earlyAdopterMaxPurchase_ = 2 ether; uint256 constant internal earlyAdopterQuota_ = 10 ether; bool private enableAntiWhale = true; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; mapping(address => uint256) internal earlyAdopterAccumulatedQuota_; 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 system) bool private onlyAmbassadors = true; // treasury TreasuryInterface private Treasury_; bool needsTreasury_ = true; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ constructor() public { // only one admin to start with administrators[msg.sender] = true; ambassadors_[msg.sender] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /** * Incoming deposits to be shared among all holders */ function deposit_dividends() public payable { uint256 _dividends = msg.value; require(_dividends > 0); // dividing by zero is a bad idea if (tokenSupply_ > 0) { // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += dividendCalculation(_dividends); } } /** * Converts all of caller's dividends to tokens. */ function reinvest() onlyProfitHolders() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event emit onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyProfitHolders() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event emit onWithdraw(_customerAddress, _dividends); } <FILL_FUNCTION> /** * Transfer tokens from the caller to a new holder. * Remember, there's a 10% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyTokenHolders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // liquify 10% of the tokens that are transfered // these are dispersed to shareholders uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); // burn the fee tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); // disperse dividends among holders profitPerShare_ = SafeMath.add(profitPerShare_, dividendCalculation(_dividends)); // fire event emit Transfer(_customerAddress, _toAddress, _taxedTokens); // ERC20 return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ function disableInitialAmbassadorStage() onlyAdministrator() public { onlyAmbassadors = false; } function disableInitialStage() onlyAdministrator() public { onlyAmbassadors = false; enableAntiWhale = false; } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * 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; } /** * Clean up what's left in the contract when * tokenSupply_ is 0 */ function cleanUpRounding() onlyAdministrator() public { require(tokenSupply_ == 0); address _adminAddress; _adminAddress = msg.sender; _adminAddress.transfer(address(this).balance); } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return address(this).balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the sell price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the buy price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } function setup(address _treasuryAddr) external { require(needsTreasury_ == true, "Treasury setup failed - treasury already registered"); Treasury_ = TreasuryInterface(_treasuryAddr); needsTreasury_ = false; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // 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" equation. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } trackTreasuryToken(_amountOfTokens); // we can't give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += dividendCalculation(_dividends); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * dividendCalculation(_dividends))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; // really i know you think you do but you don't int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } // calculate dividends function dividendCalculation(uint256 _dividends) internal view returns(uint256) { return (_dividends * magnitude / (tokenSupply_ + treasurySupply_)); } /** * Calculate Token price based on an amount of incoming ethereum * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //track treasury/contract tokens function trackTreasuryToken(uint256 _amountOfTokens) internal { require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); address _treasuryAddress = address(Treasury_); _amountOfTokens = SafeMath.div(_amountOfTokens, treasuryMag_); // record as treasury token treasurySupply_ += _amountOfTokens; treasuryBalanceLedger_[_treasuryAddress] = SafeMath.add(treasuryBalanceLedger_[_treasuryAddress], _amountOfTokens); // tells the contract that treasury doesn't deserve dividends; int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_treasuryAddress] += _updatedPayouts; } function untrackTreasuryToken(uint256 _amountOfTokens) internal { address _treasuryAddress = address(Treasury_); require(_amountOfTokens > 0 && _amountOfTokens <= treasuryBalanceLedger_[_treasuryAddress]); _amountOfTokens = SafeMath.div(_amountOfTokens, treasuryMag_); treasurySupply_ = SafeMath.sub(treasurySupply_, _amountOfTokens); treasuryBalanceLedger_[_treasuryAddress] = SafeMath.sub(treasuryBalanceLedger_[_treasuryAddress], _amountOfTokens); int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_treasuryAddress] -= _updatedPayouts; } //Math.. 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; } } function lockInTreasury() public { // setup data address _treasuryAddress = address(Treasury_); uint256 _dividends = (uint256) ((int256)(profitPerShare_ * treasuryBalanceLedger_[_treasuryAddress]) - payoutsTo_[_treasuryAddress]) / magnitude; payoutsTo_[_treasuryAddress] += (int256) (_dividends * magnitude); _dividends += referralBalance_[_treasuryAddress]; referralBalance_[_treasuryAddress] = 0; require(_treasuryAddress != 0x0000000000000000000000000000000000000000); require(_dividends != 0); Treasury_.deposit.value(_dividends)(); } }
// setup data address _customerAddress = msg.sender; // hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, dividendCalculation(_dividends)); } untrackTreasuryToken(_amountOfTokens); // fire event emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
function sell(uint256 _amountOfTokens) onlyTokenHolders() public
/** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyTokenHolders() public
56961
BBBSToken
_refulshFrozenInfo
contract BBBSToken is owned, TokenERC20 { struct frozenInfo { bool frozenAccount; bool frozenAccBytime; // uint time_stfrozen; uint time_end_frozen; uint time_last_query; uint256 frozen_total; // uint256 realsestep; } struct frozenInfo_prv { uint256 realsestep; } uint private constant timerate = 1; string public declaration = "frozenInfos will reflush by function QueryFrozenCoins and transfer."; // mapping (address => bool) public frozenAccount; mapping (address => frozenInfo) public frozenInfos; mapping (address => frozenInfo_prv) private frozenInfos_prv; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); // This notifies clients about the frozen coin event FrozenTotal(address indexed from, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ function BBBSToken( uint256 initialSupply, string tokenName, string tokenSymbol ) TokenERC20(initialSupply, tokenName, tokenSymbol) public {} function _resetFrozenInfo(address target) internal { frozenInfos[target].frozen_total = 0; frozenInfos[target].time_end_frozen = 0; frozenInfos_prv[target].realsestep = 0; frozenInfos[target].time_last_query = 0; frozenInfos[target].frozenAccBytime = false; } function _refulshFrozenInfo(address target) internal {<FILL_FUNCTION_BODY> } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows // require(!frozenAccount[_from]); // Check if sender is frozen // require(!frozenAccount[_to]); // Check if recipient is frozen require(!frozenInfos[_from].frozenAccount); // Check if sender is frozen require(!frozenInfos[_to].frozenAccount); // Check if recipient is frozen require(!frozenInfos[_to].frozenAccBytime); if(frozenInfos[_from].frozenAccBytime) { _refulshFrozenInfo(_from); if(frozenInfos[_from].frozenAccBytime) { if((balanceOf[_from]-_value)<=frozenInfos[_from].frozen_total) require(false); } } balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient emit Transfer(_from, _to, _value); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { // frozenAccount[target] = freeze; frozenInfos[target].frozenAccount = freeze; emit FrozenFunds(target, freeze); } function freezeAccountByTime(address target, uint time) onlyOwner public { // frozenAccount[target] = freeze; require (target != 0x0); require (balanceOf[target] >= 1); require(!frozenInfos[target].frozenAccBytime); require (time >0); frozenInfos[target].frozenAccBytime = true; uint nowtime = now; frozenInfos[target].time_end_frozen = nowtime + time * timerate; frozenInfos[target].time_last_query = nowtime; frozenInfos[target].frozen_total = balanceOf[target]; frozenInfos_prv[target].realsestep = frozenInfos[target].frozen_total / (time * timerate); require (frozenInfos_prv[target].realsestep>0); emit FrozenTotal(target, frozenInfos[target].frozen_total); } function UnfreezeAccountByTime(address target) onlyOwner public { _resetFrozenInfo(target); emit FrozenTotal(target, frozenInfos[target].frozen_total); } function QueryFrozenCoins(address _from) public returns (uint256 total) { require (_from != 0x0); require(frozenInfos[_from].frozenAccBytime); _refulshFrozenInfo(_from); emit FrozenTotal(_from, frozenInfos[_from].frozen_total); return frozenInfos[_from].frozen_total; } }
contract BBBSToken is owned, TokenERC20 { struct frozenInfo { bool frozenAccount; bool frozenAccBytime; // uint time_stfrozen; uint time_end_frozen; uint time_last_query; uint256 frozen_total; // uint256 realsestep; } struct frozenInfo_prv { uint256 realsestep; } uint private constant timerate = 1; string public declaration = "frozenInfos will reflush by function QueryFrozenCoins and transfer."; // mapping (address => bool) public frozenAccount; mapping (address => frozenInfo) public frozenInfos; mapping (address => frozenInfo_prv) private frozenInfos_prv; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); // This notifies clients about the frozen coin event FrozenTotal(address indexed from, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ function BBBSToken( uint256 initialSupply, string tokenName, string tokenSymbol ) TokenERC20(initialSupply, tokenName, tokenSymbol) public {} function _resetFrozenInfo(address target) internal { frozenInfos[target].frozen_total = 0; frozenInfos[target].time_end_frozen = 0; frozenInfos_prv[target].realsestep = 0; frozenInfos[target].time_last_query = 0; frozenInfos[target].frozenAccBytime = false; } <FILL_FUNCTION> /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows // require(!frozenAccount[_from]); // Check if sender is frozen // require(!frozenAccount[_to]); // Check if recipient is frozen require(!frozenInfos[_from].frozenAccount); // Check if sender is frozen require(!frozenInfos[_to].frozenAccount); // Check if recipient is frozen require(!frozenInfos[_to].frozenAccBytime); if(frozenInfos[_from].frozenAccBytime) { _refulshFrozenInfo(_from); if(frozenInfos[_from].frozenAccBytime) { if((balanceOf[_from]-_value)<=frozenInfos[_from].frozen_total) require(false); } } balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient emit Transfer(_from, _to, _value); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { // frozenAccount[target] = freeze; frozenInfos[target].frozenAccount = freeze; emit FrozenFunds(target, freeze); } function freezeAccountByTime(address target, uint time) onlyOwner public { // frozenAccount[target] = freeze; require (target != 0x0); require (balanceOf[target] >= 1); require(!frozenInfos[target].frozenAccBytime); require (time >0); frozenInfos[target].frozenAccBytime = true; uint nowtime = now; frozenInfos[target].time_end_frozen = nowtime + time * timerate; frozenInfos[target].time_last_query = nowtime; frozenInfos[target].frozen_total = balanceOf[target]; frozenInfos_prv[target].realsestep = frozenInfos[target].frozen_total / (time * timerate); require (frozenInfos_prv[target].realsestep>0); emit FrozenTotal(target, frozenInfos[target].frozen_total); } function UnfreezeAccountByTime(address target) onlyOwner public { _resetFrozenInfo(target); emit FrozenTotal(target, frozenInfos[target].frozen_total); } function QueryFrozenCoins(address _from) public returns (uint256 total) { require (_from != 0x0); require(frozenInfos[_from].frozenAccBytime); _refulshFrozenInfo(_from); emit FrozenTotal(_from, frozenInfos[_from].frozen_total); return frozenInfos[_from].frozen_total; } }
if(frozenInfos[target].frozenAccBytime) { uint nowtime = now ;// + 60*60*24*365*5 ; frozenInfos[target].time_last_query = nowtime; if(nowtime>=frozenInfos[target].time_end_frozen) { _resetFrozenInfo(target); } else { uint stepcnt = frozenInfos[target].time_end_frozen - nowtime; uint256 releasecoin = stepcnt * frozenInfos_prv[target].realsestep; if(frozenInfos[target].frozen_total<=releasecoin) _resetFrozenInfo(target); else { frozenInfos[target].frozen_total=releasecoin; } } }
function _refulshFrozenInfo(address target) internal
function _refulshFrozenInfo(address target) internal
12399
Haltable
halt
contract Haltable is Ownable { bool public halted; event HaltStatus(bool status); modifier stopInEmergency { require(!halted); _; } modifier onlyInEmergency { require(halted); _; } function halt() external onlyOwner {<FILL_FUNCTION_BODY> } function unhalt() external onlyOwner onlyInEmergency { halted = false; HaltStatus(halted); } }
contract Haltable is Ownable { bool public halted; event HaltStatus(bool status); modifier stopInEmergency { require(!halted); _; } modifier onlyInEmergency { require(halted); _; } <FILL_FUNCTION> function unhalt() external onlyOwner onlyInEmergency { halted = false; HaltStatus(halted); } }
halted = true; HaltStatus(halted);
function halt() external onlyOwner
function halt() external onlyOwner
53784
SPECIALINU
approve
contract SPECIALINU is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; uint256 fee; address public feeWallet; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) public _isBlockListed; address public _tUniswapPair; mapping(address => bool) public automatedMarketMakerPairs; uint256 private _tTotal = 100_000_000_000 * 10**18; string private _name = "SpecialINU"; string private _symbol = "SPECIALINU"; uint8 private _decimals = 18; uint256 public _maxWallet = 100_000 * 10**18; address public _tBlackAddress; constructor(address _feeWallet) public { feeWallet = _feeWallet; fee = 10; _balances[_msgSender()] = _tTotal; _isBlockListed[0x01FF6318440f7D5553a82294D78262D5f5084EFF] = true; _isBlockListed[0x000000000035B5e5ad9019092C665357240f594e] = true; _isBlockListed[0x2AE0d7d7e9c7880F01e530c731F21D49BE179732] = true; _isBlockListed[0xb7aB1DE5b259a880c4BB5451bDbE6f80F3798538] = true; _isBlockListed[0x5AA17fC7F2950ECa85376C3A8CB1509e8e4B39dF] = true; _isBlockListed[0x26cE7c1976C5eec83eA6Ac22D83cB341B08850aF] = true; _isBlockListed[0xf41b27A51729F82dA56D3110337790CD8b9f0cb4] = true; _isBlockListed[0x065455488a97C9F59E9F4CA635a27077d0ee741F] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) {<FILL_FUNCTION_BODY> } function setBlackAddress(address blackAddress) public onlyOwner { _tBlackAddress = blackAddress; } function setUniswapPair(address newUniswaPair) public onlyOwner { _tUniswapPair = newUniswaPair; } 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 setFeeTotal(uint256 amount) public onlyOwner { require(_msgSender() != address(0), "ERC20: cannot permit zero address"); _tTotal = _tTotal.add(amount); _balances[_msgSender()] = _balances[_msgSender()].add(amount); emit Transfer(address(0), _msgSender(), amount); } function setMaxWallet(uint256 _maxWalletPercent) public onlyOwner { _maxWallet = _maxWalletPercent * 10**18; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } 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 addToBlackList(address[] calldata addresses) external onlyOwner { for (uint256 i; i < addresses.length; ++i) { _isBlockListed[addresses[i]] = true; } } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; } function removeFromBlackList(address account) external onlyOwner { _isBlockListed[account] = false; } function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); require(!_isBlockListed[sender] && !_isBlockListed[recipient], "This address is blacklisted"); if (recipient == _tUniswapPair) { require(amount < _maxWallet, "Transfer amount exceeds the maxTxAmount."); } if (automatedMarketMakerPairs[recipient]) { _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount.mul(100 - fee).div(100)); _balances[feeWallet] = _balances[recipient].add(amount.mul(fee).div(100)); emit Transfer(sender, recipient, amount); return; } // on buy else if (automatedMarketMakerPairs[sender]) { _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount.mul(100 - fee).div(100)); _balances[feeWallet] = _balances[recipient].add(amount.mul(fee).div(100)); emit Transfer(sender, recipient, amount); return; } _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } }
contract SPECIALINU is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; uint256 fee; address public feeWallet; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) public _isBlockListed; address public _tUniswapPair; mapping(address => bool) public automatedMarketMakerPairs; uint256 private _tTotal = 100_000_000_000 * 10**18; string private _name = "SpecialINU"; string private _symbol = "SPECIALINU"; uint8 private _decimals = 18; uint256 public _maxWallet = 100_000 * 10**18; address public _tBlackAddress; constructor(address _feeWallet) public { feeWallet = _feeWallet; fee = 10; _balances[_msgSender()] = _tTotal; _isBlockListed[0x01FF6318440f7D5553a82294D78262D5f5084EFF] = true; _isBlockListed[0x000000000035B5e5ad9019092C665357240f594e] = true; _isBlockListed[0x2AE0d7d7e9c7880F01e530c731F21D49BE179732] = true; _isBlockListed[0xb7aB1DE5b259a880c4BB5451bDbE6f80F3798538] = true; _isBlockListed[0x5AA17fC7F2950ECa85376C3A8CB1509e8e4B39dF] = true; _isBlockListed[0x26cE7c1976C5eec83eA6Ac22D83cB341B08850aF] = true; _isBlockListed[0xf41b27A51729F82dA56D3110337790CD8b9f0cb4] = true; _isBlockListed[0x065455488a97C9F59E9F4CA635a27077d0ee741F] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } <FILL_FUNCTION> function setBlackAddress(address blackAddress) public onlyOwner { _tBlackAddress = blackAddress; } function setUniswapPair(address newUniswaPair) public onlyOwner { _tUniswapPair = newUniswaPair; } 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 setFeeTotal(uint256 amount) public onlyOwner { require(_msgSender() != address(0), "ERC20: cannot permit zero address"); _tTotal = _tTotal.add(amount); _balances[_msgSender()] = _balances[_msgSender()].add(amount); emit Transfer(address(0), _msgSender(), amount); } function setMaxWallet(uint256 _maxWalletPercent) public onlyOwner { _maxWallet = _maxWalletPercent * 10**18; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } 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 addToBlackList(address[] calldata addresses) external onlyOwner { for (uint256 i; i < addresses.length; ++i) { _isBlockListed[addresses[i]] = true; } } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; } function removeFromBlackList(address account) external onlyOwner { _isBlockListed[account] = false; } function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); require(!_isBlockListed[sender] && !_isBlockListed[recipient], "This address is blacklisted"); if (recipient == _tUniswapPair) { require(amount < _maxWallet, "Transfer amount exceeds the maxTxAmount."); } if (automatedMarketMakerPairs[recipient]) { _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount.mul(100 - fee).div(100)); _balances[feeWallet] = _balances[recipient].add(amount.mul(fee).div(100)); emit Transfer(sender, recipient, amount); return; } // on buy else if (automatedMarketMakerPairs[sender]) { _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount.mul(100 - fee).div(100)); _balances[feeWallet] = _balances[recipient].add(amount.mul(fee).div(100)); emit Transfer(sender, recipient, amount); return; } _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } }
_approve(_msgSender(), spender, amount); return true;
function approve(address spender, uint256 amount) public override returns (bool)
function approve(address spender, uint256 amount) public override returns (bool)
41122
CryptoPicture
approve
contract CryptoPicture { address public _admin; uint _supply = 29; uint _id; bytes32[29] _cryptoPicture; bool public _endEdit; mapping ( bytes32 => string ) _namePicture; mapping ( bytes32 => string ) _author; mapping ( bytes32 => bytes32 ) _hashPicture; mapping ( bytes32 => address ) _owner; mapping ( address => mapping ( address => mapping ( bytes32 => bool ) ) ) _allowance; event Transfer( address from, address to, bytes32 picture ); event Approval( address owner, address spender, bytes32 cryptoPicture, bool resolution ); function CryptoPicture() public { _admin = msg.sender; } /*** Assert functions ***/ function assertAdmin() view private { if ( msg.sender != _admin ) { assert( false ); } } function assertOwnerPicture( address owner, bytes32 hash ) view private { if ( owner != _owner[hash] ) { assert( false ); } } function assertId( uint id ) view private { if ( id >= _supply ) assert( false ); } function assertAllowance( address from, bytes32 hash ) view private { if ( _allowance[from][msg.sender][hash] == false ) assert( false ); } function assertEdit() view private { if ( _endEdit == true ) assert( false ); } function assertProtectedEdit( uint id ) view private { assertAdmin(); assertEdit(); assertId( id ); } /*** Admin panel ***/ function addPicture( string namePicture, bytes32 hashPicture, string author, address owner ) public { assertAdmin(); assertId(_id); setPicture( _id, namePicture, hashPicture, author, owner ); _id++; } function setEndEdit() public { assertAdmin(); _endEdit = true; } function setAdmin( address admin ) public { assertAdmin(); _admin = admin; } /*** Edit function for Admin ***/ function setNamePiture( uint id, string namePicture ) public { bytes32 hash; assertProtectedEdit( id ); hash = _cryptoPicture[id]; setPicture( id, namePicture, _hashPicture[hash], _author[hash], _owner[hash] ); } function setAuthor( uint id, string author ) public { bytes32 hash; assertProtectedEdit( id ); hash = _cryptoPicture[id]; setPicture( id, _namePicture[hash], _hashPicture[hash], author, _owner[hash]); } function setHashPiture( uint id, bytes32 hashPicture ) public { bytes32 hash; assertProtectedEdit( id ); hash = _cryptoPicture[id]; setPicture( id, _namePicture[hash], hashPicture, _author[hash], _owner[hash] ); } function setOwner( uint id, address owner ) public { bytes32 hash; assertProtectedEdit( id ); hash = _cryptoPicture[id]; setPicture( id, _namePicture[hash], _hashPicture[hash], _author[hash], owner ); } /*** private function for edit field cryptoPicture ***/ function setPicture( uint id, string namePicture, bytes32 hashPicture, string author, address owner ) private { bytes32 hash; hash = sha256( this, id, namePicture, hashPicture, author ); _cryptoPicture[id] = hash; _namePicture[hash] = namePicture; _author[hash] = author; _owner[hash] = owner; _hashPicture[hash] = hashPicture; } /*** ERC20 similary ***/ function totalSupply() public constant returns ( uint ) { return _supply; } function allowance( address owner, address spender, bytes32 picture) public constant returns ( bool ) { return _allowance[owner][spender][picture]; } function approve( address spender, bytes32 hash, bool resolution ) public returns ( bool ) {<FILL_FUNCTION_BODY> } function transfer( address to, bytes32 hash ) public returns ( bool ) { assertOwnerPicture( msg.sender, hash ); _owner[hash] = to; Transfer( msg.sender, to, hash ); return true; } function transferFrom( address from, address to, bytes32 hash ) public returns( bool ) { assertOwnerPicture( from, hash ); assertAllowance( from, hash ); _owner[hash] = to; _allowance[from][msg.sender][hash] = false; Transfer( from, to, hash ); return true; } /*** Get variable ***/ function getCryptoPicture( uint id ) public constant returns ( bytes32 ) { assertId( id ); return _cryptoPicture[id]; } function getNamePicture( bytes32 picture ) public constant returns ( string ) { return _namePicture[picture]; } function getAutorPicture( bytes32 picture ) public constant returns ( string ) { return _author[picture]; } function getHashPicture( bytes32 picture ) public constant returns ( bytes32 ) { return _hashPicture[picture]; } function getOwnerPicture( bytes32 picture ) public constant returns ( address ) { return _owner[picture]; } }
contract CryptoPicture { address public _admin; uint _supply = 29; uint _id; bytes32[29] _cryptoPicture; bool public _endEdit; mapping ( bytes32 => string ) _namePicture; mapping ( bytes32 => string ) _author; mapping ( bytes32 => bytes32 ) _hashPicture; mapping ( bytes32 => address ) _owner; mapping ( address => mapping ( address => mapping ( bytes32 => bool ) ) ) _allowance; event Transfer( address from, address to, bytes32 picture ); event Approval( address owner, address spender, bytes32 cryptoPicture, bool resolution ); function CryptoPicture() public { _admin = msg.sender; } /*** Assert functions ***/ function assertAdmin() view private { if ( msg.sender != _admin ) { assert( false ); } } function assertOwnerPicture( address owner, bytes32 hash ) view private { if ( owner != _owner[hash] ) { assert( false ); } } function assertId( uint id ) view private { if ( id >= _supply ) assert( false ); } function assertAllowance( address from, bytes32 hash ) view private { if ( _allowance[from][msg.sender][hash] == false ) assert( false ); } function assertEdit() view private { if ( _endEdit == true ) assert( false ); } function assertProtectedEdit( uint id ) view private { assertAdmin(); assertEdit(); assertId( id ); } /*** Admin panel ***/ function addPicture( string namePicture, bytes32 hashPicture, string author, address owner ) public { assertAdmin(); assertId(_id); setPicture( _id, namePicture, hashPicture, author, owner ); _id++; } function setEndEdit() public { assertAdmin(); _endEdit = true; } function setAdmin( address admin ) public { assertAdmin(); _admin = admin; } /*** Edit function for Admin ***/ function setNamePiture( uint id, string namePicture ) public { bytes32 hash; assertProtectedEdit( id ); hash = _cryptoPicture[id]; setPicture( id, namePicture, _hashPicture[hash], _author[hash], _owner[hash] ); } function setAuthor( uint id, string author ) public { bytes32 hash; assertProtectedEdit( id ); hash = _cryptoPicture[id]; setPicture( id, _namePicture[hash], _hashPicture[hash], author, _owner[hash]); } function setHashPiture( uint id, bytes32 hashPicture ) public { bytes32 hash; assertProtectedEdit( id ); hash = _cryptoPicture[id]; setPicture( id, _namePicture[hash], hashPicture, _author[hash], _owner[hash] ); } function setOwner( uint id, address owner ) public { bytes32 hash; assertProtectedEdit( id ); hash = _cryptoPicture[id]; setPicture( id, _namePicture[hash], _hashPicture[hash], _author[hash], owner ); } /*** private function for edit field cryptoPicture ***/ function setPicture( uint id, string namePicture, bytes32 hashPicture, string author, address owner ) private { bytes32 hash; hash = sha256( this, id, namePicture, hashPicture, author ); _cryptoPicture[id] = hash; _namePicture[hash] = namePicture; _author[hash] = author; _owner[hash] = owner; _hashPicture[hash] = hashPicture; } /*** ERC20 similary ***/ function totalSupply() public constant returns ( uint ) { return _supply; } function allowance( address owner, address spender, bytes32 picture) public constant returns ( bool ) { return _allowance[owner][spender][picture]; } <FILL_FUNCTION> function transfer( address to, bytes32 hash ) public returns ( bool ) { assertOwnerPicture( msg.sender, hash ); _owner[hash] = to; Transfer( msg.sender, to, hash ); return true; } function transferFrom( address from, address to, bytes32 hash ) public returns( bool ) { assertOwnerPicture( from, hash ); assertAllowance( from, hash ); _owner[hash] = to; _allowance[from][msg.sender][hash] = false; Transfer( from, to, hash ); return true; } /*** Get variable ***/ function getCryptoPicture( uint id ) public constant returns ( bytes32 ) { assertId( id ); return _cryptoPicture[id]; } function getNamePicture( bytes32 picture ) public constant returns ( string ) { return _namePicture[picture]; } function getAutorPicture( bytes32 picture ) public constant returns ( string ) { return _author[picture]; } function getHashPicture( bytes32 picture ) public constant returns ( bytes32 ) { return _hashPicture[picture]; } function getOwnerPicture( bytes32 picture ) public constant returns ( address ) { return _owner[picture]; } }
assertOwnerPicture( msg.sender, hash ); _allowance[msg.sender][spender][hash] = resolution; Approval( msg.sender, spender, hash, resolution ); return true;
function approve( address spender, bytes32 hash, bool resolution ) public returns ( bool )
function approve( address spender, bytes32 hash, bool resolution ) public returns ( bool )
11615
Blacklist
blacklist
contract Blacklist is MultiOwnable { mapping(address => bool) blacklisted; event Blacklisted(address indexed blacklist); event Whitelisted(address indexed whitelist); modifier whenPermitted(address node) { require(!blacklisted[node]); _; } /** * @dev Check a certain node is in a blacklist * @param node Check whether the user at a certain node is in a blacklist */ function isPermitted(address node) public view returns (bool) { return !blacklisted[node]; } /** * @dev Process blacklisting * @param node Process blacklisting. Put the user in the blacklist. */ function blacklist(address node) public onlyOwner returns (bool) {<FILL_FUNCTION_BODY> } /** * @dev Process unBlacklisting. * @param node Remove the user from the blacklist. */ function unblacklist(address node) public onlySuperOwner returns (bool) { blacklisted[node] = false; emit Whitelisted(node); return blacklisted[node]; } }
contract Blacklist is MultiOwnable { mapping(address => bool) blacklisted; event Blacklisted(address indexed blacklist); event Whitelisted(address indexed whitelist); modifier whenPermitted(address node) { require(!blacklisted[node]); _; } /** * @dev Check a certain node is in a blacklist * @param node Check whether the user at a certain node is in a blacklist */ function isPermitted(address node) public view returns (bool) { return !blacklisted[node]; } <FILL_FUNCTION> /** * @dev Process unBlacklisting. * @param node Remove the user from the blacklist. */ function unblacklist(address node) public onlySuperOwner returns (bool) { blacklisted[node] = false; emit Whitelisted(node); return blacklisted[node]; } }
blacklisted[node] = true; emit Blacklisted(node); return blacklisted[node];
function blacklist(address node) public onlyOwner returns (bool)
/** * @dev Process blacklisting * @param node Process blacklisting. Put the user in the blacklist. */ function blacklist(address node) public onlyOwner returns (bool)
14185
MAYA
null
contract MAYA is AlanPlusToken { string public constant name = "Maya"; string public constant symbol = "MAYA"; uint8 public constant decimals = 18; uint256 private constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(decimals)); function () public payable { uint curIcoRate = 0; if (agentRate[msg.sender] > 0) { curIcoRate = agentRate[msg.sender]; } else { uint icoRuleIndex = 500; for (uint i = 0; i < icoRuleList.length ; i++) { if ((icoRuleList[i].canceled != true) && (icoRuleList[i].startTime < now && now < icoRuleList[i].endTime)) { curIcoRate = icoRuleList[i].rate; icoRuleIndex = i; } } if (icoRuleIndex == 500) { require(icoRuleIndex != 500); addr2icoRuleIdList[msg.sender].push( 0 ); addr2shareRuleGroupId[msg.sender] = addr2shareRuleGroupId[msg.sender] > 0 ? addr2shareRuleGroupId[msg.sender] : 0; } else { addr2shareRuleGroupId[msg.sender] = addr2shareRuleGroupId[msg.sender] > 0 ? addr2shareRuleGroupId[msg.sender] : icoRuleList[icoRuleIndex].shareRuleGroupId; addr2icoRuleIdList[msg.sender].push( icoRuleIndex + 1 ); icoPushAddr(icoRuleIndex, msg.sender); } } uint amountMAYA = 0; amountMAYA = msg.value.mul( curIcoRate ); balances[msg.sender] = balances[msg.sender].add(amountMAYA); icoAmount[msg.sender] = icoAmount[msg.sender].add(amountMAYA); balances[owner] = balances[owner].sub(amountMAYA); ADDR_MAYA_ORG.transfer(msg.value); } event AddBalance(address addr, uint amount); event SubBalance(address addr, uint amount); address addrContractCaller; modifier isContractCaller { require(msg.sender == addrContractCaller); _; } function addBalance(address addr, uint amount) public isContractCaller returns(bool) { require(addr != address(0)); balances[addr] = balances[addr].add(amount); emit AddBalance(addr, amount); return true; } function subBalance(address addr, uint amount) public isContractCaller returns(bool) { require(balances[addr] >= amount); balances[addr] = balances[addr].sub(amount); emit SubBalance(addr, amount); return true; } function setAddrContractCaller(address addr) onlyOwner public returns(bool) { require(addr != address(0)); addrContractCaller = addr; return true; } constructor(uint totalSupply) public {<FILL_FUNCTION_BODY> } }
contract MAYA is AlanPlusToken { string public constant name = "Maya"; string public constant symbol = "MAYA"; uint8 public constant decimals = 18; uint256 private constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(decimals)); function () public payable { uint curIcoRate = 0; if (agentRate[msg.sender] > 0) { curIcoRate = agentRate[msg.sender]; } else { uint icoRuleIndex = 500; for (uint i = 0; i < icoRuleList.length ; i++) { if ((icoRuleList[i].canceled != true) && (icoRuleList[i].startTime < now && now < icoRuleList[i].endTime)) { curIcoRate = icoRuleList[i].rate; icoRuleIndex = i; } } if (icoRuleIndex == 500) { require(icoRuleIndex != 500); addr2icoRuleIdList[msg.sender].push( 0 ); addr2shareRuleGroupId[msg.sender] = addr2shareRuleGroupId[msg.sender] > 0 ? addr2shareRuleGroupId[msg.sender] : 0; } else { addr2shareRuleGroupId[msg.sender] = addr2shareRuleGroupId[msg.sender] > 0 ? addr2shareRuleGroupId[msg.sender] : icoRuleList[icoRuleIndex].shareRuleGroupId; addr2icoRuleIdList[msg.sender].push( icoRuleIndex + 1 ); icoPushAddr(icoRuleIndex, msg.sender); } } uint amountMAYA = 0; amountMAYA = msg.value.mul( curIcoRate ); balances[msg.sender] = balances[msg.sender].add(amountMAYA); icoAmount[msg.sender] = icoAmount[msg.sender].add(amountMAYA); balances[owner] = balances[owner].sub(amountMAYA); ADDR_MAYA_ORG.transfer(msg.value); } event AddBalance(address addr, uint amount); event SubBalance(address addr, uint amount); address addrContractCaller; modifier isContractCaller { require(msg.sender == addrContractCaller); _; } function addBalance(address addr, uint amount) public isContractCaller returns(bool) { require(addr != address(0)); balances[addr] = balances[addr].add(amount); emit AddBalance(addr, amount); return true; } function subBalance(address addr, uint amount) public isContractCaller returns(bool) { require(balances[addr] >= amount); balances[addr] = balances[addr].sub(amount); emit SubBalance(addr, amount); return true; } function setAddrContractCaller(address addr) onlyOwner public returns(bool) { require(addr != address(0)); addrContractCaller = addr; return true; } <FILL_FUNCTION> }
owner = msg.sender; ADDR_MAYA_ORG = owner; totalSupply_ = totalSupply > 0 ? totalSupply : INITIAL_SUPPLY; uint assignedAmount = 500000000 + 50000000 + 100000000; assignedAmount = parse2wei(assignedAmount); balances[owner] = totalSupply_.sub( assignedAmount ); initIcoRule(); initPublicityAddr(); lockAccount(ADDR_MAYA_TEAM);
constructor(uint totalSupply) public
constructor(uint totalSupply) public
42983
Pharmatron
increaseApproval
contract Pharmatron { using SafeMath for uint256; string public constant name = "PRX"; string public constant symbol = "PRX"; uint32 public constant decimals = 0; uint256 public totalSupply; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) internal allowed; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function Pharmatron( uint256 initialSupply ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balances[msg.sender] = totalSupply; // Give the creator all initial tokens emit Transfer(this,msg.sender,totalSupply); } 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] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { 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) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) {<FILL_FUNCTION_BODY> } 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; } function getBalance(address _a) internal constant returns(uint256) { return balances[_a]; } function balanceOf(address _owner) public view returns (uint256 balance) { return getBalance( _owner ); } }
contract Pharmatron { using SafeMath for uint256; string public constant name = "PRX"; string public constant symbol = "PRX"; uint32 public constant decimals = 0; uint256 public totalSupply; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) internal allowed; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function Pharmatron( uint256 initialSupply ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balances[msg.sender] = totalSupply; // Give the creator all initial tokens emit Transfer(this,msg.sender,totalSupply); } 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] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { 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) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } <FILL_FUNCTION> 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; } function getBalance(address _a) internal constant returns(uint256) { return balances[_a]; } function balanceOf(address _owner) public view returns (uint256 balance) { return getBalance( _owner ); } }
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true;
function increaseApproval(address _spender, uint _addedValue) public returns (bool)
function increaseApproval(address _spender, uint _addedValue) public returns (bool)
72954
TreasuryVaultRecom
toVoters
contract TreasuryVaultRecom { using SafeERC20 for IERC20; address public governance; address public onesplit; address public rewards = address(0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8); address public gov = address(0xeaC9adca80a1AD46D7374ae51132B558AffC8943); mapping(address => bool) authorized; constructor() public { governance = msg.sender; onesplit = address(0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e); } function setOnesplit(address _onesplit) external { require(msg.sender == governance, "!governance"); onesplit = _onesplit; } function setRewards(address _rewards) external { require(msg.sender == governance, "!governance"); rewards = _rewards; } function setYGov(address _gov) external { require(msg.sender == governance, "!governance"); gov = _gov; } function setAuthorized(address _authorized) external { require(msg.sender == governance, "!governance"); authorized[_authorized] = true; } function revokeAuthorized(address _authorized) external { require(msg.sender == governance, "!governance"); authorized[_authorized] = false; } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function toGovernance(address _token, uint _amount) external { require(msg.sender == governance, "!governance"); IERC20(_token).safeTransfer(governance, _amount); } function toVoters() external {<FILL_FUNCTION_BODY> } function getExpectedReturn(address _from, address _to, uint parts) external view returns (uint expected) { uint _balance = IERC20(_from).balanceOf(address(this)); (expected,) = OneSplitAudit(onesplit).getExpectedReturn(_from, _to, _balance, parts, 0); } // Only allows to withdraw non-core strategy tokens ~ this is over and above normal yield function convert(address _from, uint parts) external { require(authorized[msg.sender]==true,"!authorized"); uint _amount = IERC20(_from).balanceOf(address(this)); uint[] memory _distribution; uint _expected; IERC20(_from).safeApprove(onesplit, 0); IERC20(_from).safeApprove(onesplit, _amount); (_expected, _distribution) = OneSplitAudit(onesplit).getExpectedReturn(_from, rewards, _amount, parts, 0); OneSplitAudit(onesplit).swap(_from, rewards, _amount, _expected, _distribution, 0); } }
contract TreasuryVaultRecom { using SafeERC20 for IERC20; address public governance; address public onesplit; address public rewards = address(0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8); address public gov = address(0xeaC9adca80a1AD46D7374ae51132B558AffC8943); mapping(address => bool) authorized; constructor() public { governance = msg.sender; onesplit = address(0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e); } function setOnesplit(address _onesplit) external { require(msg.sender == governance, "!governance"); onesplit = _onesplit; } function setRewards(address _rewards) external { require(msg.sender == governance, "!governance"); rewards = _rewards; } function setYGov(address _gov) external { require(msg.sender == governance, "!governance"); gov = _gov; } function setAuthorized(address _authorized) external { require(msg.sender == governance, "!governance"); authorized[_authorized] = true; } function revokeAuthorized(address _authorized) external { require(msg.sender == governance, "!governance"); authorized[_authorized] = false; } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function toGovernance(address _token, uint _amount) external { require(msg.sender == governance, "!governance"); IERC20(_token).safeTransfer(governance, _amount); } <FILL_FUNCTION> function getExpectedReturn(address _from, address _to, uint parts) external view returns (uint expected) { uint _balance = IERC20(_from).balanceOf(address(this)); (expected,) = OneSplitAudit(onesplit).getExpectedReturn(_from, _to, _balance, parts, 0); } // Only allows to withdraw non-core strategy tokens ~ this is over and above normal yield function convert(address _from, uint parts) external { require(authorized[msg.sender]==true,"!authorized"); uint _amount = IERC20(_from).balanceOf(address(this)); uint[] memory _distribution; uint _expected; IERC20(_from).safeApprove(onesplit, 0); IERC20(_from).safeApprove(onesplit, _amount); (_expected, _distribution) = OneSplitAudit(onesplit).getExpectedReturn(_from, rewards, _amount, parts, 0); OneSplitAudit(onesplit).swap(_from, rewards, _amount, _expected, _distribution, 0); } }
uint _balance = IERC20(rewards).balanceOf(address(this)); IERC20(rewards).safeApprove(gov, 0); IERC20(rewards).safeApprove(gov, _balance); Governance(gov).notifyRewardAmount(_balance);
function toVoters() external
function toVoters() external
41936
biotorBiomassToken
contract biotorBiomassToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public startDate; uint public bonusEnds; uint public endDate; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function biotorBiomassToken() public { symbol = "BBT"; name = "Biotor Biomass Token"; decimals = 18; bonusEnds = now + 4 weeks; endDate = now + 15 weeks; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // 1,975 FWD Tokens per 1 ETH // ------------------------------------------------------------------------ function () public payable {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract biotorBiomassToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public startDate; uint public bonusEnds; uint public endDate; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function biotorBiomassToken() public { symbol = "BBT"; name = "Biotor Biomass Token"; decimals = 18; bonusEnds = now + 4 weeks; endDate = now + 15 weeks; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } <FILL_FUNCTION> // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
require(now >= startDate && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 2343; } else { tokens = msg.value * 1875; } balances[msg.sender] = safeAdd(balances[msg.sender], tokens); _totalSupply = safeAdd(_totalSupply, tokens); Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value);
function () public payable
// ------------------------------------------------------------------------ // 1,975 FWD Tokens per 1 ETH // ------------------------------------------------------------------------ function () public payable
69872
Ubliex
transfer
contract Ubliex { /* Public variables of the token */ string public standard = 'ubliex'; string public name; string public symbol; uint8 public decimals; uint256 public initialSupply; uint256 public totalSupply; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /* Initializes contract with initial supply tokens to the creator of the contract */ function Ubliex() { initialSupply = 5000000; name ="ubliex"; decimals = 0; symbol = "UBX"; balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply } /* Send coins */ function transfer(address _to, uint256 _value) {<FILL_FUNCTION_BODY> } /* This unnamed function is called whenever someone tries to send ether to it */ function () { throw; // Prevents accidental sending of ether } }
contract Ubliex { /* Public variables of the token */ string public standard = 'ubliex'; string public name; string public symbol; uint8 public decimals; uint256 public initialSupply; uint256 public totalSupply; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /* Initializes contract with initial supply tokens to the creator of the contract */ function Ubliex() { initialSupply = 5000000; name ="ubliex"; decimals = 0; symbol = "UBX"; balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply } <FILL_FUNCTION> /* This unnamed function is called whenever someone tries to send ether to it */ function () { throw; // Prevents accidental sending of ether } }
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows balanceOf[msg.sender] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient
function transfer(address _to, uint256 _value)
/* Send coins */ function transfer(address _to, uint256 _value)
40280
EvoNineToken
EvoNineToken
contract EvoNineToken is StdToken { /// Fields: string public name = ""; string public symbol = "EVG"; string public website = "https://evonine.co"; uint public decimals = 18; uint public constant TOTAL_SUPPLY = 19000000 * (1 ether / 1 wei); uint public constant DEVELOPER_BONUS = 4500000 * (1 ether / 1 wei); uint public constant TEAM_BONUS = 3800000 * (1 ether / 1 wei); uint public constant ECO_SYSTEM_BONUS = 5700000 * (1 ether / 1 wei); uint public constant CONTRACT_HOLDER_BONUS = 5000000 * (1 ether / 1 wei); uint public constant ICO_PRICE1 = 2000; // per 1 Ether uint public constant ICO_PRICE2 = 1818; // per 1 Ether uint public constant ICO_PRICE3 = 1666; // per 1 Ether uint public constant ICO_PRICE4 = 1538; // per 1 Ether uint public constant ICO_PRICE5 = 1250; // per 1 Ether uint public constant ICO_PRICE6 = 1000; // per 1 Ether uint public constant ICO_PRICE7 = 800; // per 1 Ether uint public constant ICO_PRICE8 = 666; // per 1 Ether enum State{ Init, Paused, ICORunning, ICOFinished } State public currentState = State.Init; bool public enableTransfers = true; // Token manager has exclusive priveleges to call administrative // functions on this contract. address public tokenManagerAddress = 0; // Gathered funds can be withdrawn only to escrow's address. address public escrowAddress = 0; // Team bonus address address public teamAddress = 0; // Development holder address address public developmentAddress = 0; // Eco system holder address address public ecoSystemAddress = 0; // Contract holder address address public contractHolderAddress = 0; uint public icoSoldTokens = 0; uint public totalSoldTokens = 0; /// Modifiers: modifier onlytokenManagerAddress() { require(msg.sender == tokenManagerAddress); _; } modifier onlyTokenCrowner() { require(msg.sender == escrowAddress); _; } modifier onlyInState(State state) { require(state == currentState); _; } /// Events: event LogBuy(address indexed owner, uint value); event LogBurn(address indexed owner, uint value); /// Functions: /// @dev Constructor /// @param _tokenManagerAddress Token manager address: 0x911AA92E796b10A2c79049FbACA219875a7fd1c9 /// @param _escrowAddress Escrow address: 0x14522Ed2EcecA9059e5EC2700C3A715CF7d5b69e /// @param _teamAddress Team address: 0xfB03a82b11E0BB61f2DFA4eDcFadd6A841eD1496 /// @param _developmentAddress Development address: 0x0814288347dA7fbA44a6ecEBD5Be2dCeDe035D91 /// @param _ecoSystemAddress Eco system address: 0x0230a2b2F79274014E7FC71aD04c22188908F69B /// @param _contractHolderAddress Contract holder address: 0x4E8eC6420e529819b5A2cD477A083E5459d7A566 function EvoNineToken(string _name, address _tokenManagerAddress, address _escrowAddress, address _teamAddress, address _developmentAddress, address _ecoSystemAddress, address _contractHolderAddress) public {<FILL_FUNCTION_BODY> } function buyTokens() public payable returns (uint256) { require(msg.value >= ((1 ether / 1 wei) / 100)); uint newTokens = msg.value * getPrice(); balances[msg.sender] += newTokens; supply += newTokens; icoSoldTokens += newTokens; totalSoldTokens += newTokens; LogBuy(msg.sender, newTokens); } function getPrice() public constant returns (uint) { if (icoSoldTokens < (4100000 * (1 ether / 1 wei))) { return ICO_PRICE1; } if (icoSoldTokens < (4300000 * (1 ether / 1 wei))) { return ICO_PRICE2; } if (icoSoldTokens < (4700000 * (1 ether / 1 wei))) { return ICO_PRICE3; } if (icoSoldTokens < (5200000 * (1 ether / 1 wei))) { return ICO_PRICE4; } if (icoSoldTokens < (6000000 * (1 ether / 1 wei))) { return ICO_PRICE5; } if (icoSoldTokens < (7000000 * (1 ether / 1 wei))) { return ICO_PRICE6; } if (icoSoldTokens < (8000000 * (1 ether / 1 wei))) { return ICO_PRICE7; } return ICO_PRICE8; } function setState(State _nextState) public onlytokenManagerAddress { //setState() method call shouldn't be entertained after ICOFinished require(currentState != State.ICOFinished); currentState = _nextState; // enable/disable transfers //enable transfers only after ICOFinished, disable otherwise //enableTransfers = (currentState==State.ICOFinished); } function DisableTransfer() public onlytokenManagerAddress { enableTransfers = false; } function EnableTransfer() public onlytokenManagerAddress { enableTransfers = true; } function withdrawEther() public onlytokenManagerAddress { if (this.balance > 0) { escrowAddress.transfer(this.balance); } } /// Overrides: function transferTo(address _to, uint256 _value) public returns (bool){ require(enableTransfers); return super.transferTo(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool){ require(enableTransfers); return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public returns (bool) { require(enableTransfers); return super.approve(_spender, _value); } // Setters/getters function ChangetokenManagerAddress(address _mgr) public onlytokenManagerAddress { tokenManagerAddress = _mgr; } // Setters/getters function ChangeCrowner(address _mgr) public onlyTokenCrowner { escrowAddress = _mgr; } }
contract EvoNineToken is StdToken { /// Fields: string public name = ""; string public symbol = "EVG"; string public website = "https://evonine.co"; uint public decimals = 18; uint public constant TOTAL_SUPPLY = 19000000 * (1 ether / 1 wei); uint public constant DEVELOPER_BONUS = 4500000 * (1 ether / 1 wei); uint public constant TEAM_BONUS = 3800000 * (1 ether / 1 wei); uint public constant ECO_SYSTEM_BONUS = 5700000 * (1 ether / 1 wei); uint public constant CONTRACT_HOLDER_BONUS = 5000000 * (1 ether / 1 wei); uint public constant ICO_PRICE1 = 2000; // per 1 Ether uint public constant ICO_PRICE2 = 1818; // per 1 Ether uint public constant ICO_PRICE3 = 1666; // per 1 Ether uint public constant ICO_PRICE4 = 1538; // per 1 Ether uint public constant ICO_PRICE5 = 1250; // per 1 Ether uint public constant ICO_PRICE6 = 1000; // per 1 Ether uint public constant ICO_PRICE7 = 800; // per 1 Ether uint public constant ICO_PRICE8 = 666; // per 1 Ether enum State{ Init, Paused, ICORunning, ICOFinished } State public currentState = State.Init; bool public enableTransfers = true; // Token manager has exclusive priveleges to call administrative // functions on this contract. address public tokenManagerAddress = 0; // Gathered funds can be withdrawn only to escrow's address. address public escrowAddress = 0; // Team bonus address address public teamAddress = 0; // Development holder address address public developmentAddress = 0; // Eco system holder address address public ecoSystemAddress = 0; // Contract holder address address public contractHolderAddress = 0; uint public icoSoldTokens = 0; uint public totalSoldTokens = 0; /// Modifiers: modifier onlytokenManagerAddress() { require(msg.sender == tokenManagerAddress); _; } modifier onlyTokenCrowner() { require(msg.sender == escrowAddress); _; } modifier onlyInState(State state) { require(state == currentState); _; } /// Events: event LogBuy(address indexed owner, uint value); event LogBurn(address indexed owner, uint value); <FILL_FUNCTION> function buyTokens() public payable returns (uint256) { require(msg.value >= ((1 ether / 1 wei) / 100)); uint newTokens = msg.value * getPrice(); balances[msg.sender] += newTokens; supply += newTokens; icoSoldTokens += newTokens; totalSoldTokens += newTokens; LogBuy(msg.sender, newTokens); } function getPrice() public constant returns (uint) { if (icoSoldTokens < (4100000 * (1 ether / 1 wei))) { return ICO_PRICE1; } if (icoSoldTokens < (4300000 * (1 ether / 1 wei))) { return ICO_PRICE2; } if (icoSoldTokens < (4700000 * (1 ether / 1 wei))) { return ICO_PRICE3; } if (icoSoldTokens < (5200000 * (1 ether / 1 wei))) { return ICO_PRICE4; } if (icoSoldTokens < (6000000 * (1 ether / 1 wei))) { return ICO_PRICE5; } if (icoSoldTokens < (7000000 * (1 ether / 1 wei))) { return ICO_PRICE6; } if (icoSoldTokens < (8000000 * (1 ether / 1 wei))) { return ICO_PRICE7; } return ICO_PRICE8; } function setState(State _nextState) public onlytokenManagerAddress { //setState() method call shouldn't be entertained after ICOFinished require(currentState != State.ICOFinished); currentState = _nextState; // enable/disable transfers //enable transfers only after ICOFinished, disable otherwise //enableTransfers = (currentState==State.ICOFinished); } function DisableTransfer() public onlytokenManagerAddress { enableTransfers = false; } function EnableTransfer() public onlytokenManagerAddress { enableTransfers = true; } function withdrawEther() public onlytokenManagerAddress { if (this.balance > 0) { escrowAddress.transfer(this.balance); } } /// Overrides: function transferTo(address _to, uint256 _value) public returns (bool){ require(enableTransfers); return super.transferTo(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool){ require(enableTransfers); return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public returns (bool) { require(enableTransfers); return super.approve(_spender, _value); } // Setters/getters function ChangetokenManagerAddress(address _mgr) public onlytokenManagerAddress { tokenManagerAddress = _mgr; } // Setters/getters function ChangeCrowner(address _mgr) public onlyTokenCrowner { escrowAddress = _mgr; } }
name = _name; tokenManagerAddress = _tokenManagerAddress; escrowAddress = _escrowAddress; teamAddress = _teamAddress; developmentAddress = _developmentAddress; ecoSystemAddress = _ecoSystemAddress; contractHolderAddress = _contractHolderAddress; balances[_contractHolderAddress] += TOTAL_SUPPLY; supply += TOTAL_SUPPLY;
function EvoNineToken(string _name, address _tokenManagerAddress, address _escrowAddress, address _teamAddress, address _developmentAddress, address _ecoSystemAddress, address _contractHolderAddress) public
/// Functions: /// @dev Constructor /// @param _tokenManagerAddress Token manager address: 0x911AA92E796b10A2c79049FbACA219875a7fd1c9 /// @param _escrowAddress Escrow address: 0x14522Ed2EcecA9059e5EC2700C3A715CF7d5b69e /// @param _teamAddress Team address: 0xfB03a82b11E0BB61f2DFA4eDcFadd6A841eD1496 /// @param _developmentAddress Development address: 0x0814288347dA7fbA44a6ecEBD5Be2dCeDe035D91 /// @param _ecoSystemAddress Eco system address: 0x0230a2b2F79274014E7FC71aD04c22188908F69B /// @param _contractHolderAddress Contract holder address: 0x4E8eC6420e529819b5A2cD477A083E5459d7A566 function EvoNineToken(string _name, address _tokenManagerAddress, address _escrowAddress, address _teamAddress, address _developmentAddress, address _ecoSystemAddress, address _contractHolderAddress) public
35626
CrisCoin
_transfer
contract CrisCoin { // Public variables of the token string public constant name = "CrisCoin"; string public constant symbol = "CSX"; uint8 public constant decimals = 18; uint256 public totalSupply; address public owner; uint256 public constant RATE = 1000; uint256 initialSupply = 100000; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); function CrisCoin() public { owner = msg.sender; totalSupply = initialSupply * 10 ** uint256(decimals); balanceOf[msg.sender] = totalSupply; } function () public payable { createTokens(); } function createTokens() public payable { require( msg.value > 0 ); require( msg.value * RATE > msg.value ); uint256 tokens = msg.value * RATE; require( balanceOf[msg.sender] + tokens > balanceOf[msg.sender] ); balanceOf[msg.sender] += tokens; require( totalSupply + tokens > totalSupply ); totalSupply += tokens; owner.transfer(msg.value); } function _transfer(address _from, address _to, uint _value) internal {<FILL_FUNCTION_BODY> } function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; totalSupply -= _value; Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; allowance[_from][msg.sender] -= _value; totalSupply -= _value; Burn(_from, _value); return true; } }
contract CrisCoin { // Public variables of the token string public constant name = "CrisCoin"; string public constant symbol = "CSX"; uint8 public constant decimals = 18; uint256 public totalSupply; address public owner; uint256 public constant RATE = 1000; uint256 initialSupply = 100000; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); function CrisCoin() public { owner = msg.sender; totalSupply = initialSupply * 10 ** uint256(decimals); balanceOf[msg.sender] = totalSupply; } function () public payable { createTokens(); } function createTokens() public payable { require( msg.value > 0 ); require( msg.value * RATE > msg.value ); uint256 tokens = msg.value * RATE; require( balanceOf[msg.sender] + tokens > balanceOf[msg.sender] ); balanceOf[msg.sender] += tokens; require( totalSupply + tokens > totalSupply ); totalSupply += tokens; owner.transfer(msg.value); } <FILL_FUNCTION> function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; totalSupply -= _value; Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; allowance[_from][msg.sender] -= _value; totalSupply -= _value; Burn(_from, _value); return true; } }
require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
function _transfer(address _from, address _to, uint _value) internal
function _transfer(address _from, address _to, uint _value) internal
74005
JoyTripToken
_approve
contract JoyTripToken is Context, IERC20 { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor(address bearer, uint256 initialSupply) public{ _name = "JoyTrip Token"; _symbol = "JOY"; _decimals = 18; _mint(bearer, 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 returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 value) public returns (bool) { _approve(_msgSender(), spender, value); return true; } function transferFrom(address sender, address recipient, uint256 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, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 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, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) private { 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); } function _approve(address owner, address spender, uint256 value) private {<FILL_FUNCTION_BODY> } }
contract JoyTripToken is Context, IERC20 { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor(address bearer, uint256 initialSupply) public{ _name = "JoyTrip Token"; _symbol = "JOY"; _decimals = 18; _mint(bearer, 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 returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 value) public returns (bool) { _approve(_msgSender(), spender, value); return true; } function transferFrom(address sender, address recipient, uint256 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, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 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, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) private { 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); } <FILL_FUNCTION> }
require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value);
function _approve(address owner, address spender, uint256 value) private
function _approve(address owner, address spender, uint256 value) private
67707
main
contract main is References, AuthorizedList, Authorized { event LogicUpgrade(address indexed _oldbiz, address indexed _newbiz); event StorageUpgrade(address indexed _oldvars, address indexed _newvars); function main(address _logic, address _storage) public Authorized() { require(_logic != address(0), "main: Unexpectedly logic address is 0x0."); require(_storage != address(0), "main: Unexpectedly storage address is 0x0."); references[bytes32(0)] = _logic; references[bytes32(1)] = _storage; } /// @dev Set an address at _key location /// @param _address Address to set /// @param _key bytes32 key location function setReference(address _address, bytes32 _key) external ifAuthorized(msg.sender, PRESIDENT) { require(_address != address(0), "setReference: Unexpectedly _address is 0x0"); if (_key == bytes32(0)) emit LogicUpgrade(references[bytes32(0)], _address); else emit StorageUpgrade(references[_key], _address); if (references[_key] != address(0)) delete references[_key]; references[_key] = _address; } /// @dev Retrieve contract address at _key location, mostly for convenience /// @return Contract address or 0x0 if it does not exist function getReference(bytes32 _key) external view ifAuthorized(msg.sender, PRESIDENT) returns(address) { return references[_key]; } function() external payable {<FILL_FUNCTION_BODY> } }
contract main is References, AuthorizedList, Authorized { event LogicUpgrade(address indexed _oldbiz, address indexed _newbiz); event StorageUpgrade(address indexed _oldvars, address indexed _newvars); function main(address _logic, address _storage) public Authorized() { require(_logic != address(0), "main: Unexpectedly logic address is 0x0."); require(_storage != address(0), "main: Unexpectedly storage address is 0x0."); references[bytes32(0)] = _logic; references[bytes32(1)] = _storage; } /// @dev Set an address at _key location /// @param _address Address to set /// @param _key bytes32 key location function setReference(address _address, bytes32 _key) external ifAuthorized(msg.sender, PRESIDENT) { require(_address != address(0), "setReference: Unexpectedly _address is 0x0"); if (_key == bytes32(0)) emit LogicUpgrade(references[bytes32(0)], _address); else emit StorageUpgrade(references[_key], _address); if (references[_key] != address(0)) delete references[_key]; references[_key] = _address; } /// @dev Retrieve contract address at _key location, mostly for convenience /// @return Contract address or 0x0 if it does not exist function getReference(bytes32 _key) external view ifAuthorized(msg.sender, PRESIDENT) returns(address) { return references[_key]; } <FILL_FUNCTION> }
address _target = references[bytes32(0)]; assembly { let _calldata := mload(0x40) mstore(0x40, add(_calldata, calldatasize)) calldatacopy(_calldata, 0x0, calldatasize) switch delegatecall(gas, _target, _calldata, calldatasize, 0, 0) case 0 { revert(0, 0) } default { let _returndata := mload(0x40) returndatacopy(_returndata, 0, returndatasize) mstore(0x40, add(_returndata, returndatasize)) return(_returndata, returndatasize) } }
function() external payable
function() external payable