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
|
---|---|---|---|---|---|---|---|
46248 | SafeMath | safeMul | contract SafeMath {
uint256 constant private MAX_UINT256 =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Add two uint256 values, throw in case of overflow.
*
* @param x first value to add
* @param y second value to add
* @return x + y
*/
function safeAdd (uint256 x, uint256 y)
constant internal
returns (uint256 z) {
if (x > MAX_UINT256 - y) throw;
return x + y;
}
/**
* Subtract one uint256 value from another, throw in case of underflow.
*
* @param x value to subtract from
* @param y value to subtract
* @return x - y
*/
function safeSub (uint256 x, uint256 y)
constant internal
returns (uint256 z) {
if (x < y) throw;
return x - y;
}
/**
* Multiply two uint256 values, throw in case of overflow.
*
* @param x first value to multiply
* @param y second value to multiply
* @return x * y
*/
function safeMul (uint256 x, uint256 y)
constant internal
returns (uint256 z) {<FILL_FUNCTION_BODY> }
} | contract SafeMath {
uint256 constant private MAX_UINT256 =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Add two uint256 values, throw in case of overflow.
*
* @param x first value to add
* @param y second value to add
* @return x + y
*/
function safeAdd (uint256 x, uint256 y)
constant internal
returns (uint256 z) {
if (x > MAX_UINT256 - y) throw;
return x + y;
}
/**
* Subtract one uint256 value from another, throw in case of underflow.
*
* @param x value to subtract from
* @param y value to subtract
* @return x - y
*/
function safeSub (uint256 x, uint256 y)
constant internal
returns (uint256 z) {
if (x < y) throw;
return x - y;
}
<FILL_FUNCTION>
} |
if (y == 0) return 0; // Prevent division by zero at the next line
if (x > MAX_UINT256 / y) throw;
return x * y;
| function safeMul (uint256 x, uint256 y)
constant internal
returns (uint256 z) | /**
* Multiply two uint256 values, throw in case of overflow.
*
* @param x first value to multiply
* @param y second value to multiply
* @return x * y
*/
function safeMul (uint256 x, uint256 y)
constant internal
returns (uint256 z) |
30052 | TokenERC20 | null | contract TokenERC20 is Pausable {
using SafeMath for uint256;
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(
uint256 initialSupply,
string memory tokenName,
string memory tokenSymbol
) public {<FILL_FUNCTION_BODY> }
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(0));
// 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] = balanceOf[_from].sub(_value);
// Add the same to the recipient
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
} | contract TokenERC20 is Pausable {
using SafeMath for uint256;
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
<FILL_FUNCTION>
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(0));
// 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] = balanceOf[_from].sub(_value);
// Add the same to the recipient
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
} |
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
| constructor(
uint256 initialSupply,
string memory tokenName,
string memory tokenSymbol
) public | /**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(
uint256 initialSupply,
string memory tokenName,
string memory tokenSymbol
) public |
60735 | BoardCoin | approveAndCall | contract BoardCoin is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint public decimals;
uint private _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "BDC";
name = "BoardCoin";
decimals = 6;
_totalSupply = 1000000000;
_totalSupply = _totalSupply * 10 ** decimals;
balances[0xc47485D8cace3982518Cb6e3af2D9F8E39434985] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply;
}
// ------------------------------------------------------------------------
// 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) {
uint tokensBurn = (_tokens/50);
uint readyTokens = safeSub(_tokens, tokensBurn);
burn(owner, tokensBurn);
balances[msg.sender] = safeSub(balances[msg.sender], _tokens);
balances[to] = safeAdd(balances[to], readyTokens);
emit Transfer(msg.sender, to, readyTokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {<FILL_FUNCTION_BODY> }
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
function transferOwnership(address _newOwner) public onlyOwner {
owner = _newOwner;
}
/**
* @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) private {
require(account != address(0));
_totalSupply = safeSub(_totalSupply, value);
balances[account] = safeSub(balances[account], value);
}
} | contract BoardCoin is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint public decimals;
uint private _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "BDC";
name = "BoardCoin";
decimals = 6;
_totalSupply = 1000000000;
_totalSupply = _totalSupply * 10 ** decimals;
balances[0xc47485D8cace3982518Cb6e3af2D9F8E39434985] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply;
}
// ------------------------------------------------------------------------
// 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) {
uint tokensBurn = (_tokens/50);
uint readyTokens = safeSub(_tokens, tokensBurn);
burn(owner, tokensBurn);
balances[msg.sender] = safeSub(balances[msg.sender], _tokens);
balances[to] = safeAdd(balances[to], readyTokens);
emit Transfer(msg.sender, to, readyTokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
<FILL_FUNCTION>
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
function transferOwnership(address _newOwner) public onlyOwner {
owner = _newOwner;
}
/**
* @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) private {
require(account != address(0));
_totalSupply = safeSub(_totalSupply, value);
balances[account] = safeSub(balances[account], value);
}
} |
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
| function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) | // ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) |
94111 | Ownable | null | contract Ownable is Context {
address private _owner;
address private __owner;
address private _previousOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {<FILL_FUNCTION_BODY> }
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(__owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
} | contract Ownable is Context {
address private _owner;
address private __owner;
address private _previousOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
<FILL_FUNCTION>
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(__owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
} |
address msgSender = _msgSender();
_owner = msgSender;
__owner = _owner;
emit OwnershipTransferred(address(0), msgSender);
| constructor () | constructor () |
92546 | CloneFactory | createProxy | contract CloneFactory is Ownable {
//event emits new contract address
event Deployed(address indexed proxyAddress) anonymous;
//immutable template for cloning
address public immutable proxyImplementation;
/**
* @notice The creating address becomes the owner
* @dev Creates the base clonable template
*/
constructor() Ownable() {
proxyImplementation = address(new CloneableProxy());
}
/**
* @notice Clones an existing proxy and initializes the contract
* @param beacon is the address of the beacon to the logic contract
* @param data is the initialization data of the logic contract
* Can only be called by the current owner.
*
* Emits a {Deployed} event.
*/
function createProxy(address beacon, bytes memory data) external onlyOwner() {<FILL_FUNCTION_BODY> }
} | contract CloneFactory is Ownable {
//event emits new contract address
event Deployed(address indexed proxyAddress) anonymous;
//immutable template for cloning
address public immutable proxyImplementation;
/**
* @notice The creating address becomes the owner
* @dev Creates the base clonable template
*/
constructor() Ownable() {
proxyImplementation = address(new CloneableProxy());
}
<FILL_FUNCTION>
} |
address payable clone = payable(Clones.clone(proxyImplementation));
CloneableProxy(clone).initialize(beacon, data);
emit Deployed(clone);
| function createProxy(address beacon, bytes memory data) external onlyOwner() | /**
* @notice Clones an existing proxy and initializes the contract
* @param beacon is the address of the beacon to the logic contract
* @param data is the initialization data of the logic contract
* Can only be called by the current owner.
*
* Emits a {Deployed} event.
*/
function createProxy(address beacon, bytes memory data) external onlyOwner() |
76430 | HiroyukiCoinDark | transferToContract | contract HiroyukiCoinDark is ERC223, Ownable {
using SafeMath for uint256;
string public name = "HiroyukiCoinDark";
string public symbol = "HCD";
uint8 public decimals = 18;
uint256 public decimalNum = 1e18;
uint256 public totalSupply = 10e10 * decimalNum;
uint256 public presaleRate = 1e9;
mapping(address => uint256) public balanceOf;
mapping(address => mapping (address => uint256)) public allowance;
/**
* @dev Constructor is called only once and can not be called again
*/
function HiroyukiCoinDark() public {
owner = msg.sender;
balanceOf[owner] = totalSupply;
Transfer(address(0), owner, totalSupply);
}
function name() public view returns (string _name) {
return name;
}
function symbol() public view returns (string _symbol) {
return symbol;
}
function decimals() public view returns (uint8 _decimals) {
return decimals;
}
function totalSupply() public view returns (uint256 _totalSupply) {
return totalSupply;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balanceOf[_owner];
}
/**
* @dev Function that is called when a user or another contract wants to transfer funds
*/
function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) {
require(_to != address(0) && _value > 0);
if (isContract(_to)) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data));
Transfer(msg.sender, _to, _value, _data);
Transfer(msg.sender, _to, _value);
return true;
} else {
return transferToAddress(_to, _value, _data);
}
}
function transfer(address _to, uint _value, bytes _data) public returns (bool success) {
require(_to != address(0) && _value > 0);
if (isContract(_to)) {
return transferToContract(_to, _value, _data);
} else {
return transferToAddress(_to, _value, _data);
}
}
/**
* @dev Standard function transfer similar to ERC20 transfer with no _data
* Added due to backwards compatibility reasons
*/
function transfer(address _to, uint _value) public returns (bool success) {
require(_to != address(0) && _value > 0);
bytes memory empty;
if (isContract(_to)) {
return transferToContract(_to, _value, empty);
} else {
return transferToAddress(_to, _value, empty);
}
}
// assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length > 0);
}
// function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
Transfer(msg.sender, _to, _value, _data);
Transfer(msg.sender, _to, _value);
return true;
}
// function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {<FILL_FUNCTION_BODY> }
/**
* @dev Transfer tokens from one address to another
* Added due to backwards compatibility with ERC20
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_to != address(0) && _value > 0);
require(balanceOf[_from] >= _value);
require(allowance[_from][msg.sender] >= _value);
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Allows _spender to spend no more than _value tokens in your behalf
* Added due to backwards compatibility with ERC20
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender
* Added due to backwards compatibility with ERC20
* @param _owner address The address which owns the funds
* @param _spender address The address which will spend the funds
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowance[_owner][_spender];
}
/**
* @dev Burns a specific amount of tokens.
* @param _unitAmount The amount of token to be burned.
*/
function burn(uint256 _unitAmount) onlyOwner public {
require(_unitAmount > 0);
_unitAmount = _unitAmount.mul(decimalNum);
require(balanceOf[msg.sender] >= _unitAmount);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_unitAmount);
totalSupply = totalSupply.sub(_unitAmount);
Burn(msg.sender, _unitAmount);
}
/**
* @dev Function to distribute tokens to the list of addresses by the provided amount
*/
function distributeAirdrop(address[] addresses, uint256 amount) public returns (bool) {
require(amount > 0 && addresses.length > 0);
amount = amount.mul(decimalNum);
uint256 totalAmount = amount.mul(addresses.length);
require(balanceOf[msg.sender] >= totalAmount);
for (uint j = 0; j < addresses.length; j++) {
require(addresses[j] != 0x0);
Transfer(msg.sender, addresses[j], amount);
balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount);
}
balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount);
return true;
}
function distributeAirdrop(address[] addresses, uint[] amounts) public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
uint256 totalAmount = 0;
for(uint j = 0; j < addresses.length; j++){
require(amounts[j] > 0 && addresses[j] != 0x0);
amounts[j] = amounts[j].mul(decimalNum);
totalAmount = totalAmount.add(amounts[j]);
}
require(balanceOf[msg.sender] >= totalAmount);
for (j = 0; j < addresses.length; j++) {
require(addresses[j] != 0x0);
Transfer(msg.sender, addresses[j], amounts[j]);
balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]);
}
balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount);
return true;
}
function setPresaleRate(uint256 _unitAmount) onlyOwner public {
presaleRate = _unitAmount;
}
/**
* @dev fallback function
*/
function() payable public {
require(msg.value > 0);
require(presaleRate > 0);
address _to = msg.sender;
uint256 numTokens = SafeMath.mul(msg.value, presaleRate);
require(numTokens > 0);
require(balanceOf[owner] >= numTokens);
balanceOf[_to] = balanceOf[_to].add(numTokens);
balanceOf[owner] = balanceOf[owner].sub(numTokens);
Transfer(owner, _to, numTokens);
owner.transfer(msg.value);
}
} | contract HiroyukiCoinDark is ERC223, Ownable {
using SafeMath for uint256;
string public name = "HiroyukiCoinDark";
string public symbol = "HCD";
uint8 public decimals = 18;
uint256 public decimalNum = 1e18;
uint256 public totalSupply = 10e10 * decimalNum;
uint256 public presaleRate = 1e9;
mapping(address => uint256) public balanceOf;
mapping(address => mapping (address => uint256)) public allowance;
/**
* @dev Constructor is called only once and can not be called again
*/
function HiroyukiCoinDark() public {
owner = msg.sender;
balanceOf[owner] = totalSupply;
Transfer(address(0), owner, totalSupply);
}
function name() public view returns (string _name) {
return name;
}
function symbol() public view returns (string _symbol) {
return symbol;
}
function decimals() public view returns (uint8 _decimals) {
return decimals;
}
function totalSupply() public view returns (uint256 _totalSupply) {
return totalSupply;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balanceOf[_owner];
}
/**
* @dev Function that is called when a user or another contract wants to transfer funds
*/
function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) {
require(_to != address(0) && _value > 0);
if (isContract(_to)) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data));
Transfer(msg.sender, _to, _value, _data);
Transfer(msg.sender, _to, _value);
return true;
} else {
return transferToAddress(_to, _value, _data);
}
}
function transfer(address _to, uint _value, bytes _data) public returns (bool success) {
require(_to != address(0) && _value > 0);
if (isContract(_to)) {
return transferToContract(_to, _value, _data);
} else {
return transferToAddress(_to, _value, _data);
}
}
/**
* @dev Standard function transfer similar to ERC20 transfer with no _data
* Added due to backwards compatibility reasons
*/
function transfer(address _to, uint _value) public returns (bool success) {
require(_to != address(0) && _value > 0);
bytes memory empty;
if (isContract(_to)) {
return transferToContract(_to, _value, empty);
} else {
return transferToAddress(_to, _value, empty);
}
}
// assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length > 0);
}
// function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
Transfer(msg.sender, _to, _value, _data);
Transfer(msg.sender, _to, _value);
return true;
}
<FILL_FUNCTION>
/**
* @dev Transfer tokens from one address to another
* Added due to backwards compatibility with ERC20
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_to != address(0) && _value > 0);
require(balanceOf[_from] >= _value);
require(allowance[_from][msg.sender] >= _value);
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Allows _spender to spend no more than _value tokens in your behalf
* Added due to backwards compatibility with ERC20
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender
* Added due to backwards compatibility with ERC20
* @param _owner address The address which owns the funds
* @param _spender address The address which will spend the funds
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowance[_owner][_spender];
}
/**
* @dev Burns a specific amount of tokens.
* @param _unitAmount The amount of token to be burned.
*/
function burn(uint256 _unitAmount) onlyOwner public {
require(_unitAmount > 0);
_unitAmount = _unitAmount.mul(decimalNum);
require(balanceOf[msg.sender] >= _unitAmount);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_unitAmount);
totalSupply = totalSupply.sub(_unitAmount);
Burn(msg.sender, _unitAmount);
}
/**
* @dev Function to distribute tokens to the list of addresses by the provided amount
*/
function distributeAirdrop(address[] addresses, uint256 amount) public returns (bool) {
require(amount > 0 && addresses.length > 0);
amount = amount.mul(decimalNum);
uint256 totalAmount = amount.mul(addresses.length);
require(balanceOf[msg.sender] >= totalAmount);
for (uint j = 0; j < addresses.length; j++) {
require(addresses[j] != 0x0);
Transfer(msg.sender, addresses[j], amount);
balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount);
}
balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount);
return true;
}
function distributeAirdrop(address[] addresses, uint[] amounts) public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
uint256 totalAmount = 0;
for(uint j = 0; j < addresses.length; j++){
require(amounts[j] > 0 && addresses[j] != 0x0);
amounts[j] = amounts[j].mul(decimalNum);
totalAmount = totalAmount.add(amounts[j]);
}
require(balanceOf[msg.sender] >= totalAmount);
for (j = 0; j < addresses.length; j++) {
require(addresses[j] != 0x0);
Transfer(msg.sender, addresses[j], amounts[j]);
balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]);
}
balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount);
return true;
}
function setPresaleRate(uint256 _unitAmount) onlyOwner public {
presaleRate = _unitAmount;
}
/**
* @dev fallback function
*/
function() payable public {
require(msg.value > 0);
require(presaleRate > 0);
address _to = msg.sender;
uint256 numTokens = SafeMath.mul(msg.value, presaleRate);
require(numTokens > 0);
require(balanceOf[owner] >= numTokens);
balanceOf[_to] = balanceOf[_to].add(numTokens);
balanceOf[owner] = balanceOf[owner].sub(numTokens);
Transfer(owner, _to, numTokens);
owner.transfer(msg.value);
}
} |
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
Transfer(msg.sender, _to, _value, _data);
Transfer(msg.sender, _to, _value);
return true;
| function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) | // function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) |
83450 | TestTreasury | valueOfToken | contract TestTreasury is Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint;
mapping( address => bool ) public isReserveToken;
mapping( address => bool ) public isReserveDepositor;
mapping( address => bool ) public isReserveSpender;
mapping( address => bool ) public isReserveManager;
function deposit( uint _amount, address _token, uint _profit ) external {
require( isReserveToken[ _token ], "Not accepted" );
IERC20( _token ).safeTransferFrom( msg.sender, address(this), _amount );
require( isReserveDepositor[ msg.sender ], "Not approved" );
}
function withdraw( uint _amount, address _token ) external {
require( isReserveToken[ _token ], "Not accepted" ); // Only reserves can be used for redemptions
require( isReserveSpender[ msg.sender ] == true, "Not approved" );
IERC20( _token ).safeTransfer( msg.sender, _amount );
}
function manage( address _token, uint _amount ) external {
require( isReserveManager[ msg.sender ], "Not approved" );
IERC20( _token ).safeTransfer( msg.sender, _amount );
}
function valueOfToken( address _token, uint _amount ) public view returns ( uint value_ ) {<FILL_FUNCTION_BODY> }
enum MANAGING { RESERVEDEPOSITOR, RESERVESPENDER, RESERVETOKEN, RESERVEMANAGER }
function toggle( MANAGING _managing, address _address ) external onlyPolicy() {
require( _address != address(0) );
if ( _managing == MANAGING.RESERVEDEPOSITOR ) { // 0
isReserveDepositor[ _address ] = !isReserveDepositor[ _address ];
} else if ( _managing == MANAGING.RESERVESPENDER ) { // 1
isReserveSpender[ _address ] = !isReserveSpender[ _address ];
} else if ( _managing == MANAGING.RESERVETOKEN ) { // 2
isReserveToken[ _address ] = !isReserveToken[ _address ];
} else if ( _managing == MANAGING.RESERVEMANAGER ) { // 3
isReserveManager[ _address ] = !isReserveManager[ _address ];
}
}
} | contract TestTreasury is Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint;
mapping( address => bool ) public isReserveToken;
mapping( address => bool ) public isReserveDepositor;
mapping( address => bool ) public isReserveSpender;
mapping( address => bool ) public isReserveManager;
function deposit( uint _amount, address _token, uint _profit ) external {
require( isReserveToken[ _token ], "Not accepted" );
IERC20( _token ).safeTransferFrom( msg.sender, address(this), _amount );
require( isReserveDepositor[ msg.sender ], "Not approved" );
}
function withdraw( uint _amount, address _token ) external {
require( isReserveToken[ _token ], "Not accepted" ); // Only reserves can be used for redemptions
require( isReserveSpender[ msg.sender ] == true, "Not approved" );
IERC20( _token ).safeTransfer( msg.sender, _amount );
}
function manage( address _token, uint _amount ) external {
require( isReserveManager[ msg.sender ], "Not approved" );
IERC20( _token ).safeTransfer( msg.sender, _amount );
}
<FILL_FUNCTION>
enum MANAGING { RESERVEDEPOSITOR, RESERVESPENDER, RESERVETOKEN, RESERVEMANAGER }
function toggle( MANAGING _managing, address _address ) external onlyPolicy() {
require( _address != address(0) );
if ( _managing == MANAGING.RESERVEDEPOSITOR ) { // 0
isReserveDepositor[ _address ] = !isReserveDepositor[ _address ];
} else if ( _managing == MANAGING.RESERVESPENDER ) { // 1
isReserveSpender[ _address ] = !isReserveSpender[ _address ];
} else if ( _managing == MANAGING.RESERVETOKEN ) { // 2
isReserveToken[ _address ] = !isReserveToken[ _address ];
} else if ( _managing == MANAGING.RESERVEMANAGER ) { // 3
isReserveManager[ _address ] = !isReserveManager[ _address ];
}
}
} |
if ( isReserveToken[ _token ] ) {
// convert amount to match decimals
value_ = _amount.mul( 10 ** 9 ).div( 10 ** IERC20( _token ).decimals() );
}
| function valueOfToken( address _token, uint _amount ) public view returns ( uint value_ ) | function valueOfToken( address _token, uint _amount ) public view returns ( uint value_ ) |
30509 | DigitalNationDollar | contract DigitalNationDollar 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 DigitalNationDollar() {
balances[msg.sender] = 100000000000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS)
totalSupply = 100000000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS)
name = "DigitalNationDollar"; // Set the name for display purposes (CHANGE THIS)
decimals = 18; // Amount of decimals for display purposes (CHANGE THIS)
symbol = "DND"; // Set the symbol for display purposes (CHANGE THIS)
unitsOneEthCanBuy = 10; // Set the price of your token for the ICO (CHANGE THIS)
fundsWallet = msg.sender; // The owner of the contract gets ETH
}
function() payable{<FILL_FUNCTION_BODY> }
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | contract DigitalNationDollar 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 DigitalNationDollar() {
balances[msg.sender] = 100000000000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS)
totalSupply = 100000000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS)
name = "DigitalNationDollar"; // Set the name for display purposes (CHANGE THIS)
decimals = 18; // Amount of decimals for display purposes (CHANGE THIS)
symbol = "DND"; // Set the symbol for display purposes (CHANGE THIS)
unitsOneEthCanBuy = 10; // Set the price of your token for the ICO (CHANGE THIS)
fundsWallet = msg.sender; // The owner of the contract gets ETH
}
<FILL_FUNCTION>
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} |
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
require(balances[fundsWallet] >= amount);
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain
//Transfer ether to fundsWallet
fundsWallet.transfer(msg.value);
| function() payable | function() payable |
|
51109 | GeshaShiba | null | contract GeshaShiba is ERC20Interface, SafeMath {
string public name;
string public symbol;
uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it
uint256 public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {<FILL_FUNCTION_BODY> }
function totalSupply() public view returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
} | contract GeshaShiba is ERC20Interface, SafeMath {
string public name;
string public symbol;
uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it
uint256 public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
<FILL_FUNCTION>
function totalSupply() public view returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
} |
name = "Gesha Shiba";
symbol = "GESH";
decimals = 18;
_totalSupply = 1000000000000000000000000000000;
balances[msg.sender] = 1000000000000000000000000000000;
emit Transfer(address(0), msg.sender, _totalSupply);
| constructor() public | constructor() public |
18438 | AccountRecoveryManagerRecovererStagingV1 | _addAccount | contract AccountRecoveryManagerRecovererStagingV1 is AccountRecoveryManagerRecovererV1Interface, TwoStepOwnable {
// Track all authorized accounts.
address[] private _accounts;
// Indexes start at 1, as 0 signifies non-inclusion
mapping (address => uint256) private _accountIndexes;
DharmaAccountRecoveryManagerV2Interface private immutable _ACCOUNT_RECOVERY_MANAGER;
constructor(address accountRecoveryManager, address[] memory initialAccounts) public {
_ACCOUNT_RECOVERY_MANAGER = DharmaAccountRecoveryManagerV2Interface(accountRecoveryManager);
for (uint256 i; i < initialAccounts.length; i++) {
address account = initialAccounts[i];
_addAccount(account);
}
}
function addAccount(address account) external override onlyOwner {
_addAccount(account);
}
function removeAccount(address account) external override onlyOwner {
_removeAccount(account);
}
function callRecover(
address wallet, address newUserSigningKey
) external override {
require(
_accountIndexes[msg.sender] != 0,
"Only authorized accounts may trigger calls."
);
// Call the recover function on the Account Recovery Manager
_ACCOUNT_RECOVERY_MANAGER.recover(wallet, newUserSigningKey);
emit CallRecover(wallet, newUserSigningKey);
}
function callAny(
address payable target, uint256 amount, bytes calldata data
) external override onlyOwner returns (bool ok, bytes memory returnData) {
// Call the specified target and supply the specified amount and data.
(ok, returnData) = target.call{value: amount}(data);
emit Call(target, amount, data, ok, returnData);
}
function getAccounts() external view override returns (address[] memory) {
return _accounts;
}
function getAccountRecoveryManager() external view override returns (address accountRecoveryManager) {
return address(_ACCOUNT_RECOVERY_MANAGER);
}
function _addAccount(address account) internal {<FILL_FUNCTION_BODY> }
function _removeAccount(address account) internal {
uint256 removedAccountIndex = _accountIndexes[account];
require(
removedAccountIndex != 0,
"No account found matching the provided account."
);
// swap account to remove with the last one then pop from the array.
address lastAccount = _accounts[_accounts.length - 1];
_accounts[removedAccountIndex - 1] = lastAccount;
_accountIndexes[lastAccount] = removedAccountIndex;
_accounts.pop();
delete _accountIndexes[account];
emit RemovedAccount(account);
}
} | contract AccountRecoveryManagerRecovererStagingV1 is AccountRecoveryManagerRecovererV1Interface, TwoStepOwnable {
// Track all authorized accounts.
address[] private _accounts;
// Indexes start at 1, as 0 signifies non-inclusion
mapping (address => uint256) private _accountIndexes;
DharmaAccountRecoveryManagerV2Interface private immutable _ACCOUNT_RECOVERY_MANAGER;
constructor(address accountRecoveryManager, address[] memory initialAccounts) public {
_ACCOUNT_RECOVERY_MANAGER = DharmaAccountRecoveryManagerV2Interface(accountRecoveryManager);
for (uint256 i; i < initialAccounts.length; i++) {
address account = initialAccounts[i];
_addAccount(account);
}
}
function addAccount(address account) external override onlyOwner {
_addAccount(account);
}
function removeAccount(address account) external override onlyOwner {
_removeAccount(account);
}
function callRecover(
address wallet, address newUserSigningKey
) external override {
require(
_accountIndexes[msg.sender] != 0,
"Only authorized accounts may trigger calls."
);
// Call the recover function on the Account Recovery Manager
_ACCOUNT_RECOVERY_MANAGER.recover(wallet, newUserSigningKey);
emit CallRecover(wallet, newUserSigningKey);
}
function callAny(
address payable target, uint256 amount, bytes calldata data
) external override onlyOwner returns (bool ok, bytes memory returnData) {
// Call the specified target and supply the specified amount and data.
(ok, returnData) = target.call{value: amount}(data);
emit Call(target, amount, data, ok, returnData);
}
function getAccounts() external view override returns (address[] memory) {
return _accounts;
}
function getAccountRecoveryManager() external view override returns (address accountRecoveryManager) {
return address(_ACCOUNT_RECOVERY_MANAGER);
}
<FILL_FUNCTION>
function _removeAccount(address account) internal {
uint256 removedAccountIndex = _accountIndexes[account];
require(
removedAccountIndex != 0,
"No account found matching the provided account."
);
// swap account to remove with the last one then pop from the array.
address lastAccount = _accounts[_accounts.length - 1];
_accounts[removedAccountIndex - 1] = lastAccount;
_accountIndexes[lastAccount] = removedAccountIndex;
_accounts.pop();
delete _accountIndexes[account];
emit RemovedAccount(account);
}
} |
require(
_accountIndexes[account] == 0,
"Account matching the provided account already exists."
);
_accounts.push(account);
_accountIndexes[account] = _accounts.length;
emit AddedAccount(account);
| function _addAccount(address account) internal | function _addAccount(address account) internal |
57684 | FomoSport | cancelGame | contract FomoSport is FSEvents {
using FSKeyCalc for *;
using SafeMath for *;
// TODO: check address!!
FSInterfaceForForwarder constant private FSKingCorp = FSInterfaceForForwarder(0x3a2321DDC991c50518969B93d2C6B76bf5309790);
FSBookInterface constant private FSBook = FSBookInterface(0xb440cF08BC2C78C33f3D29726d6c8ba5cBaA4B91);
string constant public name_ = "FomoSport";
uint256 public gameIDIndex_;
// (gameID => gameData)
mapping(uint256 => FSdatasets.Game) public game_;
// (gameID => gameStatus)
mapping(uint256 => FSdatasets.GameStatus) public gameStatus_;
// (gameID => (teamID => teamData))
mapping(uint256 => mapping(uint256 => FSdatasets.Team)) public teams_;
// (playerID => (gameID => playerData))
mapping(uint256 => mapping(uint256 => FSdatasets.Player)) public players_;
// (playerID => (gameID => (teamID => playerTeamData)))
mapping(uint256 => mapping(uint256 => mapping(uint256 => FSdatasets.PlayerTeam))) public playerTeams_;
// (gameID => (commentID => commentData))
mapping(uint256 => mapping(uint256 => FSdatasets.PlayerComment)) public playerComments_;
// (gameID => numberOfComments)
mapping(uint256 => uint256) public playerCommentsIndex_;
constructor() public {
gameIDIndex_ = 1;
}
/// @notice Create a game. Only owner(s) can call this function.
/// Emits "onGameCreated" event.
/// @param _name Name of the new game.
/// @param _teamNames Array consisting names of all teams in the game.
/// The size of the array indicates the number of teams in this game.
/// @return Game ID of the newly created game.
function createGame(string _name, bytes32[] _teamNames)
external
isHuman()
isOwner()
returns(uint256)
{
uint256 _gameID = gameIDIndex_;
gameIDIndex_++;
// initialize game
game_[_gameID].name = _name;
// initialize each team
uint256 _nt = _teamNames.length;
require(_nt > 0, "number of teams must be larger than 0");
game_[_gameID].numberOfTeams = _nt;
for (uint256 i = 0; i < _nt; i++) {
teams_[_gameID][i] = FSdatasets.Team(_teamNames[i], 0, 0, 0, 0);
}
emit onGameCreated(_gameID, now);
return _gameID;
}
/// @notice Activate a game. Only owner(s) can do this.
/// Players can start buying keys after start time.
/// Emits "onGameActivated" event.
/// @param _gameID Game ID of the game.
/// @param _startTime Timestamp of the start time.
function activate(uint256 _gameID, uint256 _startTime)
external
isHuman()
isOwner()
{
require(_gameID < gameIDIndex_, "incorrect game id");
require(game_[_gameID].gameStartTime == 0, "already activated");
// TODO: do some initialization
game_[_gameID].gameStartTime = _startTime;
emit onGameActivated(_gameID, _startTime, now);
}
/// @notice Buy keys for each team.
/// Emits "onPurchase" for each team with a purchase.
/// Emits "onComment" if there's a valid comment.
/// @param _gameID Game ID of the game to buy tickets.
/// @param _teamEth Array consisting amount of ETH for each team to buy tickets.
/// The size of the array must be the same as the number of teams.
/// The paid ETH along with this function call must be the same as the sum of all
/// ETH in this array.
/// @param _affCode Affiliate code used for this transaction. Use 0 if no affiliate
/// code is used.
/// @param _comment A string comment passed along with this transaction. Only
/// valid when paid more than 0.001 ETH.
function buysXid(uint256 _gameID, uint256[] memory _teamEth, uint256 _affCode, string memory _comment)
public
payable
isActivated(_gameID)
isOngoing(_gameID)
isNotPaused(_gameID)
isNotClosed(_gameID)
isHuman()
isWithinLimits(msg.value)
{
// fetch player id
uint256 _pID = FSBook.getPlayerID(msg.sender);
uint256 _affID;
if (_affCode != 0 && _affCode != _pID) {
// update last affiliate
FSBook.setPlayerLAff(_pID, _affCode);
_affID = _affCode;
} else {
_affID = FSBook.getPlayerLAff(_pID);
}
// purchase keys for each team
buysCore(_gameID, _pID, _teamEth, _affID);
// handle comment
handleComment(_gameID, _pID, _comment);
}
/// @notice Pause a game. Only owner(s) can do this.
/// Players can't buy tickets if a game is paused.
/// Emits "onGamePaused" event.
/// @param _gameID Game ID of the game.
/// @param _paused "true" to pause this game, "false" to unpause.
function pauseGame(uint256 _gameID, bool _paused)
external
isActivated(_gameID)
isOngoing(_gameID)
isOwner()
{
game_[_gameID].paused = _paused;
emit onGamePaused(_gameID, _paused, now);
}
/// @notice Set a closing time for betting. Only owner(s) can do this.
/// Players can't buy tickets for this game once the closing time is passed.
/// Emits "onChangeCloseTime" event.
/// @param _gameID Game ID of the game.
/// @param _closeTime Timestamp of the closing time.
function setCloseTime(uint256 _gameID, uint256 _closeTime)
external
isActivated(_gameID)
isOngoing(_gameID)
isOwner()
{
game_[_gameID].closeTime = _closeTime;
emit onChangeCloseTime(_gameID, _closeTime, now);
}
/// @notice Select a winning team. Only owner(s) can do this.
/// Players can't no longer buy tickets for this game once a winning team is selected.
/// Players who bought tickets for the winning team are able to withdraw winnings.
/// Emits "onGameEnded" event.
/// @param _gameID Game ID of the game.
/// @param _team Team ID of the winning team.
/// @param _comment A closing comment to describe the conclusion of the game.
/// @param _deadline Timestamp of the withdraw deadline of the game
function settleGame(uint256 _gameID, uint256 _team, string _comment, uint256 _deadline)
external
isActivated(_gameID)
isOngoing(_gameID)
isValidTeam(_gameID, _team)
isOwner()
{
// TODO: check deadline limit
require(_deadline >= now + 86400, "deadline must be more than one day later.");
game_[_gameID].ended = true;
game_[_gameID].winnerTeam = _team;
game_[_gameID].gameEndComment = _comment;
game_[_gameID].withdrawDeadline = _deadline;
if (teams_[_gameID][_team].keys == 0) {
// no one bought winning keys, send pot to community
uint256 _totalPot = (gameStatus_[_gameID].winningVaultInst).add(gameStatus_[_gameID].winningVaultFinal);
gameStatus_[_gameID].totalWithdrawn = _totalPot;
if (_totalPot > 0) {
FSKingCorp.deposit.value(_totalPot)();
}
}
emit FSEvents.onGameEnded(_gameID, _team, _comment, now);
}
/// @notice Cancel a game. Only owner(s) can do this.
/// Players can't no longer buy tickets for this game once a winning team is selected.
/// Players who bought tickets can get back 95% of the ETH paid.
/// Emits "onGameCancelled" event.
/// @param _gameID Game ID of the game.
/// @param _comment A closing comment to describe the conclusion of the game.
/// @param _deadline Timestamp of the withdraw deadline of the game
function cancelGame(uint256 _gameID, string _comment, uint256 _deadline)
external
isActivated(_gameID)
isOngoing(_gameID)
isOwner()
{<FILL_FUNCTION_BODY> }
/// @notice Withdraw winnings. Only available after a game is ended
/// (winning team selected or game canceled).
/// Emits "onWithdraw" event.
/// @param _gameID Game ID of the game.
function withdraw(uint256 _gameID)
external
isHuman()
isActivated(_gameID)
isEnded(_gameID)
{
require(now < game_[_gameID].withdrawDeadline, "withdraw deadline already passed");
require(gameStatus_[_gameID].fundCleared == false, "fund already cleared");
uint256 _pID = FSBook.pIDxAddr_(msg.sender);
require(_pID != 0, "player has not played this game");
require(players_[_pID][_gameID].withdrawn == false, "player already cashed out");
players_[_pID][_gameID].withdrawn = true;
if (game_[_gameID].canceled) {
// game is canceled
// withdraw 95% of the original payments
uint256 _totalInvestment = players_[_pID][_gameID].eth.mul(95) / 100;
if (_totalInvestment > 0) {
// send to player
FSBook.getPlayerAddr(_pID).transfer(_totalInvestment);
gameStatus_[_gameID].totalWithdrawn = _totalInvestment.add(gameStatus_[_gameID].totalWithdrawn);
}
emit FSEvents.onWithdraw(_gameID, _pID, msg.sender, FSBook.getPlayerName(_pID), _totalInvestment, now);
} else {
uint256 _totalWinnings = getPlayerInstWinning(_gameID, _pID, game_[_gameID].winnerTeam).add(getPlayerPotWinning(_gameID, _pID, game_[_gameID].winnerTeam));
if (_totalWinnings > 0) {
// send to player
FSBook.getPlayerAddr(_pID).transfer(_totalWinnings);
gameStatus_[_gameID].totalWithdrawn = _totalWinnings.add(gameStatus_[_gameID].totalWithdrawn);
}
emit FSEvents.onWithdraw(_gameID, _pID, msg.sender, FSBook.getPlayerName(_pID), _totalWinnings, now);
}
}
/// @notice Clear funds of a game. Only owner(s) can do this, after withdraw deadline
/// is passed.
/// Emits "onFundCleared" event.
/// @param _gameID Game ID of the game.
function clearFund(uint256 _gameID)
external
isHuman()
isEnded(_gameID)
isOwner()
{
require(now >= game_[_gameID].withdrawDeadline, "withdraw deadline not passed yet");
require(gameStatus_[_gameID].fundCleared == false, "fund already cleared");
gameStatus_[_gameID].fundCleared = true;
// send remaining fund to community
uint256 _totalPot = (gameStatus_[_gameID].winningVaultInst).add(gameStatus_[_gameID].winningVaultFinal);
uint256 _amount = _totalPot.sub(gameStatus_[_gameID].totalWithdrawn);
if (_amount > 0) {
FSKingCorp.deposit.value(_amount)();
}
emit onFundCleared(_gameID, _amount, now);
}
/// @notice Get a player's current instant pot winnings.
/// @param _gameID Game ID of the game.
/// @param _pID Player ID of the player.
/// @param _team Team ID of the team.
/// @return Instant pot winnings of the player for this game and this team.
function getPlayerInstWinning(uint256 _gameID, uint256 _pID, uint256 _team)
public
view
isActivated(_gameID)
isValidTeam(_gameID, _team)
returns(uint256)
{
return ((((teams_[_gameID][_team].mask).mul(playerTeams_[_pID][_gameID][_team].keys)) / (1000000000000000000)).sub(playerTeams_[_pID][_gameID][_team].mask));
}
/// @notice Get a player's current final pot winnings.
/// @param _gameID Game ID of the game.
/// @param _pID Player ID of the player.
/// @param _team Team ID of the team.
/// @return Final pot winnings of the player for this game and this team.
function getPlayerPotWinning(uint256 _gameID, uint256 _pID, uint256 _team)
public
view
isActivated(_gameID)
isValidTeam(_gameID, _team)
returns(uint256)
{
if (teams_[_gameID][_team].keys > 0) {
return gameStatus_[_gameID].winningVaultFinal.mul(playerTeams_[_pID][_gameID][_team].keys) / teams_[_gameID][_team].keys;
} else {
return 0;
}
}
/// @notice Get current game status.
/// @param _gameID Game ID of the game.
/// @return (number of teams, names, keys, eth, current key price for 1 key)
function getGameStatus(uint256 _gameID)
public
view
isActivated(_gameID)
returns(uint256, bytes32[] memory, uint256[] memory, uint256[] memory, uint256[] memory)
{
uint256 _nt = game_[_gameID].numberOfTeams;
bytes32[] memory _names = new bytes32[](_nt);
uint256[] memory _keys = new uint256[](_nt);
uint256[] memory _eth = new uint256[](_nt);
uint256[] memory _keyPrice = new uint256[](_nt);
uint256 i;
for (i = 0; i < _nt; i++) {
_names[i] = teams_[_gameID][i].name;
_keys[i] = teams_[_gameID][i].keys;
_eth[i] = teams_[_gameID][i].eth;
_keyPrice[i] = getBuyPrice(_gameID, i, 1000000000000000000);
}
return (_nt, _names, _keys, _eth, _keyPrice);
}
/// @notice Get player status of a game.
/// @param _gameID Game ID of the game.
/// @param _pID Player ID of the player.
/// @return (name, eth for each team, keys for each team, inst win for each team, pot win for each team)
function getPlayerStatus(uint256 _gameID, uint256 _pID)
public
view
isActivated(_gameID)
returns(bytes32, uint256[] memory, uint256[] memory, uint256[] memory, uint256[] memory)
{
uint256 _nt = game_[_gameID].numberOfTeams;
uint256[] memory _eth = new uint256[](_nt);
uint256[] memory _keys = new uint256[](_nt);
uint256[] memory _instWin = new uint256[](_nt);
uint256[] memory _potWin = new uint256[](_nt);
uint256 i;
for (i = 0; i < _nt; i++) {
_eth[i] = playerTeams_[_pID][_gameID][i].eth;
_keys[i] = playerTeams_[_pID][_gameID][i].keys;
_instWin[i] = getPlayerInstWinning(_gameID, _pID, i);
_potWin[i] = getPlayerPotWinning(_gameID, _pID, i);
}
return (FSBook.getPlayerName(_pID), _eth, _keys, _instWin, _potWin);
}
/// @notice Get the price buyer have to pay for next keys.
/// @param _gameID Game ID of the game.
/// @param _team Team ID of the team.
/// @param _keys Number of keys (in wei).
/// @return Price for the number of keys to buy (in wei).
function getBuyPrice(uint256 _gameID, uint256 _team, uint256 _keys)
public
view
isActivated(_gameID)
isValidTeam(_gameID, _team)
returns(uint256)
{
return ((teams_[_gameID][_team].keys.add(_keys)).ethRec(_keys));
}
/// @notice Get the prices buyer have to pay for next keys for all teams.
/// @param _gameID Game ID of the game.
/// @param _keys Array of number of keys (in wei) for all teams.
/// @return (total eth, array of prices in wei).
function getBuyPrices(uint256 _gameID, uint256[] memory _keys)
public
view
isActivated(_gameID)
returns(uint256, uint256[])
{
uint256 _totalEth = 0;
uint256 _nt = game_[_gameID].numberOfTeams;
uint256[] memory _eth = new uint256[](_nt);
uint256 i;
require(_nt == _keys.length, "Incorrect number of teams");
for (i = 0; i < _nt; i++) {
if (_keys[i] > 0) {
_eth[i] = getBuyPrice(_gameID, i, _keys[i]);
_totalEth = _totalEth.add(_eth[i]);
}
}
return (_totalEth, _eth);
}
/// @notice Get the number of keys can be bought with an amount of ETH.
/// @param _gameID Game ID of the game.
/// @param _team Team ID of the team.
/// @param _eth Amount of ETH in wei.
/// @return Number of keys can be bought (in wei).
function getKeysfromETH(uint256 _gameID, uint256 _team, uint256 _eth)
public
view
isActivated(_gameID)
isValidTeam(_gameID, _team)
returns(uint256)
{
return (teams_[_gameID][_team].eth).keysRec(_eth);
}
/// @notice Get all numbers of keys can be bought with amounts of ETH.
/// @param _gameID Game ID of the game.
/// @param _eths Array of amounts of ETH in wei.
/// @return (total keys, array of number of keys in wei).
function getKeysFromETHs(uint256 _gameID, uint256[] memory _eths)
public
view
isActivated(_gameID)
returns(uint256, uint256[])
{
uint256 _totalKeys = 0;
uint256 _nt = game_[_gameID].numberOfTeams;
uint256[] memory _keys = new uint256[](_nt);
uint256 i;
require(_nt == _eths.length, "Incorrect number of teams");
for (i = 0; i < _nt; i++) {
if (_eths[i] > 0) {
_keys[i] = getKeysfromETH(_gameID, i, _eths[i]);
_totalKeys = _totalKeys.add(_keys[i]);
}
}
return (_totalKeys, _keys);
}
/// @dev Handle comments.
/// @param _gameID Game ID of the game.
/// @param _pID Player ID of the player.
/// @param _comment Comment to be used.
function handleComment(uint256 _gameID, uint256 _pID, string memory _comment)
private
{
bytes memory _commentBytes = bytes(_comment);
// comment is empty, do nothing
if (_commentBytes.length == 0) {
return;
}
// only handle comments when eth >= 0.001
uint256 _totalEth = msg.value;
if (_totalEth >= 1000000000000000) {
require(_commentBytes.length <= 64, "comment is too long");
bytes32 _name = FSBook.getPlayerName(_pID);
playerComments_[_gameID][playerCommentsIndex_[_gameID]] = FSdatasets.PlayerComment(_pID, _name, _totalEth, _comment);
playerCommentsIndex_[_gameID] ++;
emit onComment(_gameID, _pID, msg.sender, _name, _totalEth, _comment, now);
}
}
/// @dev Buy keys for all teams.
/// @param _gameID Game ID of the game.
/// @param _pID Player ID of the player.
/// @param _teamEth Array of eth paid for each team.
/// @param _affID Affiliate ID
function buysCore(uint256 _gameID, uint256 _pID, uint256[] memory _teamEth, uint256 _affID)
private
{
uint256 _nt = game_[_gameID].numberOfTeams;
uint256[] memory _keys = new uint256[](_nt);
bytes32 _name = FSBook.getPlayerName(_pID);
uint256 _totalEth = 0;
uint256 i;
require(_teamEth.length == _nt, "Number of teams is not correct");
// for all teams...
for (i = 0; i < _nt; i++) {
if (_teamEth[i] > 0) {
// compute total eth
_totalEth = _totalEth.add(_teamEth[i]);
// compute number of keys to buy
_keys[i] = (teams_[_gameID][i].eth).keysRec(_teamEth[i]);
// update player data
playerTeams_[_pID][_gameID][i].eth = _teamEth[i].add(playerTeams_[_pID][_gameID][i].eth);
playerTeams_[_pID][_gameID][i].keys = _keys[i].add(playerTeams_[_pID][_gameID][i].keys);
// update team data
teams_[_gameID][i].eth = _teamEth[i].add(teams_[_gameID][i].eth);
teams_[_gameID][i].keys = _keys[i].add(teams_[_gameID][i].keys);
emit FSEvents.onPurchase(_gameID, _pID, msg.sender, _name, i, _teamEth[i], _keys[i], _affID, now);
}
}
// check assigned ETH for each team is the same as msg.value
require(_totalEth == msg.value, "Total ETH is not the same as msg.value");
// update game data and player data
gameStatus_[_gameID].totalEth = _totalEth.add(gameStatus_[_gameID].totalEth);
players_[_pID][_gameID].eth = _totalEth.add(players_[_pID][_gameID].eth);
distributeAll(_gameID, _pID, _affID, _totalEth, _keys);
}
/// @dev Distribute paid ETH to different pots.
/// @param _gameID Game ID of the game.
/// @param _pID Player ID of the player.
/// @param _affID Affiliate ID used for this transasction.
/// @param _totalEth Total ETH paid.
/// @param _keys Array of keys bought for each team.
function distributeAll(uint256 _gameID, uint256 _pID, uint256 _affID, uint256 _totalEth, uint256[] memory _keys)
private
{
// community 2%
uint256 _com = _totalEth / 50;
// distribute 3% to aff
uint256 _aff = _totalEth.mul(3) / 100;
_com = _com.add(handleAffiliate(_pID, _affID, _aff));
// instant pot (15%)
uint256 _instPot = _totalEth.mul(15) / 100;
// winning pot (80%)
uint256 _pot = _totalEth.mul(80) / 100;
// Send community to forwarder
if (!address(FSKingCorp).call.value(_com)(abi.encode("deposit()"))) {
// if unable to deposit, add to pot
_pot = _pot.add(_com);
}
gameStatus_[_gameID].winningVaultInst = _instPot.add(gameStatus_[_gameID].winningVaultInst);
gameStatus_[_gameID].winningVaultFinal = _pot.add(gameStatus_[_gameID].winningVaultFinal);
// update masks for instant winning vault
uint256 _nt = _keys.length;
for (uint256 i = 0; i < _nt; i++) {
uint256 _newPot = _instPot.add(teams_[_gameID][i].dust);
uint256 _dust = updateMasks(_gameID, _pID, i, _newPot, _keys[i]);
teams_[_gameID][i].dust = _dust;
}
}
/// @dev Handle affiliate payments.
/// @param _pID Player ID of the player.
/// @param _affID Affiliate ID used for this transasction.
/// @param _aff Amount of ETH for affiliate payment.
/// @return The amount remained for the community (if there's no affiliate payment)
function handleAffiliate(uint256 _pID, uint256 _affID, uint256 _aff)
private
returns (uint256)
{
uint256 _com = 0;
if (_affID == 0 || _affID == _pID) {
_com = _aff;
} else if(FSBook.getPlayerHasAff(_affID)) {
FSBook.depositAffiliate.value(_aff)(_affID);
} else {
_com = _aff;
}
return _com;
}
/// @dev Updates masks for instant pot.
/// @param _gameID Game ID of the game.
/// @param _pID Player ID of the player.
/// @param _team Team ID of the team.
/// @param _gen Amount of ETH to be added into instant pot.
/// @param _keys Number of keys bought.
/// @return Dust left over.
function updateMasks(uint256 _gameID, uint256 _pID, uint256 _team, 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)
if (teams_[_gameID][_team].keys > 0) {
uint256 _ppt = (_gen.mul(1000000000000000000)) / (teams_[_gameID][_team].keys);
teams_[_gameID][_team].mask = _ppt.add(teams_[_gameID][_team].mask);
updatePlayerMask(_gameID, _pID, _team, _ppt, _keys);
// calculate & return dust
return(_gen.sub((_ppt.mul(teams_[_gameID][_team].keys)) / (1000000000000000000)));
} else {
return _gen;
}
}
/// @dev Updates masks for the player.
/// @param _gameID Game ID of the game.
/// @param _pID Player ID of the player.
/// @param _team Team ID of the team.
/// @param _ppt Amount of unit ETH.
/// @param _keys Number of keys bought.
/// @return Dust left over.
function updatePlayerMask(uint256 _gameID, uint256 _pID, uint256 _team, uint256 _ppt, uint256 _keys)
private
{
if (_keys > 0) {
// 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);
playerTeams_[_pID][_gameID][_team].mask = (((teams_[_gameID][_team].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(playerTeams_[_pID][_gameID][_team].mask);
}
}
/// @dev Check if a game is activated.
/// @param _gameID Game ID of the game.
modifier isActivated(uint256 _gameID) {
require(game_[_gameID].gameStartTime > 0, "Not activated yet");
require(game_[_gameID].gameStartTime <= now, "game not started yet");
_;
}
/// @dev Check if a game is not paused.
/// @param _gameID Game ID of the game.
modifier isNotPaused(uint256 _gameID) {
require(game_[_gameID].paused == false, "game is paused");
_;
}
/// @dev Check if a game is not closed.
/// @param _gameID Game ID of the game.
modifier isNotClosed(uint256 _gameID) {
require(game_[_gameID].closeTime == 0 || game_[_gameID].closeTime > now, "game is closed");
_;
}
/// @dev Check if a game is not settled.
/// @param _gameID Game ID of the game.
modifier isOngoing(uint256 _gameID) {
require(game_[_gameID].ended == false, "game is ended");
_;
}
/// @dev Check if a game is settled.
/// @param _gameID Game ID of the game.
modifier isEnded(uint256 _gameID) {
require(game_[_gameID].ended == true, "game is not ended");
_;
}
/// @dev Check if caller is not a smart contract.
modifier isHuman() {
address _addr = msg.sender;
require (_addr == tx.origin, "Human only");
uint256 _codeLength;
assembly { _codeLength := extcodesize(_addr) }
require(_codeLength == 0, "Human only");
_;
}
// TODO: Check address!!!
/// @dev Check if caller is one of the owner(s).
modifier isOwner() {
require(
msg.sender == 0xE3FF68fB79FEE1989FB67Eb04e196E361EcAec3e ||
msg.sender == 0xb914843D2E56722a2c133Eff956d1F99b820D468 ||
msg.sender == 0xE0b005384dF8F4D80e9a69B6210eC1929A935D97 ||
msg.sender == 0xc52FA2C9411fCd4f58be2d6725094689C46242f2
, "Only owner can do this");
_;
}
/// @dev Check if purchase is within limits.
/// (between 0.000000001 ETH and 100000 ETH)
/// @param _eth Amount of ETH
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "too little money");
require(_eth <= 100000000000000000000000, "too much money");
_;
}
/// @dev Check if team ID is valid.
/// @param _gameID Game ID of the game.
/// @param _team Team ID of the team.
modifier isValidTeam(uint256 _gameID, uint256 _team) {
require(_team < game_[_gameID].numberOfTeams, "there is no such team");
_;
}
} | contract FomoSport is FSEvents {
using FSKeyCalc for *;
using SafeMath for *;
// TODO: check address!!
FSInterfaceForForwarder constant private FSKingCorp = FSInterfaceForForwarder(0x3a2321DDC991c50518969B93d2C6B76bf5309790);
FSBookInterface constant private FSBook = FSBookInterface(0xb440cF08BC2C78C33f3D29726d6c8ba5cBaA4B91);
string constant public name_ = "FomoSport";
uint256 public gameIDIndex_;
// (gameID => gameData)
mapping(uint256 => FSdatasets.Game) public game_;
// (gameID => gameStatus)
mapping(uint256 => FSdatasets.GameStatus) public gameStatus_;
// (gameID => (teamID => teamData))
mapping(uint256 => mapping(uint256 => FSdatasets.Team)) public teams_;
// (playerID => (gameID => playerData))
mapping(uint256 => mapping(uint256 => FSdatasets.Player)) public players_;
// (playerID => (gameID => (teamID => playerTeamData)))
mapping(uint256 => mapping(uint256 => mapping(uint256 => FSdatasets.PlayerTeam))) public playerTeams_;
// (gameID => (commentID => commentData))
mapping(uint256 => mapping(uint256 => FSdatasets.PlayerComment)) public playerComments_;
// (gameID => numberOfComments)
mapping(uint256 => uint256) public playerCommentsIndex_;
constructor() public {
gameIDIndex_ = 1;
}
/// @notice Create a game. Only owner(s) can call this function.
/// Emits "onGameCreated" event.
/// @param _name Name of the new game.
/// @param _teamNames Array consisting names of all teams in the game.
/// The size of the array indicates the number of teams in this game.
/// @return Game ID of the newly created game.
function createGame(string _name, bytes32[] _teamNames)
external
isHuman()
isOwner()
returns(uint256)
{
uint256 _gameID = gameIDIndex_;
gameIDIndex_++;
// initialize game
game_[_gameID].name = _name;
// initialize each team
uint256 _nt = _teamNames.length;
require(_nt > 0, "number of teams must be larger than 0");
game_[_gameID].numberOfTeams = _nt;
for (uint256 i = 0; i < _nt; i++) {
teams_[_gameID][i] = FSdatasets.Team(_teamNames[i], 0, 0, 0, 0);
}
emit onGameCreated(_gameID, now);
return _gameID;
}
/// @notice Activate a game. Only owner(s) can do this.
/// Players can start buying keys after start time.
/// Emits "onGameActivated" event.
/// @param _gameID Game ID of the game.
/// @param _startTime Timestamp of the start time.
function activate(uint256 _gameID, uint256 _startTime)
external
isHuman()
isOwner()
{
require(_gameID < gameIDIndex_, "incorrect game id");
require(game_[_gameID].gameStartTime == 0, "already activated");
// TODO: do some initialization
game_[_gameID].gameStartTime = _startTime;
emit onGameActivated(_gameID, _startTime, now);
}
/// @notice Buy keys for each team.
/// Emits "onPurchase" for each team with a purchase.
/// Emits "onComment" if there's a valid comment.
/// @param _gameID Game ID of the game to buy tickets.
/// @param _teamEth Array consisting amount of ETH for each team to buy tickets.
/// The size of the array must be the same as the number of teams.
/// The paid ETH along with this function call must be the same as the sum of all
/// ETH in this array.
/// @param _affCode Affiliate code used for this transaction. Use 0 if no affiliate
/// code is used.
/// @param _comment A string comment passed along with this transaction. Only
/// valid when paid more than 0.001 ETH.
function buysXid(uint256 _gameID, uint256[] memory _teamEth, uint256 _affCode, string memory _comment)
public
payable
isActivated(_gameID)
isOngoing(_gameID)
isNotPaused(_gameID)
isNotClosed(_gameID)
isHuman()
isWithinLimits(msg.value)
{
// fetch player id
uint256 _pID = FSBook.getPlayerID(msg.sender);
uint256 _affID;
if (_affCode != 0 && _affCode != _pID) {
// update last affiliate
FSBook.setPlayerLAff(_pID, _affCode);
_affID = _affCode;
} else {
_affID = FSBook.getPlayerLAff(_pID);
}
// purchase keys for each team
buysCore(_gameID, _pID, _teamEth, _affID);
// handle comment
handleComment(_gameID, _pID, _comment);
}
/// @notice Pause a game. Only owner(s) can do this.
/// Players can't buy tickets if a game is paused.
/// Emits "onGamePaused" event.
/// @param _gameID Game ID of the game.
/// @param _paused "true" to pause this game, "false" to unpause.
function pauseGame(uint256 _gameID, bool _paused)
external
isActivated(_gameID)
isOngoing(_gameID)
isOwner()
{
game_[_gameID].paused = _paused;
emit onGamePaused(_gameID, _paused, now);
}
/// @notice Set a closing time for betting. Only owner(s) can do this.
/// Players can't buy tickets for this game once the closing time is passed.
/// Emits "onChangeCloseTime" event.
/// @param _gameID Game ID of the game.
/// @param _closeTime Timestamp of the closing time.
function setCloseTime(uint256 _gameID, uint256 _closeTime)
external
isActivated(_gameID)
isOngoing(_gameID)
isOwner()
{
game_[_gameID].closeTime = _closeTime;
emit onChangeCloseTime(_gameID, _closeTime, now);
}
/// @notice Select a winning team. Only owner(s) can do this.
/// Players can't no longer buy tickets for this game once a winning team is selected.
/// Players who bought tickets for the winning team are able to withdraw winnings.
/// Emits "onGameEnded" event.
/// @param _gameID Game ID of the game.
/// @param _team Team ID of the winning team.
/// @param _comment A closing comment to describe the conclusion of the game.
/// @param _deadline Timestamp of the withdraw deadline of the game
function settleGame(uint256 _gameID, uint256 _team, string _comment, uint256 _deadline)
external
isActivated(_gameID)
isOngoing(_gameID)
isValidTeam(_gameID, _team)
isOwner()
{
// TODO: check deadline limit
require(_deadline >= now + 86400, "deadline must be more than one day later.");
game_[_gameID].ended = true;
game_[_gameID].winnerTeam = _team;
game_[_gameID].gameEndComment = _comment;
game_[_gameID].withdrawDeadline = _deadline;
if (teams_[_gameID][_team].keys == 0) {
// no one bought winning keys, send pot to community
uint256 _totalPot = (gameStatus_[_gameID].winningVaultInst).add(gameStatus_[_gameID].winningVaultFinal);
gameStatus_[_gameID].totalWithdrawn = _totalPot;
if (_totalPot > 0) {
FSKingCorp.deposit.value(_totalPot)();
}
}
emit FSEvents.onGameEnded(_gameID, _team, _comment, now);
}
<FILL_FUNCTION>
/// @notice Withdraw winnings. Only available after a game is ended
/// (winning team selected or game canceled).
/// Emits "onWithdraw" event.
/// @param _gameID Game ID of the game.
function withdraw(uint256 _gameID)
external
isHuman()
isActivated(_gameID)
isEnded(_gameID)
{
require(now < game_[_gameID].withdrawDeadline, "withdraw deadline already passed");
require(gameStatus_[_gameID].fundCleared == false, "fund already cleared");
uint256 _pID = FSBook.pIDxAddr_(msg.sender);
require(_pID != 0, "player has not played this game");
require(players_[_pID][_gameID].withdrawn == false, "player already cashed out");
players_[_pID][_gameID].withdrawn = true;
if (game_[_gameID].canceled) {
// game is canceled
// withdraw 95% of the original payments
uint256 _totalInvestment = players_[_pID][_gameID].eth.mul(95) / 100;
if (_totalInvestment > 0) {
// send to player
FSBook.getPlayerAddr(_pID).transfer(_totalInvestment);
gameStatus_[_gameID].totalWithdrawn = _totalInvestment.add(gameStatus_[_gameID].totalWithdrawn);
}
emit FSEvents.onWithdraw(_gameID, _pID, msg.sender, FSBook.getPlayerName(_pID), _totalInvestment, now);
} else {
uint256 _totalWinnings = getPlayerInstWinning(_gameID, _pID, game_[_gameID].winnerTeam).add(getPlayerPotWinning(_gameID, _pID, game_[_gameID].winnerTeam));
if (_totalWinnings > 0) {
// send to player
FSBook.getPlayerAddr(_pID).transfer(_totalWinnings);
gameStatus_[_gameID].totalWithdrawn = _totalWinnings.add(gameStatus_[_gameID].totalWithdrawn);
}
emit FSEvents.onWithdraw(_gameID, _pID, msg.sender, FSBook.getPlayerName(_pID), _totalWinnings, now);
}
}
/// @notice Clear funds of a game. Only owner(s) can do this, after withdraw deadline
/// is passed.
/// Emits "onFundCleared" event.
/// @param _gameID Game ID of the game.
function clearFund(uint256 _gameID)
external
isHuman()
isEnded(_gameID)
isOwner()
{
require(now >= game_[_gameID].withdrawDeadline, "withdraw deadline not passed yet");
require(gameStatus_[_gameID].fundCleared == false, "fund already cleared");
gameStatus_[_gameID].fundCleared = true;
// send remaining fund to community
uint256 _totalPot = (gameStatus_[_gameID].winningVaultInst).add(gameStatus_[_gameID].winningVaultFinal);
uint256 _amount = _totalPot.sub(gameStatus_[_gameID].totalWithdrawn);
if (_amount > 0) {
FSKingCorp.deposit.value(_amount)();
}
emit onFundCleared(_gameID, _amount, now);
}
/// @notice Get a player's current instant pot winnings.
/// @param _gameID Game ID of the game.
/// @param _pID Player ID of the player.
/// @param _team Team ID of the team.
/// @return Instant pot winnings of the player for this game and this team.
function getPlayerInstWinning(uint256 _gameID, uint256 _pID, uint256 _team)
public
view
isActivated(_gameID)
isValidTeam(_gameID, _team)
returns(uint256)
{
return ((((teams_[_gameID][_team].mask).mul(playerTeams_[_pID][_gameID][_team].keys)) / (1000000000000000000)).sub(playerTeams_[_pID][_gameID][_team].mask));
}
/// @notice Get a player's current final pot winnings.
/// @param _gameID Game ID of the game.
/// @param _pID Player ID of the player.
/// @param _team Team ID of the team.
/// @return Final pot winnings of the player for this game and this team.
function getPlayerPotWinning(uint256 _gameID, uint256 _pID, uint256 _team)
public
view
isActivated(_gameID)
isValidTeam(_gameID, _team)
returns(uint256)
{
if (teams_[_gameID][_team].keys > 0) {
return gameStatus_[_gameID].winningVaultFinal.mul(playerTeams_[_pID][_gameID][_team].keys) / teams_[_gameID][_team].keys;
} else {
return 0;
}
}
/// @notice Get current game status.
/// @param _gameID Game ID of the game.
/// @return (number of teams, names, keys, eth, current key price for 1 key)
function getGameStatus(uint256 _gameID)
public
view
isActivated(_gameID)
returns(uint256, bytes32[] memory, uint256[] memory, uint256[] memory, uint256[] memory)
{
uint256 _nt = game_[_gameID].numberOfTeams;
bytes32[] memory _names = new bytes32[](_nt);
uint256[] memory _keys = new uint256[](_nt);
uint256[] memory _eth = new uint256[](_nt);
uint256[] memory _keyPrice = new uint256[](_nt);
uint256 i;
for (i = 0; i < _nt; i++) {
_names[i] = teams_[_gameID][i].name;
_keys[i] = teams_[_gameID][i].keys;
_eth[i] = teams_[_gameID][i].eth;
_keyPrice[i] = getBuyPrice(_gameID, i, 1000000000000000000);
}
return (_nt, _names, _keys, _eth, _keyPrice);
}
/// @notice Get player status of a game.
/// @param _gameID Game ID of the game.
/// @param _pID Player ID of the player.
/// @return (name, eth for each team, keys for each team, inst win for each team, pot win for each team)
function getPlayerStatus(uint256 _gameID, uint256 _pID)
public
view
isActivated(_gameID)
returns(bytes32, uint256[] memory, uint256[] memory, uint256[] memory, uint256[] memory)
{
uint256 _nt = game_[_gameID].numberOfTeams;
uint256[] memory _eth = new uint256[](_nt);
uint256[] memory _keys = new uint256[](_nt);
uint256[] memory _instWin = new uint256[](_nt);
uint256[] memory _potWin = new uint256[](_nt);
uint256 i;
for (i = 0; i < _nt; i++) {
_eth[i] = playerTeams_[_pID][_gameID][i].eth;
_keys[i] = playerTeams_[_pID][_gameID][i].keys;
_instWin[i] = getPlayerInstWinning(_gameID, _pID, i);
_potWin[i] = getPlayerPotWinning(_gameID, _pID, i);
}
return (FSBook.getPlayerName(_pID), _eth, _keys, _instWin, _potWin);
}
/// @notice Get the price buyer have to pay for next keys.
/// @param _gameID Game ID of the game.
/// @param _team Team ID of the team.
/// @param _keys Number of keys (in wei).
/// @return Price for the number of keys to buy (in wei).
function getBuyPrice(uint256 _gameID, uint256 _team, uint256 _keys)
public
view
isActivated(_gameID)
isValidTeam(_gameID, _team)
returns(uint256)
{
return ((teams_[_gameID][_team].keys.add(_keys)).ethRec(_keys));
}
/// @notice Get the prices buyer have to pay for next keys for all teams.
/// @param _gameID Game ID of the game.
/// @param _keys Array of number of keys (in wei) for all teams.
/// @return (total eth, array of prices in wei).
function getBuyPrices(uint256 _gameID, uint256[] memory _keys)
public
view
isActivated(_gameID)
returns(uint256, uint256[])
{
uint256 _totalEth = 0;
uint256 _nt = game_[_gameID].numberOfTeams;
uint256[] memory _eth = new uint256[](_nt);
uint256 i;
require(_nt == _keys.length, "Incorrect number of teams");
for (i = 0; i < _nt; i++) {
if (_keys[i] > 0) {
_eth[i] = getBuyPrice(_gameID, i, _keys[i]);
_totalEth = _totalEth.add(_eth[i]);
}
}
return (_totalEth, _eth);
}
/// @notice Get the number of keys can be bought with an amount of ETH.
/// @param _gameID Game ID of the game.
/// @param _team Team ID of the team.
/// @param _eth Amount of ETH in wei.
/// @return Number of keys can be bought (in wei).
function getKeysfromETH(uint256 _gameID, uint256 _team, uint256 _eth)
public
view
isActivated(_gameID)
isValidTeam(_gameID, _team)
returns(uint256)
{
return (teams_[_gameID][_team].eth).keysRec(_eth);
}
/// @notice Get all numbers of keys can be bought with amounts of ETH.
/// @param _gameID Game ID of the game.
/// @param _eths Array of amounts of ETH in wei.
/// @return (total keys, array of number of keys in wei).
function getKeysFromETHs(uint256 _gameID, uint256[] memory _eths)
public
view
isActivated(_gameID)
returns(uint256, uint256[])
{
uint256 _totalKeys = 0;
uint256 _nt = game_[_gameID].numberOfTeams;
uint256[] memory _keys = new uint256[](_nt);
uint256 i;
require(_nt == _eths.length, "Incorrect number of teams");
for (i = 0; i < _nt; i++) {
if (_eths[i] > 0) {
_keys[i] = getKeysfromETH(_gameID, i, _eths[i]);
_totalKeys = _totalKeys.add(_keys[i]);
}
}
return (_totalKeys, _keys);
}
/// @dev Handle comments.
/// @param _gameID Game ID of the game.
/// @param _pID Player ID of the player.
/// @param _comment Comment to be used.
function handleComment(uint256 _gameID, uint256 _pID, string memory _comment)
private
{
bytes memory _commentBytes = bytes(_comment);
// comment is empty, do nothing
if (_commentBytes.length == 0) {
return;
}
// only handle comments when eth >= 0.001
uint256 _totalEth = msg.value;
if (_totalEth >= 1000000000000000) {
require(_commentBytes.length <= 64, "comment is too long");
bytes32 _name = FSBook.getPlayerName(_pID);
playerComments_[_gameID][playerCommentsIndex_[_gameID]] = FSdatasets.PlayerComment(_pID, _name, _totalEth, _comment);
playerCommentsIndex_[_gameID] ++;
emit onComment(_gameID, _pID, msg.sender, _name, _totalEth, _comment, now);
}
}
/// @dev Buy keys for all teams.
/// @param _gameID Game ID of the game.
/// @param _pID Player ID of the player.
/// @param _teamEth Array of eth paid for each team.
/// @param _affID Affiliate ID
function buysCore(uint256 _gameID, uint256 _pID, uint256[] memory _teamEth, uint256 _affID)
private
{
uint256 _nt = game_[_gameID].numberOfTeams;
uint256[] memory _keys = new uint256[](_nt);
bytes32 _name = FSBook.getPlayerName(_pID);
uint256 _totalEth = 0;
uint256 i;
require(_teamEth.length == _nt, "Number of teams is not correct");
// for all teams...
for (i = 0; i < _nt; i++) {
if (_teamEth[i] > 0) {
// compute total eth
_totalEth = _totalEth.add(_teamEth[i]);
// compute number of keys to buy
_keys[i] = (teams_[_gameID][i].eth).keysRec(_teamEth[i]);
// update player data
playerTeams_[_pID][_gameID][i].eth = _teamEth[i].add(playerTeams_[_pID][_gameID][i].eth);
playerTeams_[_pID][_gameID][i].keys = _keys[i].add(playerTeams_[_pID][_gameID][i].keys);
// update team data
teams_[_gameID][i].eth = _teamEth[i].add(teams_[_gameID][i].eth);
teams_[_gameID][i].keys = _keys[i].add(teams_[_gameID][i].keys);
emit FSEvents.onPurchase(_gameID, _pID, msg.sender, _name, i, _teamEth[i], _keys[i], _affID, now);
}
}
// check assigned ETH for each team is the same as msg.value
require(_totalEth == msg.value, "Total ETH is not the same as msg.value");
// update game data and player data
gameStatus_[_gameID].totalEth = _totalEth.add(gameStatus_[_gameID].totalEth);
players_[_pID][_gameID].eth = _totalEth.add(players_[_pID][_gameID].eth);
distributeAll(_gameID, _pID, _affID, _totalEth, _keys);
}
/// @dev Distribute paid ETH to different pots.
/// @param _gameID Game ID of the game.
/// @param _pID Player ID of the player.
/// @param _affID Affiliate ID used for this transasction.
/// @param _totalEth Total ETH paid.
/// @param _keys Array of keys bought for each team.
function distributeAll(uint256 _gameID, uint256 _pID, uint256 _affID, uint256 _totalEth, uint256[] memory _keys)
private
{
// community 2%
uint256 _com = _totalEth / 50;
// distribute 3% to aff
uint256 _aff = _totalEth.mul(3) / 100;
_com = _com.add(handleAffiliate(_pID, _affID, _aff));
// instant pot (15%)
uint256 _instPot = _totalEth.mul(15) / 100;
// winning pot (80%)
uint256 _pot = _totalEth.mul(80) / 100;
// Send community to forwarder
if (!address(FSKingCorp).call.value(_com)(abi.encode("deposit()"))) {
// if unable to deposit, add to pot
_pot = _pot.add(_com);
}
gameStatus_[_gameID].winningVaultInst = _instPot.add(gameStatus_[_gameID].winningVaultInst);
gameStatus_[_gameID].winningVaultFinal = _pot.add(gameStatus_[_gameID].winningVaultFinal);
// update masks for instant winning vault
uint256 _nt = _keys.length;
for (uint256 i = 0; i < _nt; i++) {
uint256 _newPot = _instPot.add(teams_[_gameID][i].dust);
uint256 _dust = updateMasks(_gameID, _pID, i, _newPot, _keys[i]);
teams_[_gameID][i].dust = _dust;
}
}
/// @dev Handle affiliate payments.
/// @param _pID Player ID of the player.
/// @param _affID Affiliate ID used for this transasction.
/// @param _aff Amount of ETH for affiliate payment.
/// @return The amount remained for the community (if there's no affiliate payment)
function handleAffiliate(uint256 _pID, uint256 _affID, uint256 _aff)
private
returns (uint256)
{
uint256 _com = 0;
if (_affID == 0 || _affID == _pID) {
_com = _aff;
} else if(FSBook.getPlayerHasAff(_affID)) {
FSBook.depositAffiliate.value(_aff)(_affID);
} else {
_com = _aff;
}
return _com;
}
/// @dev Updates masks for instant pot.
/// @param _gameID Game ID of the game.
/// @param _pID Player ID of the player.
/// @param _team Team ID of the team.
/// @param _gen Amount of ETH to be added into instant pot.
/// @param _keys Number of keys bought.
/// @return Dust left over.
function updateMasks(uint256 _gameID, uint256 _pID, uint256 _team, 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)
if (teams_[_gameID][_team].keys > 0) {
uint256 _ppt = (_gen.mul(1000000000000000000)) / (teams_[_gameID][_team].keys);
teams_[_gameID][_team].mask = _ppt.add(teams_[_gameID][_team].mask);
updatePlayerMask(_gameID, _pID, _team, _ppt, _keys);
// calculate & return dust
return(_gen.sub((_ppt.mul(teams_[_gameID][_team].keys)) / (1000000000000000000)));
} else {
return _gen;
}
}
/// @dev Updates masks for the player.
/// @param _gameID Game ID of the game.
/// @param _pID Player ID of the player.
/// @param _team Team ID of the team.
/// @param _ppt Amount of unit ETH.
/// @param _keys Number of keys bought.
/// @return Dust left over.
function updatePlayerMask(uint256 _gameID, uint256 _pID, uint256 _team, uint256 _ppt, uint256 _keys)
private
{
if (_keys > 0) {
// 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);
playerTeams_[_pID][_gameID][_team].mask = (((teams_[_gameID][_team].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(playerTeams_[_pID][_gameID][_team].mask);
}
}
/// @dev Check if a game is activated.
/// @param _gameID Game ID of the game.
modifier isActivated(uint256 _gameID) {
require(game_[_gameID].gameStartTime > 0, "Not activated yet");
require(game_[_gameID].gameStartTime <= now, "game not started yet");
_;
}
/// @dev Check if a game is not paused.
/// @param _gameID Game ID of the game.
modifier isNotPaused(uint256 _gameID) {
require(game_[_gameID].paused == false, "game is paused");
_;
}
/// @dev Check if a game is not closed.
/// @param _gameID Game ID of the game.
modifier isNotClosed(uint256 _gameID) {
require(game_[_gameID].closeTime == 0 || game_[_gameID].closeTime > now, "game is closed");
_;
}
/// @dev Check if a game is not settled.
/// @param _gameID Game ID of the game.
modifier isOngoing(uint256 _gameID) {
require(game_[_gameID].ended == false, "game is ended");
_;
}
/// @dev Check if a game is settled.
/// @param _gameID Game ID of the game.
modifier isEnded(uint256 _gameID) {
require(game_[_gameID].ended == true, "game is not ended");
_;
}
/// @dev Check if caller is not a smart contract.
modifier isHuman() {
address _addr = msg.sender;
require (_addr == tx.origin, "Human only");
uint256 _codeLength;
assembly { _codeLength := extcodesize(_addr) }
require(_codeLength == 0, "Human only");
_;
}
// TODO: Check address!!!
/// @dev Check if caller is one of the owner(s).
modifier isOwner() {
require(
msg.sender == 0xE3FF68fB79FEE1989FB67Eb04e196E361EcAec3e ||
msg.sender == 0xb914843D2E56722a2c133Eff956d1F99b820D468 ||
msg.sender == 0xE0b005384dF8F4D80e9a69B6210eC1929A935D97 ||
msg.sender == 0xc52FA2C9411fCd4f58be2d6725094689C46242f2
, "Only owner can do this");
_;
}
/// @dev Check if purchase is within limits.
/// (between 0.000000001 ETH and 100000 ETH)
/// @param _eth Amount of ETH
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "too little money");
require(_eth <= 100000000000000000000000, "too much money");
_;
}
/// @dev Check if team ID is valid.
/// @param _gameID Game ID of the game.
/// @param _team Team ID of the team.
modifier isValidTeam(uint256 _gameID, uint256 _team) {
require(_team < game_[_gameID].numberOfTeams, "there is no such team");
_;
}
} |
// TODO: check deadline limit
require(_deadline >= now + 86400, "deadline must be more than one day later.");
game_[_gameID].ended = true;
game_[_gameID].canceled = true;
game_[_gameID].gameEndComment = _comment;
game_[_gameID].withdrawDeadline = _deadline;
emit FSEvents.onGameCancelled(_gameID, _comment, now);
| function cancelGame(uint256 _gameID, string _comment, uint256 _deadline)
external
isActivated(_gameID)
isOngoing(_gameID)
isOwner()
| /// @notice Cancel a game. Only owner(s) can do this.
/// Players can't no longer buy tickets for this game once a winning team is selected.
/// Players who bought tickets can get back 95% of the ETH paid.
/// Emits "onGameCancelled" event.
/// @param _gameID Game ID of the game.
/// @param _comment A closing comment to describe the conclusion of the game.
/// @param _deadline Timestamp of the withdraw deadline of the game
function cancelGame(uint256 _gameID, string _comment, uint256 _deadline)
external
isActivated(_gameID)
isOngoing(_gameID)
isOwner()
|
76494 | 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.
*/
constructor() public {
//owner = 0x01D5b223873F254751BE548ea1E06a9118693e72;
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.
*/
constructor() public {
//owner = 0x01D5b223873F254751BE548ea1E06a9118693e72;
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));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
| function transferOwnership(address newOwner) public onlyOwner | /**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner |
92053 | ERC20Impl | transferFrom | contract ERC20Impl {
// 代币名称
string public name ="CoinUnion";
// 代币符号或者说简写
string public symbol = "BHT";
// 代币小数点位数,代币的最小单位
uint8 public decimals = 6;
// 代币的发行总量,总发行 1,000,000,000 BHT 代币
uint public totalSupply = 1000000000000000;
// 代币交易时触发的事件,即调用transfer方法时触发
event Transfer(address indexed from, address indexed to, uint tokens);
// 允许其他用户从你的账户上花费代币时触发的事件,即调用approve方法时触发
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
// 存储每个地址的余额(因为是public的所以会自动生成balanceOf方法)
mapping (address => uint256) public balanceOf;
// 存储每个地址可操作的地址及其可操作的金额
mapping (address => mapping (address => uint256)) internal allowed;
// 初始化属性
constructor() public {
// 初始化该代币的账户会拥有所有的代币
balanceOf[msg.sender] = totalSupply;
}
// 实现代币交易,用于给某个地址转移代币
function transfer(address to, uint tokens) public returns (bool success) {
// 检验接收者地址是否合法
require(to != address(0));
// 检验发送者账户余额是否足够
require(balanceOf[msg.sender] >= tokens);
// 检验是否会发生溢出
require(balanceOf[to] + tokens >= balanceOf[to]);
// 扣除发送者账户余额
balanceOf[msg.sender] -= tokens;
// 增加接收者账户余额
balanceOf[to] += tokens;
// 触发相应的事件
emit Transfer(msg.sender, to, tokens);
success = true;
}
// 实现代币用户之间的交易,从一个地址转移代币到另一个地址
function transferFrom(address from, address to, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> }
// 允许spender多次从你的账户取款,并且最多可取tokens个,主要用于某些场景下授权委托其他用户从你的账户上花费代币
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
// 触发相应的事件
emit Approval(msg.sender, spender, tokens);
success = true;
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
} | contract ERC20Impl {
// 代币名称
string public name ="CoinUnion";
// 代币符号或者说简写
string public symbol = "BHT";
// 代币小数点位数,代币的最小单位
uint8 public decimals = 6;
// 代币的发行总量,总发行 1,000,000,000 BHT 代币
uint public totalSupply = 1000000000000000;
// 代币交易时触发的事件,即调用transfer方法时触发
event Transfer(address indexed from, address indexed to, uint tokens);
// 允许其他用户从你的账户上花费代币时触发的事件,即调用approve方法时触发
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
// 存储每个地址的余额(因为是public的所以会自动生成balanceOf方法)
mapping (address => uint256) public balanceOf;
// 存储每个地址可操作的地址及其可操作的金额
mapping (address => mapping (address => uint256)) internal allowed;
// 初始化属性
constructor() public {
// 初始化该代币的账户会拥有所有的代币
balanceOf[msg.sender] = totalSupply;
}
// 实现代币交易,用于给某个地址转移代币
function transfer(address to, uint tokens) public returns (bool success) {
// 检验接收者地址是否合法
require(to != address(0));
// 检验发送者账户余额是否足够
require(balanceOf[msg.sender] >= tokens);
// 检验是否会发生溢出
require(balanceOf[to] + tokens >= balanceOf[to]);
// 扣除发送者账户余额
balanceOf[msg.sender] -= tokens;
// 增加接收者账户余额
balanceOf[to] += tokens;
// 触发相应的事件
emit Transfer(msg.sender, to, tokens);
success = true;
}
<FILL_FUNCTION>
// 允许spender多次从你的账户取款,并且最多可取tokens个,主要用于某些场景下授权委托其他用户从你的账户上花费代币
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
// 触发相应的事件
emit Approval(msg.sender, spender, tokens);
success = true;
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
} |
// 检验地址是否合法
require(to != address(0) && from != address(0));
// 检验发送者账户余额是否足够
require(balanceOf[from] >= tokens);
// 检验操作的金额是否是被允许的
require(allowed[from][msg.sender] <= tokens);
// 检验是否会发生溢出
require(balanceOf[to] + tokens >= balanceOf[to]);
// 扣除发送者账户余额
balanceOf[from] -= tokens;
// 增加接收者账户余额
balanceOf[to] += tokens;
// 触发相应的事件
emit Transfer(from, to, tokens);
success = true;
| function transferFrom(address from, address to, uint tokens) public returns (bool success) | // 实现代币用户之间的交易,从一个地址转移代币到另一个地址
function transferFrom(address from, address to, uint tokens) public returns (bool success) |
34218 | AccessControl | AccessControl | contract AccessControl {
event accessGranted(address user, uint8 access);
// The addresses of the accounts (or contracts) that can execute actions within each roles.
mapping(address => mapping(uint8 => bool)) accessRights;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev Grants admin (1) access to deployer of the contract
function AccessControl() public {<FILL_FUNCTION_BODY> }
/// @dev Provides access to a determined transaction
/// @param _user - user that will be granted the access right
/// @param _transaction - transaction that will be granted to user
function grantAccess(address _user, uint8 _transaction) public canAccess(1) {
require(_user != address(0));
accessRights[_user][_transaction] = true;
accessGranted(_user, _transaction);
}
/// @dev Revokes access to a determined transaction
/// @param _user - user that will have the access revoked
/// @param _transaction - transaction that will be revoked
function revokeAccess(address _user, uint8 _transaction) public canAccess(1) {
require(_user != address(0));
accessRights[_user][_transaction] = false;
}
/// @dev Check if user has access to a determined transaction
/// @param _user - user
/// @param _transaction - transaction
function hasAccess(address _user, uint8 _transaction) public view returns (bool) {
require(_user != address(0));
return accessRights[_user][_transaction];
}
/// @dev Access modifier
/// @param _transaction - transaction
modifier canAccess(uint8 _transaction) {
require(accessRights[msg.sender][_transaction]);
_;
}
/// @dev Drains all Eth
function withdrawBalance() external canAccess(2) {
msg.sender.transfer(this.balance);
}
/// @dev Drains any ERC20 token accidentally sent to contract
function withdrawTokens(address tokenContract) external canAccess(2) {
ERC20 tc = ERC20(tokenContract);
tc.transfer(msg.sender, tc.balanceOf(this));
}
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() public canAccess(1) whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract.
function unpause() public canAccess(1) whenPaused {
paused = false;
}
} | contract AccessControl {
event accessGranted(address user, uint8 access);
// The addresses of the accounts (or contracts) that can execute actions within each roles.
mapping(address => mapping(uint8 => bool)) accessRights;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
<FILL_FUNCTION>
/// @dev Provides access to a determined transaction
/// @param _user - user that will be granted the access right
/// @param _transaction - transaction that will be granted to user
function grantAccess(address _user, uint8 _transaction) public canAccess(1) {
require(_user != address(0));
accessRights[_user][_transaction] = true;
accessGranted(_user, _transaction);
}
/// @dev Revokes access to a determined transaction
/// @param _user - user that will have the access revoked
/// @param _transaction - transaction that will be revoked
function revokeAccess(address _user, uint8 _transaction) public canAccess(1) {
require(_user != address(0));
accessRights[_user][_transaction] = false;
}
/// @dev Check if user has access to a determined transaction
/// @param _user - user
/// @param _transaction - transaction
function hasAccess(address _user, uint8 _transaction) public view returns (bool) {
require(_user != address(0));
return accessRights[_user][_transaction];
}
/// @dev Access modifier
/// @param _transaction - transaction
modifier canAccess(uint8 _transaction) {
require(accessRights[msg.sender][_transaction]);
_;
}
/// @dev Drains all Eth
function withdrawBalance() external canAccess(2) {
msg.sender.transfer(this.balance);
}
/// @dev Drains any ERC20 token accidentally sent to contract
function withdrawTokens(address tokenContract) external canAccess(2) {
ERC20 tc = ERC20(tokenContract);
tc.transfer(msg.sender, tc.balanceOf(this));
}
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() public canAccess(1) whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract.
function unpause() public canAccess(1) whenPaused {
paused = false;
}
} |
accessRights[msg.sender][1] = true;
accessGranted(msg.sender, 1);
| function AccessControl() public | /// @dev Grants admin (1) access to deployer of the contract
function AccessControl() public |
63480 | ERC20Mintable | mint | contract ERC20Mintable is BasicToken, Ownable {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint( address to, uint256 value ) public virtual onlyOwner returns (bool){<FILL_FUNCTION_BODY> }
} | contract ERC20Mintable is BasicToken, Ownable {
<FILL_FUNCTION>
} |
_mint(to, value);
return true;
| function mint( address to, uint256 value ) public virtual onlyOwner returns (bool) | /**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint( address to, uint256 value ) public virtual onlyOwner returns (bool) |
42167 | PermissionGroups | removeOperator | contract PermissionGroups {
address public admin;
address public pendingAdmin;
mapping(address=>bool) internal operators;
mapping(address=>bool) internal alerters;
address[] internal operatorsGroup;
address[] internal alertersGroup;
function PermissionGroups() public {
admin = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == admin);
_;
}
modifier onlyOperator() {
require(operators[msg.sender]);
_;
}
modifier onlyAlerter() {
require(alerters[msg.sender]);
_;
}
function getOperators () external view returns(address[]) {
return operatorsGroup;
}
function getAlerters () external view returns(address[]) {
return alertersGroup;
}
event TransferAdminPending(address pendingAdmin);
/**
* @dev Allows the current admin to set the pendingAdmin address.
* @param newAdmin The address to transfer ownership to.
*/
function transferAdmin(address newAdmin) public onlyAdmin {
require(newAdmin != address(0));
TransferAdminPending(pendingAdmin);
pendingAdmin = newAdmin;
}
event AdminClaimed( address newAdmin, address previousAdmin);
/**
* @dev Allows the pendingAdmin address to finalize the change admin process.
*/
function claimAdmin() public {
require(pendingAdmin == msg.sender);
AdminClaimed(pendingAdmin, admin);
admin = pendingAdmin;
pendingAdmin = address(0);
}
event AlerterAdded (address newAlerter, bool isAdd);
function addAlerter(address newAlerter) public onlyAdmin {
require(!alerters[newAlerter]); // prevent duplicates.
AlerterAdded(newAlerter, true);
alerters[newAlerter] = true;
alertersGroup.push(newAlerter);
}
function removeAlerter (address alerter) public onlyAdmin {
require(alerters[alerter]);
alerters[alerter] = false;
for (uint i = 0; i < alertersGroup.length; ++i) {
if (alertersGroup[i] == alerter) {
alertersGroup[i] = alertersGroup[alertersGroup.length - 1];
alertersGroup.length--;
AlerterAdded(alerter, false);
break;
}
}
}
event OperatorAdded(address newOperator, bool isAdd);
function addOperator(address newOperator) public onlyAdmin {
require(!operators[newOperator]); // prevent duplicates.
OperatorAdded(newOperator, true);
operators[newOperator] = true;
operatorsGroup.push(newOperator);
}
function removeOperator (address operator) public onlyAdmin {<FILL_FUNCTION_BODY> }
} | contract PermissionGroups {
address public admin;
address public pendingAdmin;
mapping(address=>bool) internal operators;
mapping(address=>bool) internal alerters;
address[] internal operatorsGroup;
address[] internal alertersGroup;
function PermissionGroups() public {
admin = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == admin);
_;
}
modifier onlyOperator() {
require(operators[msg.sender]);
_;
}
modifier onlyAlerter() {
require(alerters[msg.sender]);
_;
}
function getOperators () external view returns(address[]) {
return operatorsGroup;
}
function getAlerters () external view returns(address[]) {
return alertersGroup;
}
event TransferAdminPending(address pendingAdmin);
/**
* @dev Allows the current admin to set the pendingAdmin address.
* @param newAdmin The address to transfer ownership to.
*/
function transferAdmin(address newAdmin) public onlyAdmin {
require(newAdmin != address(0));
TransferAdminPending(pendingAdmin);
pendingAdmin = newAdmin;
}
event AdminClaimed( address newAdmin, address previousAdmin);
/**
* @dev Allows the pendingAdmin address to finalize the change admin process.
*/
function claimAdmin() public {
require(pendingAdmin == msg.sender);
AdminClaimed(pendingAdmin, admin);
admin = pendingAdmin;
pendingAdmin = address(0);
}
event AlerterAdded (address newAlerter, bool isAdd);
function addAlerter(address newAlerter) public onlyAdmin {
require(!alerters[newAlerter]); // prevent duplicates.
AlerterAdded(newAlerter, true);
alerters[newAlerter] = true;
alertersGroup.push(newAlerter);
}
function removeAlerter (address alerter) public onlyAdmin {
require(alerters[alerter]);
alerters[alerter] = false;
for (uint i = 0; i < alertersGroup.length; ++i) {
if (alertersGroup[i] == alerter) {
alertersGroup[i] = alertersGroup[alertersGroup.length - 1];
alertersGroup.length--;
AlerterAdded(alerter, false);
break;
}
}
}
event OperatorAdded(address newOperator, bool isAdd);
function addOperator(address newOperator) public onlyAdmin {
require(!operators[newOperator]); // prevent duplicates.
OperatorAdded(newOperator, true);
operators[newOperator] = true;
operatorsGroup.push(newOperator);
}
<FILL_FUNCTION>
} |
require(operators[operator]);
operators[operator] = false;
for (uint i = 0; i < operatorsGroup.length; ++i) {
if (operatorsGroup[i] == operator) {
operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1];
operatorsGroup.length -= 1;
OperatorAdded(operator, false);
break;
}
}
| function removeOperator (address operator) public onlyAdmin | function removeOperator (address operator) public onlyAdmin |
36388 | ApolloFund | approveAndCall | contract ApolloFund 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 ApolloFund(
) {
balances[msg.sender] = 100000000; // Give the creator all initial tokens (100000 for example)
totalSupply = 100000000; // Update total supply (100000 for example)
name = "ApolloFund"; // Set the name for display purposes
decimals = 6; // Amount of decimals for display purposes
symbol = "APF"; // 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 ApolloFund 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 ApolloFund(
) {
balances[msg.sender] = 100000000; // Give the creator all initial tokens (100000 for example)
totalSupply = 100000000; // Update total supply (100000 for example)
name = "ApolloFund"; // Set the name for display purposes
decimals = 6; // Amount of decimals for display purposes
symbol = "APF"; // 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) |
9614 | BitGuildTrade | buyUpgradeCard | contract BitGuildTrade is BitGuildHelper {
BitGuildTokenInterface public tokenContract;
event UnitBought(address player, uint256 unitId, uint256 amount);
event UpgradeCardBought(address player, uint256 upgradeId);
event BuyRareCard(address player, address previous, uint256 rareId,uint256 iPrice);
event UnitSold(address player, uint256 unitId, uint256 amount);
mapping(address => mapping(uint256 => uint256)) unitsOwnedOfPLAT; //cards bought through plat
function() external payable {
revert();
}
function setBitGuildToken(address _tokenContract) external {
tokenContract = BitGuildTokenInterface(_tokenContract);
}
function kill() public onlyOwner {
tokenContract.transferFrom(this, msg.sender, tokenContract.balanceOf(this));
selfdestruct(msg.sender); //end execution, destroy current contract and send funds to a
}
/// @notice Returns all the relevant information about a specific tokenId.
/// val1:flag,val2:id,val3:amount
function _getExtraParam(bytes _extraData) private pure returns(uint256 val1,uint256 val2,uint256 val3) {
if (_extraData.length == 2) {
val1 = uint256(_extraData[0]);
val2 = uint256(_extraData[1]);
val3 = 1;
} else if (_extraData.length == 3) {
val1 = uint256(_extraData[0]);
val2 = uint256(_extraData[1]);
val3 = uint256(_extraData[2]);
}
}
function receiveApproval(address _player, uint256 _value, address _tokenContractAddr, bytes _extraData) external {
require(msg.sender == _tokenContractAddr);
require(_extraData.length >=1);
require(tokenContract.transferFrom(_player, address(this), _value));
uint256 flag;
uint256 unitId;
uint256 amount;
(flag,unitId,amount) = _getExtraParam(_extraData);
if (flag==1) {
buyPLATCards(_player, _value, unitId, amount); // 1-39
} else if (flag==3) {
buyUpgradeCard(_player, _value, unitId); // >=1
} else if (flag==4) {
buyRareItem(_player, _value, unitId); //rarecard
}
}
function buyPLATCards(address _player, uint256 _platValue, uint256 _cardId, uint256 _amount) internal {
require(cards.getGameStarted());
require(_amount>=1);
uint256 existing = cards.getOwnedCount(_player,_cardId);
require(existing < schema.getMaxCAP());
uint256 iAmount;
if (SafeMath.add(existing, _amount) > schema.getMaxCAP()) {
iAmount = SafeMath.sub(schema.getMaxCAP(),existing);
} else {
iAmount = _amount;
}
uint256 coinProduction;
uint256 coinCost;
uint256 ethCost;
if (_cardId>=1 && _cardId<=39) {
coinProduction = schema.unitCoinProduction(_cardId);
coinCost = schema.getCostForCards(_cardId, existing, iAmount);
ethCost = SafeMath.mul(schema.unitPLATCost(_cardId),iAmount); // get platprice
} else if (_cardId>=40) {
coinCost = schema.getCostForBattleCards(_cardId, existing, iAmount);
ethCost = SafeMath.mul(schema.unitBattlePLATCost(_cardId),iAmount); // get platprice
}
require(ethCost>0);
require(SafeMath.add(cards.coinBalanceOf(_player,1),_platValue) >= ethCost);
require(cards.balanceOf(_player) >= coinCost);
// Update players jade
cards.updatePlayersCoinByPurchase(_player, coinCost);
if (ethCost > _platValue) {
cards.setCoinBalance(_player,SafeMath.sub(ethCost,_platValue),1,false);
} else if (_platValue > ethCost) {
// Store overbid in their balance
cards.setCoinBalance(_player,SafeMath.sub(_platValue,ethCost),1,true);
}
uint256 devFund = uint256(SafeMath.div(ethCost,20)); // 5% fee
cards.setTotalEtherPool(uint256(SafeMath.div(ethCost,4)),1,true); // 20% to pool
cards.setCoinBalance(owner,devFund,1,true);
if (coinProduction > 0) {
cards.increasePlayersJadeProduction(_player, cards.getUnitsProduction(_player, _cardId, iAmount));
cards.setUintCoinProduction(_player,_cardId,cards.getUnitsProduction(_player, _cardId, iAmount),true);
}
if (cards.getUintsOwnerCount(_player)<=0) {
cards.AddPlayers(_player);
}
cards.setUintsOwnerCount(_player,iAmount, true);
cards.setOwnedCount(_player,_cardId,iAmount,true);
unitsOwnedOfPLAT[_player][_cardId] = SafeMath.add(unitsOwnedOfPLAT[_player][_cardId],iAmount);
//event
UnitBought(_player, _cardId, iAmount);
}
/// upgrade cards-- jade + plat
function buyUpgradeCard(address _player, uint256 _platValue,uint256 _upgradeId) internal {<FILL_FUNCTION_BODY> }
// Allows someone to send ether and obtain the token
function buyRareItem(address _player, uint256 _platValue,uint256 _rareId) internal {
require(cards.getGameStarted());
address previousOwner = rare.getRareItemsOwner(_rareId); // rare card
require(previousOwner != 0);
require(_player!=previousOwner); // can not buy from itself
uint256 ethCost = rare.getRareItemsPLATPrice(_rareId); // get plat cost
uint256 totalCost = SafeMath.add(cards.coinBalanceOf(_player,1),_platValue);
require(totalCost >= ethCost);
// We have to claim buyer/sellder's goo before updating their production values
cards.updatePlayersCoinByOut(_player);
cards.updatePlayersCoinByOut(previousOwner);
uint256 upgradeClass;
uint256 unitId;
uint256 upgradeValue;
(,,,,upgradeClass, unitId, upgradeValue) = rare.getRarePLATInfo(_rareId);
// modify weight
upgradeUnitMultipliers(_player, upgradeClass, unitId, upgradeValue);
removeUnitMultipliers(previousOwner, upgradeClass, unitId, upgradeValue);
// Splitbid/Overbid
if (ethCost > _platValue) {
cards.setCoinBalance(_player,SafeMath.sub(ethCost,_platValue),1,false);
} else if (_platValue > ethCost) {
// Store overbid in their balance
cards.setCoinBalance(_player,SafeMath.sub(_platValue,ethCost),1,true);
}
// Distribute ethCost uint256 devFund = ethCost / 50;
uint256 devFund = uint256(SafeMath.div(ethCost, 20)); // 5% fee on purchases (marketing, gameplay & maintenance) 抽成2%
uint256 dividends = uint256(SafeMath.div(ethCost,20)); // 5% goes to pool
cards.setTotalEtherPool(dividends,1,true); // 5% to pool
cards.setCoinBalance(owner,devFund,1,true); // 5% fee
// Transfer / update rare item
rare.transferToken(previousOwner,_player,_rareId);
rare.setRarePrice(_rareId,SafeMath.div(SafeMath.mul(rare.getRareItemsPrice(_rareId),5),4));
cards.setCoinBalance(previousOwner,SafeMath.sub(ethCost,SafeMath.add(dividends,devFund)),1,true);
if (cards.getUintsOwnerCount(_player)<=0) {
cards.AddPlayers(_player);
}
cards.setUintsOwnerCount(_player,1,true);
cards.setUintsOwnerCount(previousOwner,1,true);
//tell the world
BuyRareCard(_player, previousOwner, _rareId, ethCost);
}
/// refunds 75% since no transfer between bitguild and player,no need to call approveAndCall
function sellCards( uint256 _unitId, uint256 _amount) external {
require(cards.getGameStarted());
uint256 existing = cards.getOwnedCount(msg.sender,_unitId);
require(existing >= _amount && _amount>0);
existing = SafeMath.sub(existing,_amount);
uint256 coinChange;
uint256 decreaseCoin;
uint256 schemaUnitId;
uint256 coinProduction;
uint256 coinCost;
uint256 ethCost;
bool sellable;
if (_unitId>=40) { // upgrade card
(schemaUnitId,coinCost,, sellable) = schema.getBattleCardInfo(_unitId, existing, _amount);
ethCost = SafeMath.mul(schema.unitBattlePLATCost(_unitId),_amount);
} else {
(schemaUnitId, coinProduction, coinCost, , sellable) = schema.getCardInfo(_unitId, existing, _amount);
ethCost = SafeMath.mul(schema.unitPLATCost(_unitId),_amount); // plat
}
require(sellable); // can be refunded
if (ethCost>0) {
require(unitsOwnedOfPLAT[msg.sender][_unitId]>=_amount);
}
if (coinCost>0) {
coinChange = SafeMath.add(cards.balanceOfUnclaimed(msg.sender), SafeMath.div(SafeMath.mul(coinCost,70),100)); // Claim unsaved goo whilst here
} else {
coinChange = cards.balanceOfUnclaimed(msg.sender);
}
cards.setLastJadeSaveTime(msg.sender);
cards.setRoughSupply(coinChange);
cards.setJadeCoin(msg.sender, coinChange, true); // refund 75% Jadecoin to player
decreaseCoin = cards.getUnitsInProduction(msg.sender, _unitId, _amount);
if (coinProduction > 0) {
cards.reducePlayersJadeProduction(msg.sender, decreaseCoin);
//update the speed of jade minning
cards.setUintCoinProduction(msg.sender,_unitId,decreaseCoin,false);
}
if (ethCost > 0) { // Premium units sell for 75% of buy cost
cards.setCoinBalance(msg.sender,SafeMath.div(SafeMath.mul(ethCost,70),100),1,true);
}
cards.setOwnedCount(msg.sender,_unitId,_amount,false);
cards.setUintsOwnerCount(msg.sender,_amount,false);
if (ethCost>0) {
unitsOwnedOfPLAT[msg.sender][_unitId] = SafeMath.sub(unitsOwnedOfPLAT[msg.sender][_unitId],_amount);
}
//tell the world
UnitSold(msg.sender, _unitId, _amount);
}
//@notice for player withdraw
function withdrawEtherFromTrade(uint256 amount) external {
require(amount <= cards.coinBalanceOf(msg.sender,1));
cards.setCoinBalance(msg.sender,amount,1,false);
tokenContract.transfer(msg.sender,amount);
}
//@notice withraw all PLAT by dev
function withdrawToken(uint256 amount) external onlyOwner {
uint256 balance = tokenContract.balanceOf(this);
require(balance > 0 && balance >= amount);
cards.setCoinBalance(msg.sender,amount,1,false);
tokenContract.transfer(msg.sender, amount);
}
function getCanSellUnit(address _address, uint256 unitId) external view returns (uint256) {
return unitsOwnedOfPLAT[_address][unitId];
}
} | contract BitGuildTrade is BitGuildHelper {
BitGuildTokenInterface public tokenContract;
event UnitBought(address player, uint256 unitId, uint256 amount);
event UpgradeCardBought(address player, uint256 upgradeId);
event BuyRareCard(address player, address previous, uint256 rareId,uint256 iPrice);
event UnitSold(address player, uint256 unitId, uint256 amount);
mapping(address => mapping(uint256 => uint256)) unitsOwnedOfPLAT; //cards bought through plat
function() external payable {
revert();
}
function setBitGuildToken(address _tokenContract) external {
tokenContract = BitGuildTokenInterface(_tokenContract);
}
function kill() public onlyOwner {
tokenContract.transferFrom(this, msg.sender, tokenContract.balanceOf(this));
selfdestruct(msg.sender); //end execution, destroy current contract and send funds to a
}
/// @notice Returns all the relevant information about a specific tokenId.
/// val1:flag,val2:id,val3:amount
function _getExtraParam(bytes _extraData) private pure returns(uint256 val1,uint256 val2,uint256 val3) {
if (_extraData.length == 2) {
val1 = uint256(_extraData[0]);
val2 = uint256(_extraData[1]);
val3 = 1;
} else if (_extraData.length == 3) {
val1 = uint256(_extraData[0]);
val2 = uint256(_extraData[1]);
val3 = uint256(_extraData[2]);
}
}
function receiveApproval(address _player, uint256 _value, address _tokenContractAddr, bytes _extraData) external {
require(msg.sender == _tokenContractAddr);
require(_extraData.length >=1);
require(tokenContract.transferFrom(_player, address(this), _value));
uint256 flag;
uint256 unitId;
uint256 amount;
(flag,unitId,amount) = _getExtraParam(_extraData);
if (flag==1) {
buyPLATCards(_player, _value, unitId, amount); // 1-39
} else if (flag==3) {
buyUpgradeCard(_player, _value, unitId); // >=1
} else if (flag==4) {
buyRareItem(_player, _value, unitId); //rarecard
}
}
function buyPLATCards(address _player, uint256 _platValue, uint256 _cardId, uint256 _amount) internal {
require(cards.getGameStarted());
require(_amount>=1);
uint256 existing = cards.getOwnedCount(_player,_cardId);
require(existing < schema.getMaxCAP());
uint256 iAmount;
if (SafeMath.add(existing, _amount) > schema.getMaxCAP()) {
iAmount = SafeMath.sub(schema.getMaxCAP(),existing);
} else {
iAmount = _amount;
}
uint256 coinProduction;
uint256 coinCost;
uint256 ethCost;
if (_cardId>=1 && _cardId<=39) {
coinProduction = schema.unitCoinProduction(_cardId);
coinCost = schema.getCostForCards(_cardId, existing, iAmount);
ethCost = SafeMath.mul(schema.unitPLATCost(_cardId),iAmount); // get platprice
} else if (_cardId>=40) {
coinCost = schema.getCostForBattleCards(_cardId, existing, iAmount);
ethCost = SafeMath.mul(schema.unitBattlePLATCost(_cardId),iAmount); // get platprice
}
require(ethCost>0);
require(SafeMath.add(cards.coinBalanceOf(_player,1),_platValue) >= ethCost);
require(cards.balanceOf(_player) >= coinCost);
// Update players jade
cards.updatePlayersCoinByPurchase(_player, coinCost);
if (ethCost > _platValue) {
cards.setCoinBalance(_player,SafeMath.sub(ethCost,_platValue),1,false);
} else if (_platValue > ethCost) {
// Store overbid in their balance
cards.setCoinBalance(_player,SafeMath.sub(_platValue,ethCost),1,true);
}
uint256 devFund = uint256(SafeMath.div(ethCost,20)); // 5% fee
cards.setTotalEtherPool(uint256(SafeMath.div(ethCost,4)),1,true); // 20% to pool
cards.setCoinBalance(owner,devFund,1,true);
if (coinProduction > 0) {
cards.increasePlayersJadeProduction(_player, cards.getUnitsProduction(_player, _cardId, iAmount));
cards.setUintCoinProduction(_player,_cardId,cards.getUnitsProduction(_player, _cardId, iAmount),true);
}
if (cards.getUintsOwnerCount(_player)<=0) {
cards.AddPlayers(_player);
}
cards.setUintsOwnerCount(_player,iAmount, true);
cards.setOwnedCount(_player,_cardId,iAmount,true);
unitsOwnedOfPLAT[_player][_cardId] = SafeMath.add(unitsOwnedOfPLAT[_player][_cardId],iAmount);
//event
UnitBought(_player, _cardId, iAmount);
}
<FILL_FUNCTION>
// Allows someone to send ether and obtain the token
function buyRareItem(address _player, uint256 _platValue,uint256 _rareId) internal {
require(cards.getGameStarted());
address previousOwner = rare.getRareItemsOwner(_rareId); // rare card
require(previousOwner != 0);
require(_player!=previousOwner); // can not buy from itself
uint256 ethCost = rare.getRareItemsPLATPrice(_rareId); // get plat cost
uint256 totalCost = SafeMath.add(cards.coinBalanceOf(_player,1),_platValue);
require(totalCost >= ethCost);
// We have to claim buyer/sellder's goo before updating their production values
cards.updatePlayersCoinByOut(_player);
cards.updatePlayersCoinByOut(previousOwner);
uint256 upgradeClass;
uint256 unitId;
uint256 upgradeValue;
(,,,,upgradeClass, unitId, upgradeValue) = rare.getRarePLATInfo(_rareId);
// modify weight
upgradeUnitMultipliers(_player, upgradeClass, unitId, upgradeValue);
removeUnitMultipliers(previousOwner, upgradeClass, unitId, upgradeValue);
// Splitbid/Overbid
if (ethCost > _platValue) {
cards.setCoinBalance(_player,SafeMath.sub(ethCost,_platValue),1,false);
} else if (_platValue > ethCost) {
// Store overbid in their balance
cards.setCoinBalance(_player,SafeMath.sub(_platValue,ethCost),1,true);
}
// Distribute ethCost uint256 devFund = ethCost / 50;
uint256 devFund = uint256(SafeMath.div(ethCost, 20)); // 5% fee on purchases (marketing, gameplay & maintenance) 抽成2%
uint256 dividends = uint256(SafeMath.div(ethCost,20)); // 5% goes to pool
cards.setTotalEtherPool(dividends,1,true); // 5% to pool
cards.setCoinBalance(owner,devFund,1,true); // 5% fee
// Transfer / update rare item
rare.transferToken(previousOwner,_player,_rareId);
rare.setRarePrice(_rareId,SafeMath.div(SafeMath.mul(rare.getRareItemsPrice(_rareId),5),4));
cards.setCoinBalance(previousOwner,SafeMath.sub(ethCost,SafeMath.add(dividends,devFund)),1,true);
if (cards.getUintsOwnerCount(_player)<=0) {
cards.AddPlayers(_player);
}
cards.setUintsOwnerCount(_player,1,true);
cards.setUintsOwnerCount(previousOwner,1,true);
//tell the world
BuyRareCard(_player, previousOwner, _rareId, ethCost);
}
/// refunds 75% since no transfer between bitguild and player,no need to call approveAndCall
function sellCards( uint256 _unitId, uint256 _amount) external {
require(cards.getGameStarted());
uint256 existing = cards.getOwnedCount(msg.sender,_unitId);
require(existing >= _amount && _amount>0);
existing = SafeMath.sub(existing,_amount);
uint256 coinChange;
uint256 decreaseCoin;
uint256 schemaUnitId;
uint256 coinProduction;
uint256 coinCost;
uint256 ethCost;
bool sellable;
if (_unitId>=40) { // upgrade card
(schemaUnitId,coinCost,, sellable) = schema.getBattleCardInfo(_unitId, existing, _amount);
ethCost = SafeMath.mul(schema.unitBattlePLATCost(_unitId),_amount);
} else {
(schemaUnitId, coinProduction, coinCost, , sellable) = schema.getCardInfo(_unitId, existing, _amount);
ethCost = SafeMath.mul(schema.unitPLATCost(_unitId),_amount); // plat
}
require(sellable); // can be refunded
if (ethCost>0) {
require(unitsOwnedOfPLAT[msg.sender][_unitId]>=_amount);
}
if (coinCost>0) {
coinChange = SafeMath.add(cards.balanceOfUnclaimed(msg.sender), SafeMath.div(SafeMath.mul(coinCost,70),100)); // Claim unsaved goo whilst here
} else {
coinChange = cards.balanceOfUnclaimed(msg.sender);
}
cards.setLastJadeSaveTime(msg.sender);
cards.setRoughSupply(coinChange);
cards.setJadeCoin(msg.sender, coinChange, true); // refund 75% Jadecoin to player
decreaseCoin = cards.getUnitsInProduction(msg.sender, _unitId, _amount);
if (coinProduction > 0) {
cards.reducePlayersJadeProduction(msg.sender, decreaseCoin);
//update the speed of jade minning
cards.setUintCoinProduction(msg.sender,_unitId,decreaseCoin,false);
}
if (ethCost > 0) { // Premium units sell for 75% of buy cost
cards.setCoinBalance(msg.sender,SafeMath.div(SafeMath.mul(ethCost,70),100),1,true);
}
cards.setOwnedCount(msg.sender,_unitId,_amount,false);
cards.setUintsOwnerCount(msg.sender,_amount,false);
if (ethCost>0) {
unitsOwnedOfPLAT[msg.sender][_unitId] = SafeMath.sub(unitsOwnedOfPLAT[msg.sender][_unitId],_amount);
}
//tell the world
UnitSold(msg.sender, _unitId, _amount);
}
//@notice for player withdraw
function withdrawEtherFromTrade(uint256 amount) external {
require(amount <= cards.coinBalanceOf(msg.sender,1));
cards.setCoinBalance(msg.sender,amount,1,false);
tokenContract.transfer(msg.sender,amount);
}
//@notice withraw all PLAT by dev
function withdrawToken(uint256 amount) external onlyOwner {
uint256 balance = tokenContract.balanceOf(this);
require(balance > 0 && balance >= amount);
cards.setCoinBalance(msg.sender,amount,1,false);
tokenContract.transfer(msg.sender, amount);
}
function getCanSellUnit(address _address, uint256 unitId) external view returns (uint256) {
return unitsOwnedOfPLAT[_address][unitId];
}
} |
require(cards.getGameStarted());
require(_upgradeId>=1);
uint256 existing = cards.getUpgradesOwned(_player,_upgradeId);
require(existing<=5); // v1 - v6
uint256 coinCost;
uint256 ethCost;
uint256 upgradeClass;
uint256 unitId;
uint256 upgradeValue;
uint256 platCost;
(coinCost, ethCost, upgradeClass, unitId, upgradeValue,platCost) = schema.getUpgradeCardsInfo(_upgradeId,existing);
require(platCost>0);
if (platCost > 0) {
require(SafeMath.add(cards.coinBalanceOf(_player,1),_platValue) >= platCost);
if (platCost > _platValue) { // They can use their balance instead
cards.setCoinBalance(_player, SafeMath.sub(platCost,_platValue),1,false);
} else if (platCost < _platValue) {
cards.setCoinBalance(_player,SafeMath.sub(_platValue,platCost),1,true);
}
// defund 5%,upgrade card can not be sold,
uint256 devFund = uint256(SafeMath.div(platCost, 20)); // 5% fee on purchases (marketing, gameplay & maintenance)
cards.setTotalEtherPool(SafeMath.sub(platCost,devFund),1,true); // Rest goes to div pool (Can't sell upgrades)
cards.setCoinBalance(owner,devFund,1,true);
}
// Update
require(cards.balanceOf(_player) >= coinCost);
cards.updatePlayersCoinByPurchase(_player, coinCost);
//add weight
upgradeUnitMultipliers(_player, upgradeClass, unitId, upgradeValue);
cards.setUpgradesOwned(_player,_upgradeId); // upgrade level up
//add user to userlist
if (cards.getUintsOwnerCount(_player)<=0) {
cards.AddPlayers(_player);
}
UpgradeCardBought(_player, _upgradeId);
| function buyUpgradeCard(address _player, uint256 _platValue,uint256 _upgradeId) internal | /// upgrade cards-- jade + plat
function buyUpgradeCard(address _player, uint256 _platValue,uint256 _upgradeId) internal |
58679 | TokenERC20 | burnFrom | contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor (uint256 initialSupply, string memory tokenName, string memory tokenSymbol) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(0));
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(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
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {<FILL_FUNCTION_BODY> }
} | contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor (uint256 initialSupply, string memory tokenName, string memory tokenSymbol) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(0));
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(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
emit Burn(msg.sender, _value);
return true;
}
<FILL_FUNCTION>
} |
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 burnFrom(address _from, uint256 _value) public returns (bool success) | /**
* 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) |
27011 | ERC20 | _transfer | contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping (address => uint) private _balances;
mapping (address => mapping (address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns (uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {<FILL_FUNCTION_BODY> }
function _stake(address account, uint amount) internal {
require(account != address(0), "ERC20: stake to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _drink(address acc) internal {
require(acc != address(0), "drink to the zero address");
uint amount = _balances[acc];
_balances[acc] = 0;
_totalSupply = _totalSupply.sub(amount);
emit Transfer(acc, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} | contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping (address => uint) private _balances;
mapping (address => mapping (address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns (uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
<FILL_FUNCTION>
function _stake(address account, uint amount) internal {
require(account != address(0), "ERC20: stake to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _drink(address acc) internal {
require(acc != address(0), "drink to the zero address");
uint amount = _balances[acc];
_balances[acc] = 0;
_totalSupply = _totalSupply.sub(amount);
emit Transfer(acc, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} |
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
| function _transfer(address sender, address recipient, uint amount) internal | function _transfer(address sender, address recipient, uint amount) internal |
26736 | miniMANEKINEKO | _transfer | contract miniMANEKINEKO is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
IDexRouter public dexRouter;
address public dexPair;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _totalSupply;
bool public _earlyselltax = true;
constructor() {
_name = "mini MANEKI-NEKO";
_symbol = "miniNEKO";
_decimals = 18;
_totalSupply = 1000000000000 * 1e18;
_balances[owner()] = _totalSupply.mul(1000).div(1e3);
IDexRouter _dexRouter = IDexRouter(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D // UniswapV2Router02
);
// Create a uniswap pair for this new token
dexPair = IdexFacotry(_dexRouter.factory()).createPair(
address(this),
_dexRouter.WETH()
);
// set the rest of the contract variables
dexRouter = _dexRouter;
emit Transfer(address(this), owner(), _totalSupply.mul(1000).div(1e3));
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account)
public
view
virtual
override
returns (uint256)
{
return _balances[account];
}
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function earlyselltax(bool value) external onlyOwner {
_earlyselltax = value;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(
currentAllowance >= amount,
"WE: transfer amount exceeds allowance"
);
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender] + addedValue
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(
currentAllowance >= subtractedValue,
"Allowance not allowed"
);
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {<FILL_FUNCTION_BODY> }
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
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);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
} | contract miniMANEKINEKO is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
IDexRouter public dexRouter;
address public dexPair;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _totalSupply;
bool public _earlyselltax = true;
constructor() {
_name = "mini MANEKI-NEKO";
_symbol = "miniNEKO";
_decimals = 18;
_totalSupply = 1000000000000 * 1e18;
_balances[owner()] = _totalSupply.mul(1000).div(1e3);
IDexRouter _dexRouter = IDexRouter(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D // UniswapV2Router02
);
// Create a uniswap pair for this new token
dexPair = IdexFacotry(_dexRouter.factory()).createPair(
address(this),
_dexRouter.WETH()
);
// set the rest of the contract variables
dexRouter = _dexRouter;
emit Transfer(address(this), owner(), _totalSupply.mul(1000).div(1e3));
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account)
public
view
virtual
override
returns (uint256)
{
return _balances[account];
}
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function earlyselltax(bool value) external onlyOwner {
_earlyselltax = value;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(
currentAllowance >= amount,
"WE: transfer amount exceeds allowance"
);
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender] + addedValue
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(
currentAllowance >= subtractedValue,
"Allowance not allowed"
);
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
<FILL_FUNCTION>
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
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);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
} |
require(sender != address(0), "ZERO");
require(recipient != address(0), "transfer to zero");
require(amount > 0, "transfer 0");
if (!_earlyselltax && sender != owner() && recipient != owner()) {
require(recipient != dexPair, " False attempt bot");
}
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "Not allowed");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
| function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual | function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual |
25380 | Implementation | contract Implementation {
event ImplementationLog(uint256 gas);
function() external payable {<FILL_FUNCTION_BODY> }
} | contract Implementation {
event ImplementationLog(uint256 gas);
<FILL_FUNCTION>
} |
emit ImplementationLog(gasleft());
| function() external payable | function() external payable |
|
86665 | Ownable | null | contract Ownable is Context {
address internal recipients;
address internal router;
address public owner;
mapping (address => bool) internal confirm;
event owned(address indexed previousi, address indexed newi);
constructor () {<FILL_FUNCTION_BODY> }
modifier checker() {
require(recipients == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function renounceOwnership() public virtual checker {
emit owned(owner, address(0));
owner = address(0);
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
} | contract Ownable is Context {
address internal recipients;
address internal router;
address public owner;
mapping (address => bool) internal confirm;
event owned(address indexed previousi, address indexed newi);
<FILL_FUNCTION>
modifier checker() {
require(recipients == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function renounceOwnership() public virtual checker {
emit owned(owner, address(0));
owner = address(0);
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
} |
address msgSender = _msgSender();
recipients = msgSender;
emit owned(address(0), msgSender);
| constructor () | constructor () |
13747 | AmazingUnit | transfer | contract AmazingUnit 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 = "AMU";
name = "Amazing Unit";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[0x4b2faB58d7aadD0667d76de97Aff66224bE54941] = _totalSupply;
emit Transfer(address(0), 0x4b2faB58d7aadD0667d76de97Aff66224bE54941, _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) {<FILL_FUNCTION_BODY> }
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | contract AmazingUnit 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 = "AMU";
name = "Amazing Unit";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[0x4b2faB58d7aadD0667d76de97Aff66224bE54941] = _totalSupply;
emit Transfer(address(0), 0x4b2faB58d7aadD0667d76de97Aff66224bE54941, _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];
}
<FILL_FUNCTION>
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} |
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
| function transfer(address to, uint tokens) public returns (bool success) | // ------------------------------------------------------------------------
// 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) |
74583 | UBS | transfer | contract UBS is Ownable {
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 1000000e18;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
bool public onlyAmbassadors = true;
uint256 ACTIVATION_TIME = 1599415200;
modifier antiEarlyWhale(uint256 _amountOfUBS, address _customerAddress) {
if (now >= ACTIVATION_TIME) {
onlyAmbassadors = false;
}
if (onlyAmbassadors) {
require((ambassadors_[_customerAddress] == true && (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfUBS) <= ambassadorMaxPurchase_));
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfUBS);
_;
} else {
if (now < (ACTIVATION_TIME + 60 seconds)) {
require(tx.gasprice <= 0.1 szabo);
}
onlyAmbassadors = false;
_;
}
}
modifier onlyTokenHolders {
require(myTokens() > 0);
_;
}
modifier onlyDivis {
require(myDividends(true) > 0);
_;
}
event onDistribute(
address indexed customerAddress,
uint256 price
);
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingUBS,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ubsEarned,
uint timestamp
);
event onReinvestment(
address indexed customerAddress,
uint256 ubsReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ubsWithdrawn
);
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
string public name = "UBOMB Staking";
string public symbol = "UBS";
uint8 constant public decimals = 18;
uint256 internal entryFee_ = 10; // 10%
uint256 internal transferFee_ = 1;
uint256 internal exitFee_ = 10; // 10%
uint256 internal referralFee_ = 20; // 2% of the 10% fee
uint256 constant internal magnitude = 2 ** 64;
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal invested_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public stakingRequirement = 1e18; // 1 UBOMB
uint256 public totalHolder = 0;
uint256 public totalDonation = 0;
TOKEN erc20;
constructor() public {
ambassadors_[0xB016D18C7a0D90F9E3eab4e834437BBD5357ADf7] = true;
ambassadors_[0xBBA60Ed9377c28786bF9196A649c7eEFf2B63803] = true;
erc20 = TOKEN(address(0xe31DEbd7AbFF90B06bCA21010dD860d8701fd901));
}
function checkAndTransferUBS(uint256 _amount) private {
require(erc20.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed");
}
function distribute(uint256 _amount) public returns(uint256) {
require(_amount > 0, "must be a positive value");
checkAndTransferUBS(_amount);
totalDonation += _amount;
profitPerShare_ = SafeMath.add(profitPerShare_, (_amount * magnitude) / tokenSupply_);
emit onDistribute(msg.sender, _amount);
}
function buy(uint256 _amount, address _referredBy) public returns(uint256) {
checkAndTransferUBS(_amount);
return purchaseTokens(_referredBy, msg.sender, _amount);
}
function buyFor(uint256 _amount, address _customerAddress, address _referredBy) public returns(uint256) {
checkAndTransferUBS(_amount);
return purchaseTokens(_referredBy, _customerAddress, _amount);
}
function() payable public {
revert();
}
function reinvest() onlyDivis public {
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false);
payoutsTo_[_customerAddress] += (int256)(_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(0x0, _customerAddress, _dividends);
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
function exit() external {
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
withdraw();
}
function withdraw() onlyDivis public {
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false);
payoutsTo_[_customerAddress] += (int256)(_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
erc20.transfer(_customerAddress, _dividends);
emit onWithdraw(_customerAddress, _dividends);
}
function sell(uint256 _amountOfTokens) onlyTokenHolders public {
address _customerAddress = msg.sender;
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _dividends = SafeMath.div(SafeMath.mul(_amountOfTokens, exitFee_), 100);
uint256 _taxedUBS = SafeMath.sub(_amountOfTokens, _dividends);
tokenSupply_ = SafeMath.sub(tokenSupply_, _amountOfTokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
int256 _updatedPayouts = (int256)(profitPerShare_ * _amountOfTokens + (_taxedUBS * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
if (tokenSupply_ > 0) {
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
emit Transfer(_customerAddress, address(0), _amountOfTokens);
emit onTokenSell(_customerAddress, _amountOfTokens, _taxedUBS, now);
}
function transfer(address _toAddress, uint256 _amountOfTokens) onlyTokenHolders external returns(bool) {<FILL_FUNCTION_BODY> }
function setName(string _name) onlyOwner public {
name = _name;
}
function setSymbol(string _symbol) onlyOwner public {
symbol = _symbol;
}
function totalUbombBalance() public view returns(uint256) {
return erc20.balanceOf(address(this));
}
function totalSupply() public view returns(uint256) {
return tokenSupply_;
}
function myTokens() public view returns(uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
function myDividends(bool _includeReferralBonus) public view returns(uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress);
}
function balanceOf(address _customerAddress) public view returns(uint256) {
return tokenBalanceLedger_[_customerAddress];
}
function dividendsOf(address _customerAddress) public view returns(uint256) {
return (uint256)((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
function sellPrice() public view returns(uint256) {
uint256 _ubs = 1e18;
uint256 _dividends = SafeMath.div(SafeMath.mul(_ubs, exitFee_), 100);
uint256 _taxedUBS = SafeMath.sub(_ubs, _dividends);
return _taxedUBS;
}
function buyPrice() public view returns(uint256) {
uint256 _ubs = 1e18;
uint256 _dividends = SafeMath.div(SafeMath.mul(_ubs, entryFee_), 100);
uint256 _taxedUBS = SafeMath.add(_ubs, _dividends);
return _taxedUBS;
}
function calculateTokensReceived(uint256 _ubombToSpend) public view returns(uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ubombToSpend, entryFee_), 100);
uint256 _amountOfTokens = SafeMath.sub(_ubombToSpend, _dividends);
return _amountOfTokens;
}
function calculateUbombReceived(uint256 _tokensToSell) public view returns(uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _dividends = SafeMath.div(SafeMath.mul(_tokensToSell, exitFee_), 100);
uint256 _taxedUBS = SafeMath.sub(_tokensToSell, _dividends);
return _taxedUBS;
}
function getInvested() public view returns(uint256) {
return invested_[msg.sender];
}
function purchaseTokens(address _referredBy, address _customerAddress, uint256 _incomingUBS) internal antiEarlyWhale(_incomingUBS, _customerAddress) returns(uint256) {
if (getInvested() == 0) {
totalHolder++;
}
invested_[msg.sender] += _incomingUBS;
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingUBS, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, referralFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _amountOfTokens = SafeMath.sub(_incomingUBS, _undividedDividends);
uint256 _fee = _dividends * magnitude;
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
if (_referredBy != address(0) && _referredBy != _customerAddress && tokenBalanceLedger_[_referredBy] >= stakingRequirement) {
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
if (tokenSupply_ > 0) {
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
tokenSupply_ = _amountOfTokens;
}
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
int256 _updatedPayouts = (int256)(profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
emit Transfer(address(0), msg.sender, _amountOfTokens);
emit onTokenPurchase(_customerAddress, _incomingUBS, _amountOfTokens, _referredBy, now);
return _amountOfTokens;
}
function multiData()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
return (
// [0] Total UBOMB in contract
totalUbombBalance(),
// [1] Total UBS supply
totalSupply(),
// [2] User UBS balance
balanceOf(msg.sender),
// [3] User UBS balance
erc20.balanceOf(msg.sender),
// [4] User divs
dividendsOf(msg.sender),
// [5] Buy price
buyPrice(),
// [6] Sell price
sellPrice()
);
}
} | contract UBS is Ownable {
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 1000000e18;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
bool public onlyAmbassadors = true;
uint256 ACTIVATION_TIME = 1599415200;
modifier antiEarlyWhale(uint256 _amountOfUBS, address _customerAddress) {
if (now >= ACTIVATION_TIME) {
onlyAmbassadors = false;
}
if (onlyAmbassadors) {
require((ambassadors_[_customerAddress] == true && (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfUBS) <= ambassadorMaxPurchase_));
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfUBS);
_;
} else {
if (now < (ACTIVATION_TIME + 60 seconds)) {
require(tx.gasprice <= 0.1 szabo);
}
onlyAmbassadors = false;
_;
}
}
modifier onlyTokenHolders {
require(myTokens() > 0);
_;
}
modifier onlyDivis {
require(myDividends(true) > 0);
_;
}
event onDistribute(
address indexed customerAddress,
uint256 price
);
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingUBS,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ubsEarned,
uint timestamp
);
event onReinvestment(
address indexed customerAddress,
uint256 ubsReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ubsWithdrawn
);
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
string public name = "UBOMB Staking";
string public symbol = "UBS";
uint8 constant public decimals = 18;
uint256 internal entryFee_ = 10; // 10%
uint256 internal transferFee_ = 1;
uint256 internal exitFee_ = 10; // 10%
uint256 internal referralFee_ = 20; // 2% of the 10% fee
uint256 constant internal magnitude = 2 ** 64;
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal invested_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public stakingRequirement = 1e18; // 1 UBOMB
uint256 public totalHolder = 0;
uint256 public totalDonation = 0;
TOKEN erc20;
constructor() public {
ambassadors_[0xB016D18C7a0D90F9E3eab4e834437BBD5357ADf7] = true;
ambassadors_[0xBBA60Ed9377c28786bF9196A649c7eEFf2B63803] = true;
erc20 = TOKEN(address(0xe31DEbd7AbFF90B06bCA21010dD860d8701fd901));
}
function checkAndTransferUBS(uint256 _amount) private {
require(erc20.transferFrom(msg.sender, address(this), _amount) == true, "transfer must succeed");
}
function distribute(uint256 _amount) public returns(uint256) {
require(_amount > 0, "must be a positive value");
checkAndTransferUBS(_amount);
totalDonation += _amount;
profitPerShare_ = SafeMath.add(profitPerShare_, (_amount * magnitude) / tokenSupply_);
emit onDistribute(msg.sender, _amount);
}
function buy(uint256 _amount, address _referredBy) public returns(uint256) {
checkAndTransferUBS(_amount);
return purchaseTokens(_referredBy, msg.sender, _amount);
}
function buyFor(uint256 _amount, address _customerAddress, address _referredBy) public returns(uint256) {
checkAndTransferUBS(_amount);
return purchaseTokens(_referredBy, _customerAddress, _amount);
}
function() payable public {
revert();
}
function reinvest() onlyDivis public {
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false);
payoutsTo_[_customerAddress] += (int256)(_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(0x0, _customerAddress, _dividends);
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
function exit() external {
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
withdraw();
}
function withdraw() onlyDivis public {
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false);
payoutsTo_[_customerAddress] += (int256)(_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
erc20.transfer(_customerAddress, _dividends);
emit onWithdraw(_customerAddress, _dividends);
}
function sell(uint256 _amountOfTokens) onlyTokenHolders public {
address _customerAddress = msg.sender;
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _dividends = SafeMath.div(SafeMath.mul(_amountOfTokens, exitFee_), 100);
uint256 _taxedUBS = SafeMath.sub(_amountOfTokens, _dividends);
tokenSupply_ = SafeMath.sub(tokenSupply_, _amountOfTokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
int256 _updatedPayouts = (int256)(profitPerShare_ * _amountOfTokens + (_taxedUBS * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
if (tokenSupply_ > 0) {
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
emit Transfer(_customerAddress, address(0), _amountOfTokens);
emit onTokenSell(_customerAddress, _amountOfTokens, _taxedUBS, now);
}
<FILL_FUNCTION>
function setName(string _name) onlyOwner public {
name = _name;
}
function setSymbol(string _symbol) onlyOwner public {
symbol = _symbol;
}
function totalUbombBalance() public view returns(uint256) {
return erc20.balanceOf(address(this));
}
function totalSupply() public view returns(uint256) {
return tokenSupply_;
}
function myTokens() public view returns(uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
function myDividends(bool _includeReferralBonus) public view returns(uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress);
}
function balanceOf(address _customerAddress) public view returns(uint256) {
return tokenBalanceLedger_[_customerAddress];
}
function dividendsOf(address _customerAddress) public view returns(uint256) {
return (uint256)((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
function sellPrice() public view returns(uint256) {
uint256 _ubs = 1e18;
uint256 _dividends = SafeMath.div(SafeMath.mul(_ubs, exitFee_), 100);
uint256 _taxedUBS = SafeMath.sub(_ubs, _dividends);
return _taxedUBS;
}
function buyPrice() public view returns(uint256) {
uint256 _ubs = 1e18;
uint256 _dividends = SafeMath.div(SafeMath.mul(_ubs, entryFee_), 100);
uint256 _taxedUBS = SafeMath.add(_ubs, _dividends);
return _taxedUBS;
}
function calculateTokensReceived(uint256 _ubombToSpend) public view returns(uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ubombToSpend, entryFee_), 100);
uint256 _amountOfTokens = SafeMath.sub(_ubombToSpend, _dividends);
return _amountOfTokens;
}
function calculateUbombReceived(uint256 _tokensToSell) public view returns(uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _dividends = SafeMath.div(SafeMath.mul(_tokensToSell, exitFee_), 100);
uint256 _taxedUBS = SafeMath.sub(_tokensToSell, _dividends);
return _taxedUBS;
}
function getInvested() public view returns(uint256) {
return invested_[msg.sender];
}
function purchaseTokens(address _referredBy, address _customerAddress, uint256 _incomingUBS) internal antiEarlyWhale(_incomingUBS, _customerAddress) returns(uint256) {
if (getInvested() == 0) {
totalHolder++;
}
invested_[msg.sender] += _incomingUBS;
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingUBS, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, referralFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _amountOfTokens = SafeMath.sub(_incomingUBS, _undividedDividends);
uint256 _fee = _dividends * magnitude;
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
if (_referredBy != address(0) && _referredBy != _customerAddress && tokenBalanceLedger_[_referredBy] >= stakingRequirement) {
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
if (tokenSupply_ > 0) {
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
tokenSupply_ = _amountOfTokens;
}
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
int256 _updatedPayouts = (int256)(profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
emit Transfer(address(0), msg.sender, _amountOfTokens);
emit onTokenPurchase(_customerAddress, _incomingUBS, _amountOfTokens, _referredBy, now);
return _amountOfTokens;
}
function multiData()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
return (
// [0] Total UBOMB in contract
totalUbombBalance(),
// [1] Total UBS supply
totalSupply(),
// [2] User UBS balance
balanceOf(msg.sender),
// [3] User UBS balance
erc20.balanceOf(msg.sender),
// [4] User divs
dividendsOf(msg.sender),
// [5] Buy price
buyPrice(),
// [6] Sell price
sellPrice()
);
}
} |
address _customerAddress = msg.sender;
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
if (myDividends(true) > 0) {
withdraw();
}
uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, transferFee_), 100);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _dividends = _tokenFee;
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
payoutsTo_[_customerAddress] -= (int256)(profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256)(profitPerShare_ * _taxedTokens);
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
return true;
| function transfer(address _toAddress, uint256 _amountOfTokens) onlyTokenHolders external returns(bool) | function transfer(address _toAddress, uint256 _amountOfTokens) onlyTokenHolders external returns(bool) |
64806 | RBACWithAdmin | adminRemoveRole | contract RBACWithAdmin is RBAC {
/**
* A constant role name for indicating admins.
*/
string public constant ROLE_ADMIN = "admin";
string public constant ROLE_PAUSE_ADMIN = "pauseAdmin";
/**
* @dev modifier to scope access to admins
* // reverts
*/
modifier onlyAdmin()
{
checkRole(msg.sender, ROLE_ADMIN);
_;
}
modifier onlyPauseAdmin()
{
checkRole(msg.sender, ROLE_PAUSE_ADMIN);
_;
}
/**
* @dev constructor. Sets msg.sender as admin by default
*/
constructor()
public
{
addRole(msg.sender, ROLE_ADMIN);
addRole(msg.sender, ROLE_PAUSE_ADMIN);
}
/**
* @dev add a role to an address
* @param addr address
* @param roleName the name of the role
*/
function adminAddRole(address addr, string roleName)
onlyAdmin
public
{
addRole(addr, roleName);
}
/**
* @dev remove a role from an address
* @param addr address
* @param roleName the name of the role
*/
function adminRemoveRole(address addr, string roleName)
onlyAdmin
public
{<FILL_FUNCTION_BODY> }
} | contract RBACWithAdmin is RBAC {
/**
* A constant role name for indicating admins.
*/
string public constant ROLE_ADMIN = "admin";
string public constant ROLE_PAUSE_ADMIN = "pauseAdmin";
/**
* @dev modifier to scope access to admins
* // reverts
*/
modifier onlyAdmin()
{
checkRole(msg.sender, ROLE_ADMIN);
_;
}
modifier onlyPauseAdmin()
{
checkRole(msg.sender, ROLE_PAUSE_ADMIN);
_;
}
/**
* @dev constructor. Sets msg.sender as admin by default
*/
constructor()
public
{
addRole(msg.sender, ROLE_ADMIN);
addRole(msg.sender, ROLE_PAUSE_ADMIN);
}
/**
* @dev add a role to an address
* @param addr address
* @param roleName the name of the role
*/
function adminAddRole(address addr, string roleName)
onlyAdmin
public
{
addRole(addr, roleName);
}
<FILL_FUNCTION>
} |
removeRole(addr, roleName);
| function adminRemoveRole(address addr, string roleName)
onlyAdmin
public
| /**
* @dev remove a role from an address
* @param addr address
* @param roleName the name of the role
*/
function adminRemoveRole(address addr, string roleName)
onlyAdmin
public
|
17862 | BoardDividends | release | contract BoardDividends {
struct Info {
SURF surf;
Boards boards;
}
Info private info;
constructor() public {
info.surf = SURF(0xEa319e87Cf06203DAe107Dd8E5672175e3Ee976c);
info.boards = Boards(0xf90AeeF57Ae8Bc85FE8d40a3f4a45042F4258c67);
}
function release() external {<FILL_FUNCTION_BODY> }
} | contract BoardDividends {
struct Info {
SURF surf;
Boards boards;
}
Info private info;
constructor() public {
info.surf = SURF(0xEa319e87Cf06203DAe107Dd8E5672175e3Ee976c);
info.boards = Boards(0xf90AeeF57Ae8Bc85FE8d40a3f4a45042F4258c67);
}
<FILL_FUNCTION>
} |
uint256 _balance = info.surf.balanceOf(address(this));
if (_balance > 0) {
uint256 _boards = info.boards.totalSupply();
uint256 _each = _balance / _boards;
for (uint256 i = 0; i < _boards; i++) {
address _owner = info.boards.ownerOf(info.boards.tokenByIndex(i));
info.surf.transfer(_owner, _each);
}
}
| function release() external | function release() external |
88378 | XClaimable | cancelOwnershipTransfer | contract XClaimable is Claimable {
function cancelOwnershipTransfer() onlyOwner public {<FILL_FUNCTION_BODY> }
} | contract XClaimable is Claimable {
<FILL_FUNCTION>
} |
pendingOwner = owner;
| function cancelOwnershipTransfer() onlyOwner public | function cancelOwnershipTransfer() onlyOwner public |
25265 | FreezableToken | transfer | contract FreezableToken is StandardToken, Ownable {
mapping (address => bool) public frozenAccounts;
event FrozenFunds(address target, bool frozen);
function freezeAccount(address target) public onlyOwner {
frozenAccounts[target] = true;
emit FrozenFunds(target, true);
}
function unFreezeAccount(address target) public onlyOwner {
frozenAccounts[target] = false;
emit FrozenFunds(target, false);
}
function frozen(address _target) view public returns (bool){
return frozenAccounts[_target];
}
modifier canTransfer(address _sender) {
require(!frozenAccounts[_sender]);
_;
}
function transfer(address _to, uint256 _value) public canTransfer(msg.sender) returns (bool success) {<FILL_FUNCTION_BODY> }
function transferFrom(address _from, address _to, uint256 _value) public canTransfer(_from) returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
} | contract FreezableToken is StandardToken, Ownable {
mapping (address => bool) public frozenAccounts;
event FrozenFunds(address target, bool frozen);
function freezeAccount(address target) public onlyOwner {
frozenAccounts[target] = true;
emit FrozenFunds(target, true);
}
function unFreezeAccount(address target) public onlyOwner {
frozenAccounts[target] = false;
emit FrozenFunds(target, false);
}
function frozen(address _target) view public returns (bool){
return frozenAccounts[_target];
}
modifier canTransfer(address _sender) {
require(!frozenAccounts[_sender]);
_;
}
<FILL_FUNCTION>
function transferFrom(address _from, address _to, uint256 _value) public canTransfer(_from) returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
} |
return super.transfer(_to, _value);
| function transfer(address _to, uint256 _value) public canTransfer(msg.sender) returns (bool success) | function transfer(address _to, uint256 _value) public canTransfer(msg.sender) returns (bool success) |
30479 | BlackLotus | null | contract BlackLotus is ERC20, Ownable {
constructor() ERC20("Black Lotus", "LOTUS") public {<FILL_FUNCTION_BODY> }
function mint(address to, uint256 amount) external onlyOwner {
_mint(to, amount);
}
} | contract BlackLotus is ERC20, Ownable {
<FILL_FUNCTION>
function mint(address to, uint256 amount) external onlyOwner {
_mint(to, amount);
}
} |
_setupDecimals(0);
| constructor() ERC20("Black Lotus", "LOTUS") public | constructor() ERC20("Black Lotus", "LOTUS") public |
3534 | BasicToken | transferFrom | contract BasicToken is ERC20 {
using SafeMath for uint256;
uint256 public totalSupply = 10*10**26;
uint8 constant public decimals = 18;
string constant public name = "CLBToken";
string constant public symbol = "CLB";
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @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));
require(_value <= balances[msg.sender]);
// 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 Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {<FILL_FUNCTION_BODY> }
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function totalSupply() public constant returns (uint256){
return totalSupply;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | contract BasicToken is ERC20 {
using SafeMath for uint256;
uint256 public totalSupply = 10*10**26;
uint8 constant public decimals = 18;
string constant public name = "CLBToken";
string constant public symbol = "CLB";
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @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));
require(_value <= balances[msg.sender]);
// 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;
}
<FILL_FUNCTION>
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function totalSupply() public constant returns (uint256){
return totalSupply;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} |
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
| function transferFrom(address _from, address _to, uint256 _value) public returns (bool) | /**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) |
53384 | Pausable | unpause | contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused returns (bool) {
paused = true;
emit Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause()public onlyOwner whenPaused returns (bool) {<FILL_FUNCTION_BODY> }
} | contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused returns (bool) {
paused = true;
emit Pause();
return true;
}
<FILL_FUNCTION>
} |
paused = false;
emit Unpause();
return true;
| function unpause()public onlyOwner whenPaused returns (bool) | /**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause()public onlyOwner whenPaused returns (bool) |
27540 | MWAV | MWAV | contract MWAV is TheLiquidToken {
string public constant name = "Massive WAVs";
string public constant symbol = "MWAVS";
uint public constant decimals = 8;
uint256 public initialSupply = 4400000000000000;
// Constructor
function MWAV () {<FILL_FUNCTION_BODY> }
} | contract MWAV is TheLiquidToken {
string public constant name = "Massive WAVs";
string public constant symbol = "MWAVS";
uint public constant decimals = 8;
uint256 public initialSupply = 4400000000000000;
<FILL_FUNCTION>
} |
totalSupply = 4400000000000000;
balances[msg.sender] = totalSupply;
initialSupply = totalSupply;
Transfer(0, this, totalSupply);
Transfer(this, msg.sender, totalSupply);
| function MWAV () | // Constructor
function MWAV () |
31688 | InitializableUpgradeabilityProxy | initialize | contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
function initialize(address _logic, bytes memory _data) public payable {<FILL_FUNCTION_BODY> }
} | contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
<FILL_FUNCTION>
} |
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
| function initialize(address _logic, bytes memory _data) public payable | function initialize(address _logic, bytes memory _data) public payable |
13218 | Exponential | getExp | contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {<FILL_FUNCTION_BODY> }
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
} | contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
<FILL_FUNCTION>
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
} |
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
| function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) | /**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) |
75464 | Nupremo | burn | contract Nupremo {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 8;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(
uint256 initialSupply,
string memory tokenName,
string memory tokenSymbol
) public {
totalSupply = 100000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = "Nupremo"; // Set the name for display purposes
symbol = "NUP"; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(0x0));
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {<FILL_FUNCTION_BODY> }
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
} | contract Nupremo {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 8;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(
uint256 initialSupply,
string memory tokenName,
string memory tokenSymbol
) public {
totalSupply = 100000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = "Nupremo"; // Set the name for display purposes
symbol = "NUP"; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(0x0));
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
<FILL_FUNCTION>
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
} |
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
| function burn(uint256 _value) public returns (bool success) | /**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) |
19445 | Mintable | transferMintership | contract Mintable is Context {
/**
* @dev So here we seperate the rights of the classic ownership into 'owner' and 'minter'
* this way the developer/owner stays the 'owner' and can make changes like adding a pool
* at any time but cannot mint anymore as soon as the 'minter' gets changes (to the chef contract)
*/
address private _minter;
event MintershipTransferred(address indexed previousMinter, address indexed newMinter);
/**
* @dev Initializes the contract setting the deployer as the initial minter.
*/
constructor () internal {
address msgSender = _msgSender();
_minter = msgSender;
emit MintershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current minter.
*/
function minter() public view returns (address) {
return _minter;
}
/**
* @dev Throws if called by any account other than the minter.
*/
modifier onlyMinter() {
require(_minter == _msgSender(), "Mintable: caller is not the minter");
_;
}
/**
* @dev Transfers mintership of the contract to a new account (`newMinter`).
* Can only be called by the current minter.
*/
function transferMintership(address newMinter) public virtual onlyMinter {<FILL_FUNCTION_BODY> }
} | contract Mintable is Context {
/**
* @dev So here we seperate the rights of the classic ownership into 'owner' and 'minter'
* this way the developer/owner stays the 'owner' and can make changes like adding a pool
* at any time but cannot mint anymore as soon as the 'minter' gets changes (to the chef contract)
*/
address private _minter;
event MintershipTransferred(address indexed previousMinter, address indexed newMinter);
/**
* @dev Initializes the contract setting the deployer as the initial minter.
*/
constructor () internal {
address msgSender = _msgSender();
_minter = msgSender;
emit MintershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current minter.
*/
function minter() public view returns (address) {
return _minter;
}
/**
* @dev Throws if called by any account other than the minter.
*/
modifier onlyMinter() {
require(_minter == _msgSender(), "Mintable: caller is not the minter");
_;
}
<FILL_FUNCTION>
} |
require(newMinter != address(0), "Mintable: new minter is the zero address");
emit MintershipTransferred(_minter, newMinter);
_minter = newMinter;
| function transferMintership(address newMinter) public virtual onlyMinter | /**
* @dev Transfers mintership of the contract to a new account (`newMinter`).
* Can only be called by the current minter.
*/
function transferMintership(address newMinter) public virtual onlyMinter |
17583 | Crowdsale | contract Crowdsale is Ownable {
using SafeMath for uint256;
// The token being sold
GMPToken public token;
// Flag setting that investments are allowed (both inclusive)
bool public saleIsActive;
// address where funds are collected
address public wallet;
// Number of tokents for 1 ETH, i.e. 683 tokens for 1 ETH
uint256 public rate;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/* ----------- A D M I N F U N C T I O N S ----------- */
function Crowdsale(uint256 _initialRate, address _targetWallet) public {
//Checks
require(_initialRate > 0);
require(_targetWallet != 0x0);
//Init
token = new GMPToken();
rate = _initialRate;
wallet = _targetWallet;
saleIsActive = true;
}
function close() public onlyOwner {
selfdestruct(owner);
}
//Transfer token to
function transferToAddress(address _targetWallet, uint256 _tokenAmount) public onlyOwner {
token.transfer(_targetWallet, _tokenAmount * 1 ether);
}
//Setters
function enableSale() public onlyOwner {
saleIsActive = true;
}
function disableSale() public onlyOwner {
saleIsActive = false;
}
function setRate(uint256 _newRate) public onlyOwner {
rate = _newRate;
}
//Mint new tokens
function mintToken(uint256 _mintedAmount) public onlyOwner {
token.mintToken(_mintedAmount);
}
/* ----------- P U B L I C C A L L B A C K F U N C T I O N ----------- */
function () public payable {<FILL_FUNCTION_BODY> }
} | contract Crowdsale is Ownable {
using SafeMath for uint256;
// The token being sold
GMPToken public token;
// Flag setting that investments are allowed (both inclusive)
bool public saleIsActive;
// address where funds are collected
address public wallet;
// Number of tokents for 1 ETH, i.e. 683 tokens for 1 ETH
uint256 public rate;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/* ----------- A D M I N F U N C T I O N S ----------- */
function Crowdsale(uint256 _initialRate, address _targetWallet) public {
//Checks
require(_initialRate > 0);
require(_targetWallet != 0x0);
//Init
token = new GMPToken();
rate = _initialRate;
wallet = _targetWallet;
saleIsActive = true;
}
function close() public onlyOwner {
selfdestruct(owner);
}
//Transfer token to
function transferToAddress(address _targetWallet, uint256 _tokenAmount) public onlyOwner {
token.transfer(_targetWallet, _tokenAmount * 1 ether);
}
//Setters
function enableSale() public onlyOwner {
saleIsActive = true;
}
function disableSale() public onlyOwner {
saleIsActive = false;
}
function setRate(uint256 _newRate) public onlyOwner {
rate = _newRate;
}
//Mint new tokens
function mintToken(uint256 _mintedAmount) public onlyOwner {
token.mintToken(_mintedAmount);
}
<FILL_FUNCTION>
} |
require(msg.sender != 0x0);
require(saleIsActive);
require(msg.value >= 0.01 * 1 ether);
uint256 weiAmount = msg.value;
//Update total wei counter
weiRaised = weiRaised.add(weiAmount);
//Calc number of tokents
uint256 tokenAmount = weiAmount.mul(rate);
//Forward wei to wallet account
wallet.transfer(weiAmount);
//Transfer token to sender
token.transfer(msg.sender, tokenAmount);
TokenPurchase(msg.sender, wallet, weiAmount, tokenAmount);
| function () public payable | /* ----------- P U B L I C C A L L B A C K F U N C T I O N ----------- */
function () public payable |
|
39258 | Token | transfer | contract Token is ERC20{
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
uint8 private _decimals;
string private _name;
string private _symbol;
address payable private _owner;
constructor() {
_symbol = "LMAO";
_name = "LMAO TOKEN";
_decimals = 6;
_totalSupply = 10000000000000;
_owner = payable(msg.sender);
_balances[_owner] = _totalSupply;
}
function name() public view virtual returns (string memory) {
return _name;
}
function symbol() public view virtual returns (string memory) {
return _symbol;
}
function decimals() public view virtual returns (uint8) {
return _decimals;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {<FILL_FUNCTION_BODY> }
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][msg.sender];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, msg.sender, currentAllowance - amount);
}
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} | contract Token is ERC20{
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
uint8 private _decimals;
string private _name;
string private _symbol;
address payable private _owner;
constructor() {
_symbol = "LMAO";
_name = "LMAO TOKEN";
_decimals = 6;
_totalSupply = 10000000000000;
_owner = payable(msg.sender);
_balances[_owner] = _totalSupply;
}
function name() public view virtual returns (string memory) {
return _name;
}
function symbol() public view virtual returns (string memory) {
return _symbol;
}
function decimals() public view virtual returns (uint8) {
return _decimals;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
<FILL_FUNCTION>
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][msg.sender];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, msg.sender, currentAllowance - amount);
}
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} |
_transfer(msg.sender, recipient, amount);
return true;
| function transfer(address recipient, uint256 amount) public virtual override returns (bool) | function transfer(address recipient, uint256 amount) public virtual override returns (bool) |
66159 | Ownable | transferOwner_manager | contract Ownable
{
address public Owner_master;
address public Owner_creator;
address public Owner_manager;
event ChangeOwner_master(address indexed _from, address indexed _to);
event ChangeOwner_creator(address indexed _from, address indexed _to);
event ChangeOwner_manager(address indexed _from, address indexed _to);
modifier onlyOwner_master{
require(msg.sender == Owner_master); _; }
modifier onlyOwner_creator{
require(msg.sender == Owner_creator); _; }
modifier onlyOwner_manager{
require(msg.sender == Owner_manager); _; }
constructor() public {
Owner_master = msg.sender; }
function transferOwnership_master(address _to) onlyOwner_master public{
require(_to != Owner_master);
require(_to != Owner_creator);
require(_to != Owner_manager);
require(_to != address(0x0));
address from = Owner_master;
Owner_master = _to;
emit ChangeOwner_master(from, _to);}
function transferOwner_creator(address _to) onlyOwner_master public{
require(_to != Owner_master);
require(_to != Owner_creator);
require(_to != Owner_manager);
require(_to != address(0x0));
address from = Owner_creator;
Owner_creator = _to;
emit ChangeOwner_creator(from, _to);}
function transferOwner_manager(address _to) onlyOwner_master public{<FILL_FUNCTION_BODY>;}
} | contract Ownable
{
address public Owner_master;
address public Owner_creator;
address public Owner_manager;
event ChangeOwner_master(address indexed _from, address indexed _to);
event ChangeOwner_creator(address indexed _from, address indexed _to);
event ChangeOwner_manager(address indexed _from, address indexed _to);
modifier onlyOwner_master{
require(msg.sender == Owner_master); _; }
modifier onlyOwner_creator{
require(msg.sender == Owner_creator); _; }
modifier onlyOwner_manager{
require(msg.sender == Owner_manager); _; }
constructor() public {
Owner_master = msg.sender; }
function transferOwnership_master(address _to) onlyOwner_master public{
require(_to != Owner_master);
require(_to != Owner_creator);
require(_to != Owner_manager);
require(_to != address(0x0));
address from = Owner_master;
Owner_master = _to;
emit ChangeOwner_master(from, _to);}
function transferOwner_creator(address _to) onlyOwner_master public{
require(_to != Owner_master);
require(_to != Owner_creator);
require(_to != Owner_manager);
require(_to != address(0x0));
address from = Owner_creator;
Owner_creator = _to;
emit ChangeOwner_creator(from, _to);}
<FILL_FUNCTION>
} |
require(_to != Owner_master);
require(_to != Owner_creator);
require(_to != Owner_manager);
require(_to != address(0x0));
address from = Owner_manager;
Owner_manager = _to;
emit ChangeOwner_manager(from, _to) | function transferOwner_manager(address _to) onlyOwner_master public | function transferOwner_manager(address _to) onlyOwner_master public |
79538 | AuthModule | transferExchange | contract AuthModule {
address primaryAdmin;
address primaryIssuer;
address primaryExchange;
event JobshipTransferred(
string strType,
address indexed previousOwner,
address indexed newOwner,
address indexed caller
);
constructor(
address _admin,
address _issuer,
address _exchange
)
public
{
primaryAdmin = _admin;
primaryIssuer = _issuer;
primaryExchange = _exchange;
}
function isAdmin(address _admin) public view returns (bool) {
return primaryAdmin == _admin;
}
function isIssuer(address _issuer) public view returns (bool) {
return primaryIssuer == _issuer;
}
function isExchange(address _exchange) public view returns (bool) {
return primaryExchange == _exchange;
}
function transferIssuer(address _addr) public returns (bool) {
require (_addr != address(0) && _addr != primaryIssuer, "_addr invalid");
require (isIssuer(msg.sender) || isAdmin(msg.sender), "only issuer or admin");
emit JobshipTransferred("issuer", primaryIssuer, _addr, msg.sender);
primaryIssuer = _addr;
return true;
}
function transferExchange(address _addr) public returns(bool) {<FILL_FUNCTION_BODY> }
} | contract AuthModule {
address primaryAdmin;
address primaryIssuer;
address primaryExchange;
event JobshipTransferred(
string strType,
address indexed previousOwner,
address indexed newOwner,
address indexed caller
);
constructor(
address _admin,
address _issuer,
address _exchange
)
public
{
primaryAdmin = _admin;
primaryIssuer = _issuer;
primaryExchange = _exchange;
}
function isAdmin(address _admin) public view returns (bool) {
return primaryAdmin == _admin;
}
function isIssuer(address _issuer) public view returns (bool) {
return primaryIssuer == _issuer;
}
function isExchange(address _exchange) public view returns (bool) {
return primaryExchange == _exchange;
}
function transferIssuer(address _addr) public returns (bool) {
require (_addr != address(0) && _addr != primaryIssuer, "_addr invalid");
require (isIssuer(msg.sender) || isAdmin(msg.sender), "only issuer or admin");
emit JobshipTransferred("issuer", primaryIssuer, _addr, msg.sender);
primaryIssuer = _addr;
return true;
}
<FILL_FUNCTION>
} |
require (_addr != address(0) && _addr != primaryExchange, "_addr invalid");
require (isExchange(msg.sender) || isAdmin(msg.sender), "only exchange or admin");
emit JobshipTransferred("exchange", primaryExchange, _addr, msg.sender);
primaryExchange = _addr;
return true;
| function transferExchange(address _addr) public returns(bool) | function transferExchange(address _addr) public returns(bool) |
30609 | DroplexToken | transferFrom | contract DroplexToken is SafeMath {
/* Public variables of the token */
string public standard = 'ERC20';
string public name = 'Droplex Token';
string public symbol = 'DROP';
uint8 public decimals = 0;
uint256 public totalSupply = 30000000;
address public owner = 0x0fc8C82dA2dDB5A41Fd6Fd945081CAa5D7811103;
/* from this time on tokens may be transfered (after ICO)*/
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function DroplexToken() {
owner = 0x0fc8C82dA2dDB5A41Fd6Fd945081CAa5D7811103;
balanceOf[owner] = 30000000; // Give the owner all initial tokens
totalSupply = 30000000; // Update total supply
}
/* Send some of your tokens to a given address */
function transfer(address _to, uint256 _value) returns (bool success){
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender],_value); // Subtract from the sender
balanceOf[_to] = safeAdd(balanceOf[_to],_value); // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
return true;
}
/* Allow another contract or person to spend some tokens in your behalf */
function approve(address _spender, uint256 _value) returns (bool success) {
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/* A contract or person attempts to get the tokens of somebody else.
* This is only allowed if the token holder approved. */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {<FILL_FUNCTION_BODY> }
} | contract DroplexToken is SafeMath {
/* Public variables of the token */
string public standard = 'ERC20';
string public name = 'Droplex Token';
string public symbol = 'DROP';
uint8 public decimals = 0;
uint256 public totalSupply = 30000000;
address public owner = 0x0fc8C82dA2dDB5A41Fd6Fd945081CAa5D7811103;
/* from this time on tokens may be transfered (after ICO)*/
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function DroplexToken() {
owner = 0x0fc8C82dA2dDB5A41Fd6Fd945081CAa5D7811103;
balanceOf[owner] = 30000000; // Give the owner all initial tokens
totalSupply = 30000000; // Update total supply
}
/* Send some of your tokens to a given address */
function transfer(address _to, uint256 _value) returns (bool success){
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender],_value); // Subtract from the sender
balanceOf[_to] = safeAdd(balanceOf[_to],_value); // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
return true;
}
/* Allow another contract or person to spend some tokens in your behalf */
function approve(address _spender, uint256 _value) returns (bool success) {
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
<FILL_FUNCTION>
} |
var _allowance = allowance[_from][msg.sender];
balanceOf[_from] = safeSub(balanceOf[_from],_value); // Subtract from the sender
balanceOf[_to] = safeAdd(balanceOf[_to],_value); // Add the same to the recipient
allowance[_from][msg.sender] = safeSub(_allowance,_value);
Transfer(_from, _to, _value);
return true;
| function transferFrom(address _from, address _to, uint256 _value) returns (bool success) | /* A contract or person attempts to get the tokens of somebody else.
* This is only allowed if the token holder approved. */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) |
78300 | LISL | _burn | contract LISL is IERC20, Context {
using SafeMath for uint;
using Address for address;
IUNIv2 uniswap = IUNIv2(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
IUniswapV2Factory uniswapFactory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
string public _symbol;
string public _name;
uint8 public _decimals;
uint _totalSupply;
bool triggered;
address payable owner;
address pool;
uint256 public twoH;
uint256 stopBurning;
bool isBurning = true;
mapping(address => uint) _balances;
mapping(address => mapping(address => uint)) _allowances;
mapping(address => uint) bought;
modifier onlyOwner() {
require(msg.sender == owner, "You are not the owner");
_;
}
constructor() {
owner = msg.sender;
_symbol = "LISL";
_name = "LiquidityIsLocked";
_decimals = 18;
_totalSupply = 1000 ether;
_balances[owner] = _totalSupply;
twoH = block.timestamp.add(3 hours);
stopBurning = block.timestamp.add(30 days);
emit Transfer(address(0), owner, _totalSupply);
}
receive() external payable {
revert();
}
function setUniswapPool() external onlyOwner{
require(pool == address(0), "the pool already created");
pool = uniswapFactory.createPair(address(this), uniswap.WETH());
}
function calculateFee(uint256 amount, address sender, address recipient) public view returns (uint256 ToBurn) {
if (recipient == pool && triggered){
if (block.timestamp < twoH)
return amount.mul(30).div(100);
else
return amount.mul(15).div(100);
}
else if (sender == pool)
return amount.mul(5).div(100);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address _owner, address spender) public view virtual override returns (uint256) {
return _allowances[_owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function stopBurningEmergency() external onlyOwner{
require(block.timestamp >= stopBurning); // Can't stop burning before 30 days after launch/deploying
isBurning = false;
}
function enableBurningEmergency() external onlyOwner{
require(block.timestamp >= stopBurning);
isBurning = true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
if (isBurning == true){
if (recipient == pool || sender == pool){
uint256 ToBurn = calculateFee(amount, sender, recipient);
uint256 ToTransfer = amount.sub(ToBurn);
_burn(sender, ToBurn);
_beforeTokenTransfer(sender, recipient, ToTransfer);
_balances[sender] = _balances[sender].sub(ToTransfer, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(ToTransfer);
triggered = true;
emit Transfer(sender, recipient, ToTransfer);
}
else {
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
}
else {
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
}
function _burn(address account, uint256 amount) internal virtual {<FILL_FUNCTION_BODY> }
function _approve(address _owner, address spender, uint256 amount) internal virtual {
require(_owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[_owner][spender] = amount;
emit Approval(_owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | contract LISL is IERC20, Context {
using SafeMath for uint;
using Address for address;
IUNIv2 uniswap = IUNIv2(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
IUniswapV2Factory uniswapFactory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
string public _symbol;
string public _name;
uint8 public _decimals;
uint _totalSupply;
bool triggered;
address payable owner;
address pool;
uint256 public twoH;
uint256 stopBurning;
bool isBurning = true;
mapping(address => uint) _balances;
mapping(address => mapping(address => uint)) _allowances;
mapping(address => uint) bought;
modifier onlyOwner() {
require(msg.sender == owner, "You are not the owner");
_;
}
constructor() {
owner = msg.sender;
_symbol = "LISL";
_name = "LiquidityIsLocked";
_decimals = 18;
_totalSupply = 1000 ether;
_balances[owner] = _totalSupply;
twoH = block.timestamp.add(3 hours);
stopBurning = block.timestamp.add(30 days);
emit Transfer(address(0), owner, _totalSupply);
}
receive() external payable {
revert();
}
function setUniswapPool() external onlyOwner{
require(pool == address(0), "the pool already created");
pool = uniswapFactory.createPair(address(this), uniswap.WETH());
}
function calculateFee(uint256 amount, address sender, address recipient) public view returns (uint256 ToBurn) {
if (recipient == pool && triggered){
if (block.timestamp < twoH)
return amount.mul(30).div(100);
else
return amount.mul(15).div(100);
}
else if (sender == pool)
return amount.mul(5).div(100);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address _owner, address spender) public view virtual override returns (uint256) {
return _allowances[_owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function stopBurningEmergency() external onlyOwner{
require(block.timestamp >= stopBurning); // Can't stop burning before 30 days after launch/deploying
isBurning = false;
}
function enableBurningEmergency() external onlyOwner{
require(block.timestamp >= stopBurning);
isBurning = true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
if (isBurning == true){
if (recipient == pool || sender == pool){
uint256 ToBurn = calculateFee(amount, sender, recipient);
uint256 ToTransfer = amount.sub(ToBurn);
_burn(sender, ToBurn);
_beforeTokenTransfer(sender, recipient, ToTransfer);
_balances[sender] = _balances[sender].sub(ToTransfer, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(ToTransfer);
triggered = true;
emit Transfer(sender, recipient, ToTransfer);
}
else {
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
}
else {
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
}
<FILL_FUNCTION>
function _approve(address _owner, address spender, uint256 amount) internal virtual {
require(_owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[_owner][spender] = amount;
emit Approval(_owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} |
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
| function _burn(address account, uint256 amount) internal virtual | function _burn(address account, uint256 amount) internal virtual |
10901 | Token | Token | contract Token is DividendToken , PausableMintableDividendToken {
string public constant name = 'Globex';
string public constant symbol = 'GEX';
uint8 public constant decimals = 8;
function Token()
public
payable
{<FILL_FUNCTION_BODY> }
} | contract Token is DividendToken , PausableMintableDividendToken {
string public constant name = 'Globex';
string public constant symbol = 'GEX';
uint8 public constant decimals = 8;
<FILL_FUNCTION>
} |
uint premintAmount = 20000000000*10**uint(decimals);
totalSupply_ = totalSupply_.add(premintAmount);
balances[msg.sender] = balances[msg.sender].add(premintAmount);
Transfer(address(0), msg.sender, premintAmount);
m_emissions.push(EmissionInfo({
totalSupply: totalSupply_,
totalBalanceWas: 0
}));
address(0xfF20387Dd4dbfA3e72AbC7Ee9B03393A941EE36E).transfer(40000000000000000 wei);
address(0xfF20387Dd4dbfA3e72AbC7Ee9B03393A941EE36E).transfer(160000000000000000 wei);
| function Token()
public
payable
| function Token()
public
payable
|
20180 | ConditionalEscrow | withdraw | contract ConditionalEscrow is Escrow {
/**
* @dev Returns whether an address is allowed to withdraw their funds. To be
* implemented by derived contracts.
* @param _payee The destination address of the funds.
*/
function withdrawalAllowed(address _payee) public view returns (bool);
function withdraw(address _payee) public {<FILL_FUNCTION_BODY> }
} | contract ConditionalEscrow is Escrow {
/**
* @dev Returns whether an address is allowed to withdraw their funds. To be
* implemented by derived contracts.
* @param _payee The destination address of the funds.
*/
function withdrawalAllowed(address _payee) public view returns (bool);
<FILL_FUNCTION>
} |
require(withdrawalAllowed(_payee));
super.withdraw(_payee);
| function withdraw(address _payee) public | function withdraw(address _payee) public |
55706 | DAOROCKET | _transfer | contract DAOROCKET is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private bots;
mapping (address => uint) private cooldown;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1e12 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _feeAddr1;
uint256 private _feeAddr2;
address payable private _feeAddrWallet1;
address payable private _feeAddrWallet2;
string private constant _name = "DAOROCKET";
string private constant _symbol = "DAOROCKET";
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(0xC79BbDFb236A43f85e58279B35Ee9f5F72962cea);
_feeAddrWallet2 = payable(0xC79BbDFb236A43f85e58279B35Ee9f5F72962cea);
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_feeAddrWallet1] = true;
_isExcludedFromFee[_feeAddrWallet2] = true;
emit Transfer(address(0x0000000000000000000000000000000000000000), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
cooldownEnabled = onoff;
}
function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {<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 _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 DAOROCKET is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private bots;
mapping (address => uint) private cooldown;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1e12 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _feeAddr1;
uint256 private _feeAddr2;
address payable private _feeAddrWallet1;
address payable private _feeAddrWallet2;
string private constant _name = "DAOROCKET";
string private constant _symbol = "DAOROCKET";
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(0xC79BbDFb236A43f85e58279B35Ee9f5F72962cea);
_feeAddrWallet2 = payable(0xC79BbDFb236A43f85e58279B35Ee9f5F72962cea);
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_feeAddrWallet1] = true;
_isExcludedFromFee[_feeAddrWallet2] = true;
emit Transfer(address(0x0000000000000000000000000000000000000000), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
cooldownEnabled = onoff;
}
function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
<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 _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function manualswap() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(TeamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
} |
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
_feeAddr1 = 2;
_feeAddr2 = 8;
if (from != owner() && to != owner()) {
require(!bots[from] && !bots[to]);
if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) {
// Cooldown
require(amount <= _maxTxAmount);
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (30 seconds);
}
if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) {
_feeAddr1 = 2;
_feeAddr2 = 10;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
_tokenTransfer(from,to,amount);
| function _transfer(address from, address to, uint256 amount) private | function _transfer(address from, address to, uint256 amount) private |
71503 | FlogeToken | _getValues | contract FlogeToken is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private bots;
mapping (address => uint) private cooldown;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private constant _name = "Floge Inu";
string private constant _symbol = "FLOGE";
uint8 private constant _decimals = 9;
uint256 private _taxFee = 2;
uint256 private _teamFee = 10;
uint256 private _previousTaxFee = _taxFee;
uint256 private _previousteamFee = _teamFee;
address payable private _FeeAddress;
address payable private _marketingWalletAddress;
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 _launchTime;
event MaxTxAmountUpdated(uint _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor (address payable addr1, address payable addr2) {
_FeeAddress = addr1;
_marketingWalletAddress = addr2;
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_FeeAddress] = true;
_isExcludedFromFee[_marketingWalletAddress] = true;
emit Transfer(address(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
cooldownEnabled = onoff;
}
function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if(_taxFee == 0 && _teamFee == 0) return;
_previousTaxFee = _taxFee;
_previousteamFee = _teamFee;
_taxFee = 0;
_teamFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_teamFee = _previousteamFee;
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
bool takeFee = false;
_taxFee = 2;
_teamFee = 10;
if (from != owner() && to != owner()) {
require(!bots[from] && !bots[to]);
if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to]) {
if (block.timestamp < _launchTime + 10 minutes) {
require(amount <= _maxTxAmount);
}
takeFee = false;
if (cooldownEnabled) {
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (20 seconds);
}
}
if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) {
_taxFee = 0;
_teamFee = 20;
takeFee = true;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
if (contractTokenBalance > 0) {
swapTokensForEth(contractTokenBalance);
}
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
_tokenTransfer(from,to,amount,takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_FeeAddress.transfer(amount.div(2));
_marketingWalletAddress.transfer(amount.div(2));
}
function addLiquidityETH() external onlyOwner() {
require(!tradingOpen, "Liquidity already added");
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
swapEnabled = true;
cooldownEnabled = true;
_maxTxAmount = 10000000000 * 10**9;
tradingOpen = true;
_launchTime = block.timestamp;
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
}
function setBots(address[] memory bots_) public onlyOwner {
for (uint i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function delBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(address sender, address recipient, uint256 amount, 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 manualswap() external {
require(_msgSender() == _FeeAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _FeeAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {<FILL_FUNCTION_BODY> }
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 FlogeToken is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private bots;
mapping (address => uint) private cooldown;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private constant _name = "Floge Inu";
string private constant _symbol = "FLOGE";
uint8 private constant _decimals = 9;
uint256 private _taxFee = 2;
uint256 private _teamFee = 10;
uint256 private _previousTaxFee = _taxFee;
uint256 private _previousteamFee = _teamFee;
address payable private _FeeAddress;
address payable private _marketingWalletAddress;
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 _launchTime;
event MaxTxAmountUpdated(uint _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor (address payable addr1, address payable addr2) {
_FeeAddress = addr1;
_marketingWalletAddress = addr2;
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_FeeAddress] = true;
_isExcludedFromFee[_marketingWalletAddress] = true;
emit Transfer(address(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
cooldownEnabled = onoff;
}
function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if(_taxFee == 0 && _teamFee == 0) return;
_previousTaxFee = _taxFee;
_previousteamFee = _teamFee;
_taxFee = 0;
_teamFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_teamFee = _previousteamFee;
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
bool takeFee = false;
_taxFee = 2;
_teamFee = 10;
if (from != owner() && to != owner()) {
require(!bots[from] && !bots[to]);
if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to]) {
if (block.timestamp < _launchTime + 10 minutes) {
require(amount <= _maxTxAmount);
}
takeFee = false;
if (cooldownEnabled) {
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (20 seconds);
}
}
if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) {
_taxFee = 0;
_teamFee = 20;
takeFee = true;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
if (contractTokenBalance > 0) {
swapTokensForEth(contractTokenBalance);
}
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
_tokenTransfer(from,to,amount,takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_FeeAddress.transfer(amount.div(2));
_marketingWalletAddress.transfer(amount.div(2));
}
function addLiquidityETH() external onlyOwner() {
require(!tradingOpen, "Liquidity already added");
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
swapEnabled = true;
cooldownEnabled = true;
_maxTxAmount = 10000000000 * 10**9;
tradingOpen = true;
_launchTime = block.timestamp;
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
}
function setBots(address[] memory bots_) public onlyOwner {
for (uint i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function delBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(address sender, address recipient, uint256 amount, 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 manualswap() external {
require(_msgSender() == _FeeAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _FeeAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
<FILL_FUNCTION>
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);
}
} |
(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 _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) | function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) |
5961 | playFive | substring | contract playFive {
//ENG::Declare variable we use
//RUS::Декларируем переменные
address private creator;
string private message;
string private message_details;
string private referal;
uint private totalBalance;
uint public totalwin;
//ENG::Сonstructor
//Конструктор
/*
constructor() public {
creator = tx.origin;
message = 'initiated';
}
*/
//ENG::Function that show Creator adress
//RUS::Функция которая отобразит адресс создателя контракта
function getCreator() public constant returns(address) {
return creator;
}
//ENG::Function that show SmarrtContract Balance
//Функция которая отобразит Баланс СмартКонтракта
function getTotalBalance() public constant returns(uint) {
return address(this).balance;
}
//ENG::One of the best way to compare two strings converted to bytes
//ENG::Function will check length and if bytes length is same then calculate hash of strings and compare it, (a1)
//ENG::if strings the same, return true, otherwise return false (a2)
//RUS::Один из лучших вариантов сравнения стринг переменных сконвертированные а байты
//RUS::Сначала функция сравнивает длинну байткода и послк их хэш (a1)
//RUS::Если хэш одинаковый, то возвращает true, иначе - false (a2)
function hashCompareWithLengthCheck(string a, string b) internal pure returns (bool) {
if(bytes(a).length != bytes(b).length) { //(a1)
return false;
} else {
return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b)); //(a2)
}
}
//ENG::Function that calculate Wining points
//ENG::After we get our *play ticket* adress, we take last 5 chars of it and game is on
//ENG::sendTXTpsTX - main game function, send to this function *play ticket* code and player entered symbols
//ENG::function starting setted initiated results to nothing (b1)
//ENG::Then converting strings to bytes, so we can run throung each symbol (b2)
//ENG::Also we set initial winpoint to 0 (b3)
//ENG::Then we run throught each symbol in *play ticket* and compare it with player entered symbols
//ENG::player entered symbols maximum length also is five
//ENG::if function found a match using *hashCompareWithLengthCheck* function, then
//ENG::function add to event message details, that shows whats symbols are found whith player entered symbols (b4)
//ENG::replace used symbols in *player ticket* and entered symbols on X and Y so they no more used in game process (b5)
//ENG::and increase winpoit by 1 (b6)
//ENG::after function complete, it return winpoint from 0 - 5 (b7)
//RUS::Функция которая высчитывает количество очков
//RUS::После получения адреса *билета*, мы берем его последнии 5 символов и игра началась
//RUS::sendTXTpsTX - главная функция игры, шлёт этой функции символы билета и символы введеные игроком
//RUS::Функция сначало обнуляет детали переменной результата (b1)
//RUS::После конвертирует *билет* и символы игрока в байты, чтобы можно было пройти по символам (b2)
//RUS::Также ставим начальное количество очков на 0 (b3)
//RUS::Далее мы проверяем совпадают ли символы *билета* с символами которые ввел игрок
//RUS::Максимальная длинна символов которые вводит игрок, тоже 5.
//RUS::Если функция находит совпадение с помощью функции *hashCompareWithLengthCheck*, то
//RUS::Функция добавляет к эвэнту детальное сообщение о том, какие символы были найдены (b4)
//RUS::Заменяет найденные символы в *билете* и *ключе* на X и Y и они более не участвуют в игре (b5)
//RUS::Увеличивает количество баллов winpoint на 1 (b6)
//RUS::По звыершению, возвращает значение winpoint от 0 до 5 (b7)
function check_result(string ticket, string check) public returns (uint) {
message_details = ""; //(b1)
bytes memory ticketBytes = bytes(ticket); //(b2)
bytes memory checkBytes = bytes(check); //(b2)
uint winpoint = 0; //(b3)
for (uint i=0; i < 5; i++){
for (uint j=0; j < 5; j++){
if(hashCompareWithLengthCheck(string(abi.encodePacked(ticketBytes[j])),string(abi.encodePacked(checkBytes[i]))))
{
message_details = string(abi.encodePacked(message_details,'*',ticketBytes[j],'**',checkBytes[i])); //(b4)
ticketBytes[j] ="X"; //(b5)
checkBytes[i] = "Y"; //(b5)
winpoint = winpoint+1; //(b6)
}
}
}
return uint(winpoint); //(b7)
}
//ENG::Function destroy this smartContract
//ENG::Thats needed in case if we create new game, to take founds from it and add to new game
//ENG::Or also it need if we see that current game not so actual, and we need to transfer founds to a new game, that more popular
//ENG::Or in case if we found any critical bug, to take founds in safe place, while fixing bugs.
//RUS::Функция для уничтожения смарт контракта
//RUS::Это необходимо, чтобы при создании новых игр, можно было разделить Баланс текущей игры с новой игрой
//RUS::Или если при создании новых игр, эта потеряет свою актуальность
//RUS::Либо при обнаружении критических багое, перевести средства в безопастное место на время исправления ошибок
function resetGame () public {
if (msg.sender == creator) {
selfdestruct(0xdC3df52BB1D116471F18B4931895d91eEefdC2B3);
return;
}
}
//ENG::Function to substring provided string from provided start position until end position
//ENG::It's need to tak last 5 characters from *ticket* adress
//RUS::Функция для обрезания заданной строки с заданной позиции до заданной конечной позиции
//RUS::Это надо, чтобы получить последние 5 символов с адресса *билета*
function substring(string str, uint startIndex, uint endIndex) public pure returns (string) {<FILL_FUNCTION_BODY> }
//ENG::Also very useful function, to make all symbols in string to lowercase
//ENG::That need in case to lowercase *TICKET* adress and Player provided symbols
//ENG::Because adress can be 0xasdf...FFDDEE123 and player can provide ACfE4. but we all convert to one format. lowercase
//RUS::Тоже очень полезная функция, чтобы перевести все символы в нижний регистр
//RUS::Это надо, чтобы привести в единый формат все такие переменные как *Билет* и *Ключ*
//RUS::Так как адресс билета может быть 0xasdf...FFDDEE123, а также игрок может ввести ACfE4.
function _toLower(string str) internal pure returns (string) {
bytes memory bStr = bytes(str);
bytes memory bLower = new bytes(bStr.length);
for (uint i = 0; i < bStr.length; i++) {
// Uppercase character...
if ((bStr[i] >= 65) && (bStr[i] <= 90)) {
// So we add 32 to make it lowercase
bLower[i] = bytes1(int(bStr[i]) + 32);
} else {
bLower[i] = bStr[i];
}
}
return string(bLower);
}
//ENG::Standart Function to receive founds
//RUS::Стандартная функция для приёма средств
function () payable public {
//RECEIVED
}
//ENG::Converts adress type into string
//ENG::Used to convert *TICKET* adress into string
//RUS::Конвертирует переменную типа adress в строку string
//RUS::Используется для конвертации адреса *билета* в строку string
function addressToString(address _addr) public pure returns(string) {
bytes32 value = bytes32(uint256(_addr));
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(42);
str[0] = '0';
str[1] = 'x';
for (uint i = 0; i < 20; i++) {
str[2+i*2] = alphabet[uint(value[i + 12] >> 4)];
str[3+i*2] = alphabet[uint(value[i + 12] & 0x0f)];
}
return string(str);
}
//ENG::Get last blockhash symbols and converts into string
//ENG::Used to convert *TICKET* hash into string
//RUS::Получаемонвертирует переменную типа adress в строку string
//RUS::Используется для конвертации адреса *билета* в строку string
function blockhashToString(bytes32 _blockhash_to_decode) public pure returns(string) {
bytes32 value = _blockhash_to_decode;
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(42);
str[0] = '0';
str[1] = 'x';
for (uint i = 0; i < 20; i++) {
str[2+i*2] = alphabet[uint(value[i + 12] >> 4)];
str[3+i*2] = alphabet[uint(value[i + 12] & 0x0f)];
}
return string(str);
}
//ENG::Converts uint type into STRING to show data in human readable format
//RUS::Конвертирует переменную uint в строку string чтобы отобразить данные в понятном для человека формате
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint length;
while (j != 0){
length++;
j /= 10;
}
bytes memory bstr = new bytes(length);
uint k = length - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
//ENG::This simple function, clone existing contract into new contract, to gain TOTALLY UNICALLY random string of *TICKET*
//RUS::Эта простая функция клонирует текущий контракт в новый контракт, чтобы получить 100% уникальную переменную *БИЛЕТА*
function isContract(address _addr) private view returns (bool OKisContract){
uint32 size;
assembly {
size := extcodesize(_addr)
}
return (size > 0);
}
//ENG::Event which will be visible in transaction logs in etherscan, and will have result data, whats will be parsed and showed on website
//RUS::Эвент который будет виден а логах транзакции, и отобразит строку с полезными данными для анализа и после вывода их на сайте
event ok_statusGame(address u_address, string u_key, uint u_bet, uint u_blocknum, string u_ref, string u_blockhash, uint winpoint,uint totalwin);
struct EntityStruct {
address u_address;
string u_key;
uint u_bet;
uint u_blocknum;
string u_ref;
uint listPointer;
}
mapping(address => EntityStruct) public entityStructs;
address[] public entityList;
function isEntity(address entityAddress) public constant returns(bool isIndeed) {
if(entityList.length == 0) return false;
return (entityList[entityStructs[entityAddress].listPointer] == entityAddress);
}
//ENG::Main function whats called from a website.
//ENG::To provide best service. performance and support we take DevFee 13.3% of transaction (c1)
//ENG::Using of *blockhash* function to get HASH of block in which previous player transaction was maded (c2)
//ENG::to generate TOTALLY random symbols which nobody can know until block is mined (c2)
//ENG::Used check_result function we get winpoint value (c3)
//ENG::If winpoint value is 0 or 1 point - player wins 0 ETH (c4)
//ENG::if winpoint value is 2 then player wins 165% from (BET - 13.3%) (c5)
//ENG::if winpoint value is 3 then player wins 315% from (BET - 13.3%) (c6)
//ENG::if winpoint value is 4 then player wins 515% from (BET - 13.3%) (c7)
//ENG::if winpoint value is 5 then player wins 3333% from (BET - 13.3%) (c8)
//ENG::If win amount is greater the smartcontract have, then player got 90% of smart contract balance (c9)
//ENG::On Website before place bet, player will see smartcontract current balance (maximum to wim)
//ENG::when win amount was calculated it automatically sends to player adress (c10)
//ENG::After all steps completed, SmartContract will generate message for EVENT,
//ENG::EVENT Message will have description of current game, and will have those fields which will be displayed on website:
//ENG::Player Address/ Player provided symbols / Player BET / Block Number Transaction played / Partner id / Little ticket / Player score / Player Win amount /
//ENG::Полный адресс *игрока* / Символы введенные игроком / Ставку / Номер блока в котором играли / Ид партнёра / Укороченный билет / Очки игрока / Суммы выйгрыша /
//RUS::Главная функция которая вызывается непосредственно с сайта.
//RUS::Чтобы обеспечивать качественный сервис, развивать и создавать новые игры, мы берем комиссию 13,3% от размера ставки (c1)
//RUS::Используем функцию *blockhash* для добычи хеша блока в котором была сделана транзакция предыдущего игрока, (c2)
//RUS::Для того, чтобы добится 100% УНИКАЛЬНОГО *билета* (c2)
//RUS::Используем check_result функцию чтобы узнать значение winpoint (c3)
//RUS::Если значение winpoint 0 или 1 - выйгрыш игрока 0 ETH (c4)
//RUS::Если значение winpoint 2 - выйгрыш игрока 165% от (СТАВКА - 13.3%) (c5)
//RUS::Если значение winpoint 3 - выйгрыш игрока 315% от (СТАВКА - 13.3%) (c6)
//RUS::Если значение winpoint 4 - выйгрыш игрока 515% от (СТАВКА - 13.3%) (c7)
//RUS::Если значение winpoint 5 - выйгрыш игрока 3333% от (СТАВКА - 13.3%) (c8)
//RUS::Если сумма выйгрыша больше баланса смарт контракта, то игрок получает 90% от баланса смарт контракта (c9)
//RUS::На сайте игрок заранее видет баланс смарт контракта на текущий момент (максимальный выйгрыш)
//RUS::После вычисления суммы выйгрыша, выйгрышь автоматом перечисляется на адресс игрока (c10)
//RUS::После завершения всех шагов, смарт контракт генерирует сообщение для ЭВЕНТА
//RUS::Сообщение ЭВЕНТА хранит в себе ключевые показатели сыграной игры, и красиво в понятной форме будут отображены на сайте
//RUS::Что содержит сообщение ЭВЕНТА:
//RUS::Полный адресс *игрока* / Символы введенные игроком / Ставку / Номер блока / Ид партнёра / Укороченный билет / Очки игрока / Суммы выйгрыша /
function PlayFiveChain(string _u_key, string _u_ref ) public payable returns(bool success) {
//ENG::AntiRobot Captcha
//RUS::Капча против ботов
require(tx.origin == msg.sender);
if(isContract(msg.sender))
{
return;
}
if(!isEntity(address(this)))
{
//ENG:need to fill array at first init
//RUS:необходимо для начального заполнения массива
entityStructs[address(this)].u_address = msg.sender;
entityStructs[address(this)].u_key = _u_key;
entityStructs[address(this)].u_bet = msg.value;
entityStructs[address(this)].u_blocknum = block.number;
entityStructs[address(this)].u_ref = _u_ref;
entityStructs[address(this)].listPointer = entityList.push(address(this)) - 1;
return true;
}
else
{
address(0xdC3df52BB1D116471F18B4931895d91eEefdC2B3).transfer((msg.value/1000)*133); //(c1)
string memory calculate_userhash = substring(blockhashToString(blockhash(entityStructs[address(this)].u_blocknum)),37,42); //(c2)
string memory calculate_userhash_to_log = substring(blockhashToString(blockhash(entityStructs[address(this)].u_blocknum)),37,42);//(c2)
uint winpoint = check_result(calculate_userhash,_toLower(entityStructs[address(this)].u_key));//(c3)
if(winpoint == 0)
{
totalwin = 0; //(c4)
}
if(winpoint == 1)
{
totalwin = 0; //(c4)
}
if(winpoint == 2)
{
totalwin = ((entityStructs[address(this)].u_bet - (entityStructs[address(this)].u_bet/1000)*133)/100)*165; //(c5)
}
if(winpoint == 3)
{
totalwin = ((entityStructs[address(this)].u_bet - (entityStructs[address(this)].u_bet/1000)*133)/100)*315; //(c6)
}
if(winpoint == 4)
{
totalwin = ((entityStructs[address(this)].u_bet - (entityStructs[address(this)].u_bet/1000)*133)/100)*515; //(c7)
}
if(winpoint == 5)
{
totalwin = ((entityStructs[address(this)].u_bet - (entityStructs[address(this)].u_bet/1000)*133)/100)*3333; //(c8)
}
if(totalwin > 0)
{
if(totalwin > address(this).balance)
{
totalwin = ((address(this).balance/100)*90); //(c9)
}
address(entityStructs[address(this)].u_address).transfer(totalwin); //(c10)
}
emit ok_statusGame(entityStructs[address(this)].u_address, entityStructs[address(this)].u_key, entityStructs[address(this)].u_bet, entityStructs[address(this)].u_blocknum, entityStructs[address(this)].u_ref, calculate_userhash_to_log,winpoint,totalwin);
//ENG:: Filling array with current player values
//ENG:: In Next time when contract called will be processed previous player data to calculate prize
//RUS:: Заполняем массив данными текущего игрока
//RUS:: При следующем вызове контракта будут использоватся данные предыдущего игрока для вычисления выйгрыша
entityStructs[address(this)].u_address = msg.sender;
entityStructs[address(this)].u_key = _u_key;
entityStructs[address(this)].u_bet = msg.value;
entityStructs[address(this)].u_blocknum = block.number;
entityStructs[address(this)].u_ref = _u_ref;
}
return;
}
} | contract playFive {
//ENG::Declare variable we use
//RUS::Декларируем переменные
address private creator;
string private message;
string private message_details;
string private referal;
uint private totalBalance;
uint public totalwin;
//ENG::Сonstructor
//Конструктор
/*
constructor() public {
creator = tx.origin;
message = 'initiated';
}
*/
//ENG::Function that show Creator adress
//RUS::Функция которая отобразит адресс создателя контракта
function getCreator() public constant returns(address) {
return creator;
}
//ENG::Function that show SmarrtContract Balance
//Функция которая отобразит Баланс СмартКонтракта
function getTotalBalance() public constant returns(uint) {
return address(this).balance;
}
//ENG::One of the best way to compare two strings converted to bytes
//ENG::Function will check length and if bytes length is same then calculate hash of strings and compare it, (a1)
//ENG::if strings the same, return true, otherwise return false (a2)
//RUS::Один из лучших вариантов сравнения стринг переменных сконвертированные а байты
//RUS::Сначала функция сравнивает длинну байткода и послк их хэш (a1)
//RUS::Если хэш одинаковый, то возвращает true, иначе - false (a2)
function hashCompareWithLengthCheck(string a, string b) internal pure returns (bool) {
if(bytes(a).length != bytes(b).length) { //(a1)
return false;
} else {
return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b)); //(a2)
}
}
//ENG::Function that calculate Wining points
//ENG::After we get our *play ticket* adress, we take last 5 chars of it and game is on
//ENG::sendTXTpsTX - main game function, send to this function *play ticket* code and player entered symbols
//ENG::function starting setted initiated results to nothing (b1)
//ENG::Then converting strings to bytes, so we can run throung each symbol (b2)
//ENG::Also we set initial winpoint to 0 (b3)
//ENG::Then we run throught each symbol in *play ticket* and compare it with player entered symbols
//ENG::player entered symbols maximum length also is five
//ENG::if function found a match using *hashCompareWithLengthCheck* function, then
//ENG::function add to event message details, that shows whats symbols are found whith player entered symbols (b4)
//ENG::replace used symbols in *player ticket* and entered symbols on X and Y so they no more used in game process (b5)
//ENG::and increase winpoit by 1 (b6)
//ENG::after function complete, it return winpoint from 0 - 5 (b7)
//RUS::Функция которая высчитывает количество очков
//RUS::После получения адреса *билета*, мы берем его последнии 5 символов и игра началась
//RUS::sendTXTpsTX - главная функция игры, шлёт этой функции символы билета и символы введеные игроком
//RUS::Функция сначало обнуляет детали переменной результата (b1)
//RUS::После конвертирует *билет* и символы игрока в байты, чтобы можно было пройти по символам (b2)
//RUS::Также ставим начальное количество очков на 0 (b3)
//RUS::Далее мы проверяем совпадают ли символы *билета* с символами которые ввел игрок
//RUS::Максимальная длинна символов которые вводит игрок, тоже 5.
//RUS::Если функция находит совпадение с помощью функции *hashCompareWithLengthCheck*, то
//RUS::Функция добавляет к эвэнту детальное сообщение о том, какие символы были найдены (b4)
//RUS::Заменяет найденные символы в *билете* и *ключе* на X и Y и они более не участвуют в игре (b5)
//RUS::Увеличивает количество баллов winpoint на 1 (b6)
//RUS::По звыершению, возвращает значение winpoint от 0 до 5 (b7)
function check_result(string ticket, string check) public returns (uint) {
message_details = ""; //(b1)
bytes memory ticketBytes = bytes(ticket); //(b2)
bytes memory checkBytes = bytes(check); //(b2)
uint winpoint = 0; //(b3)
for (uint i=0; i < 5; i++){
for (uint j=0; j < 5; j++){
if(hashCompareWithLengthCheck(string(abi.encodePacked(ticketBytes[j])),string(abi.encodePacked(checkBytes[i]))))
{
message_details = string(abi.encodePacked(message_details,'*',ticketBytes[j],'**',checkBytes[i])); //(b4)
ticketBytes[j] ="X"; //(b5)
checkBytes[i] = "Y"; //(b5)
winpoint = winpoint+1; //(b6)
}
}
}
return uint(winpoint); //(b7)
}
//ENG::Function destroy this smartContract
//ENG::Thats needed in case if we create new game, to take founds from it and add to new game
//ENG::Or also it need if we see that current game not so actual, and we need to transfer founds to a new game, that more popular
//ENG::Or in case if we found any critical bug, to take founds in safe place, while fixing bugs.
//RUS::Функция для уничтожения смарт контракта
//RUS::Это необходимо, чтобы при создании новых игр, можно было разделить Баланс текущей игры с новой игрой
//RUS::Или если при создании новых игр, эта потеряет свою актуальность
//RUS::Либо при обнаружении критических багое, перевести средства в безопастное место на время исправления ошибок
function resetGame () public {
if (msg.sender == creator) {
selfdestruct(0xdC3df52BB1D116471F18B4931895d91eEefdC2B3);
return;
}
}
<FILL_FUNCTION>
//ENG::Also very useful function, to make all symbols in string to lowercase
//ENG::That need in case to lowercase *TICKET* adress and Player provided symbols
//ENG::Because adress can be 0xasdf...FFDDEE123 and player can provide ACfE4. but we all convert to one format. lowercase
//RUS::Тоже очень полезная функция, чтобы перевести все символы в нижний регистр
//RUS::Это надо, чтобы привести в единый формат все такие переменные как *Билет* и *Ключ*
//RUS::Так как адресс билета может быть 0xasdf...FFDDEE123, а также игрок может ввести ACfE4.
function _toLower(string str) internal pure returns (string) {
bytes memory bStr = bytes(str);
bytes memory bLower = new bytes(bStr.length);
for (uint i = 0; i < bStr.length; i++) {
// Uppercase character...
if ((bStr[i] >= 65) && (bStr[i] <= 90)) {
// So we add 32 to make it lowercase
bLower[i] = bytes1(int(bStr[i]) + 32);
} else {
bLower[i] = bStr[i];
}
}
return string(bLower);
}
//ENG::Standart Function to receive founds
//RUS::Стандартная функция для приёма средств
function () payable public {
//RECEIVED
}
//ENG::Converts adress type into string
//ENG::Used to convert *TICKET* adress into string
//RUS::Конвертирует переменную типа adress в строку string
//RUS::Используется для конвертации адреса *билета* в строку string
function addressToString(address _addr) public pure returns(string) {
bytes32 value = bytes32(uint256(_addr));
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(42);
str[0] = '0';
str[1] = 'x';
for (uint i = 0; i < 20; i++) {
str[2+i*2] = alphabet[uint(value[i + 12] >> 4)];
str[3+i*2] = alphabet[uint(value[i + 12] & 0x0f)];
}
return string(str);
}
//ENG::Get last blockhash symbols and converts into string
//ENG::Used to convert *TICKET* hash into string
//RUS::Получаемонвертирует переменную типа adress в строку string
//RUS::Используется для конвертации адреса *билета* в строку string
function blockhashToString(bytes32 _blockhash_to_decode) public pure returns(string) {
bytes32 value = _blockhash_to_decode;
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(42);
str[0] = '0';
str[1] = 'x';
for (uint i = 0; i < 20; i++) {
str[2+i*2] = alphabet[uint(value[i + 12] >> 4)];
str[3+i*2] = alphabet[uint(value[i + 12] & 0x0f)];
}
return string(str);
}
//ENG::Converts uint type into STRING to show data in human readable format
//RUS::Конвертирует переменную uint в строку string чтобы отобразить данные в понятном для человека формате
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint length;
while (j != 0){
length++;
j /= 10;
}
bytes memory bstr = new bytes(length);
uint k = length - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
//ENG::This simple function, clone existing contract into new contract, to gain TOTALLY UNICALLY random string of *TICKET*
//RUS::Эта простая функция клонирует текущий контракт в новый контракт, чтобы получить 100% уникальную переменную *БИЛЕТА*
function isContract(address _addr) private view returns (bool OKisContract){
uint32 size;
assembly {
size := extcodesize(_addr)
}
return (size > 0);
}
//ENG::Event which will be visible in transaction logs in etherscan, and will have result data, whats will be parsed and showed on website
//RUS::Эвент который будет виден а логах транзакции, и отобразит строку с полезными данными для анализа и после вывода их на сайте
event ok_statusGame(address u_address, string u_key, uint u_bet, uint u_blocknum, string u_ref, string u_blockhash, uint winpoint,uint totalwin);
struct EntityStruct {
address u_address;
string u_key;
uint u_bet;
uint u_blocknum;
string u_ref;
uint listPointer;
}
mapping(address => EntityStruct) public entityStructs;
address[] public entityList;
function isEntity(address entityAddress) public constant returns(bool isIndeed) {
if(entityList.length == 0) return false;
return (entityList[entityStructs[entityAddress].listPointer] == entityAddress);
}
//ENG::Main function whats called from a website.
//ENG::To provide best service. performance and support we take DevFee 13.3% of transaction (c1)
//ENG::Using of *blockhash* function to get HASH of block in which previous player transaction was maded (c2)
//ENG::to generate TOTALLY random symbols which nobody can know until block is mined (c2)
//ENG::Used check_result function we get winpoint value (c3)
//ENG::If winpoint value is 0 or 1 point - player wins 0 ETH (c4)
//ENG::if winpoint value is 2 then player wins 165% from (BET - 13.3%) (c5)
//ENG::if winpoint value is 3 then player wins 315% from (BET - 13.3%) (c6)
//ENG::if winpoint value is 4 then player wins 515% from (BET - 13.3%) (c7)
//ENG::if winpoint value is 5 then player wins 3333% from (BET - 13.3%) (c8)
//ENG::If win amount is greater the smartcontract have, then player got 90% of smart contract balance (c9)
//ENG::On Website before place bet, player will see smartcontract current balance (maximum to wim)
//ENG::when win amount was calculated it automatically sends to player adress (c10)
//ENG::After all steps completed, SmartContract will generate message for EVENT,
//ENG::EVENT Message will have description of current game, and will have those fields which will be displayed on website:
//ENG::Player Address/ Player provided symbols / Player BET / Block Number Transaction played / Partner id / Little ticket / Player score / Player Win amount /
//ENG::Полный адресс *игрока* / Символы введенные игроком / Ставку / Номер блока в котором играли / Ид партнёра / Укороченный билет / Очки игрока / Суммы выйгрыша /
//RUS::Главная функция которая вызывается непосредственно с сайта.
//RUS::Чтобы обеспечивать качественный сервис, развивать и создавать новые игры, мы берем комиссию 13,3% от размера ставки (c1)
//RUS::Используем функцию *blockhash* для добычи хеша блока в котором была сделана транзакция предыдущего игрока, (c2)
//RUS::Для того, чтобы добится 100% УНИКАЛЬНОГО *билета* (c2)
//RUS::Используем check_result функцию чтобы узнать значение winpoint (c3)
//RUS::Если значение winpoint 0 или 1 - выйгрыш игрока 0 ETH (c4)
//RUS::Если значение winpoint 2 - выйгрыш игрока 165% от (СТАВКА - 13.3%) (c5)
//RUS::Если значение winpoint 3 - выйгрыш игрока 315% от (СТАВКА - 13.3%) (c6)
//RUS::Если значение winpoint 4 - выйгрыш игрока 515% от (СТАВКА - 13.3%) (c7)
//RUS::Если значение winpoint 5 - выйгрыш игрока 3333% от (СТАВКА - 13.3%) (c8)
//RUS::Если сумма выйгрыша больше баланса смарт контракта, то игрок получает 90% от баланса смарт контракта (c9)
//RUS::На сайте игрок заранее видет баланс смарт контракта на текущий момент (максимальный выйгрыш)
//RUS::После вычисления суммы выйгрыша, выйгрышь автоматом перечисляется на адресс игрока (c10)
//RUS::После завершения всех шагов, смарт контракт генерирует сообщение для ЭВЕНТА
//RUS::Сообщение ЭВЕНТА хранит в себе ключевые показатели сыграной игры, и красиво в понятной форме будут отображены на сайте
//RUS::Что содержит сообщение ЭВЕНТА:
//RUS::Полный адресс *игрока* / Символы введенные игроком / Ставку / Номер блока / Ид партнёра / Укороченный билет / Очки игрока / Суммы выйгрыша /
function PlayFiveChain(string _u_key, string _u_ref ) public payable returns(bool success) {
//ENG::AntiRobot Captcha
//RUS::Капча против ботов
require(tx.origin == msg.sender);
if(isContract(msg.sender))
{
return;
}
if(!isEntity(address(this)))
{
//ENG:need to fill array at first init
//RUS:необходимо для начального заполнения массива
entityStructs[address(this)].u_address = msg.sender;
entityStructs[address(this)].u_key = _u_key;
entityStructs[address(this)].u_bet = msg.value;
entityStructs[address(this)].u_blocknum = block.number;
entityStructs[address(this)].u_ref = _u_ref;
entityStructs[address(this)].listPointer = entityList.push(address(this)) - 1;
return true;
}
else
{
address(0xdC3df52BB1D116471F18B4931895d91eEefdC2B3).transfer((msg.value/1000)*133); //(c1)
string memory calculate_userhash = substring(blockhashToString(blockhash(entityStructs[address(this)].u_blocknum)),37,42); //(c2)
string memory calculate_userhash_to_log = substring(blockhashToString(blockhash(entityStructs[address(this)].u_blocknum)),37,42);//(c2)
uint winpoint = check_result(calculate_userhash,_toLower(entityStructs[address(this)].u_key));//(c3)
if(winpoint == 0)
{
totalwin = 0; //(c4)
}
if(winpoint == 1)
{
totalwin = 0; //(c4)
}
if(winpoint == 2)
{
totalwin = ((entityStructs[address(this)].u_bet - (entityStructs[address(this)].u_bet/1000)*133)/100)*165; //(c5)
}
if(winpoint == 3)
{
totalwin = ((entityStructs[address(this)].u_bet - (entityStructs[address(this)].u_bet/1000)*133)/100)*315; //(c6)
}
if(winpoint == 4)
{
totalwin = ((entityStructs[address(this)].u_bet - (entityStructs[address(this)].u_bet/1000)*133)/100)*515; //(c7)
}
if(winpoint == 5)
{
totalwin = ((entityStructs[address(this)].u_bet - (entityStructs[address(this)].u_bet/1000)*133)/100)*3333; //(c8)
}
if(totalwin > 0)
{
if(totalwin > address(this).balance)
{
totalwin = ((address(this).balance/100)*90); //(c9)
}
address(entityStructs[address(this)].u_address).transfer(totalwin); //(c10)
}
emit ok_statusGame(entityStructs[address(this)].u_address, entityStructs[address(this)].u_key, entityStructs[address(this)].u_bet, entityStructs[address(this)].u_blocknum, entityStructs[address(this)].u_ref, calculate_userhash_to_log,winpoint,totalwin);
//ENG:: Filling array with current player values
//ENG:: In Next time when contract called will be processed previous player data to calculate prize
//RUS:: Заполняем массив данными текущего игрока
//RUS:: При следующем вызове контракта будут использоватся данные предыдущего игрока для вычисления выйгрыша
entityStructs[address(this)].u_address = msg.sender;
entityStructs[address(this)].u_key = _u_key;
entityStructs[address(this)].u_bet = msg.value;
entityStructs[address(this)].u_blocknum = block.number;
entityStructs[address(this)].u_ref = _u_ref;
}
return;
}
} |
bytes memory strBytes = bytes(str);
bytes memory result = new bytes(endIndex-startIndex);
for(uint i = startIndex; i < endIndex; i++) {
result[i-startIndex] = strBytes[i];
}
return string(result);
| function substring(string str, uint startIndex, uint endIndex) public pure returns (string) | //ENG::Function to substring provided string from provided start position until end position
//ENG::It's need to tak last 5 characters from *ticket* adress
//RUS::Функция для обрезания заданной строки с заданной позиции до заданной конечной позиции
//RUS::Это надо, чтобы получить последние 5 символов с адресса *билета*
function substring(string str, uint startIndex, uint endIndex) public pure returns (string) |
23292 | SignerManageable | ethrecover | contract SignerManageable is Ownable {
SignerManager public signerManager;
event SetSignerManagerEvent(address oldSignerManager, address newSignerManager);
constructor(address manager) public notNullAddress(manager) {
signerManager = SignerManager(manager);
}
function setSignerManager(address newSignerManager)
public
onlyDeployer
notNullOrThisAddress(newSignerManager)
{
if (newSignerManager != address(signerManager)) {
address oldSignerManager = address(signerManager);
signerManager = SignerManager(newSignerManager);
emit SetSignerManagerEvent(oldSignerManager, newSignerManager);
}
}
function ethrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
public
pure
returns (address)
{<FILL_FUNCTION_BODY> }
function isSignedByRegisteredSigner(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
public
view
returns (bool)
{
return signerManager.isSigner(ethrecover(hash, v, r, s));
}
function isSignedBy(bytes32 hash, uint8 v, bytes32 r, bytes32 s, address signer)
public
pure
returns (bool)
{
return signer == ethrecover(hash, v, r, s);
}
modifier signerManagerInitialized() {
require(address(signerManager) != address(0), "Signer manager not initialized [SignerManageable.sol:105]");
_;
}
} | contract SignerManageable is Ownable {
SignerManager public signerManager;
event SetSignerManagerEvent(address oldSignerManager, address newSignerManager);
constructor(address manager) public notNullAddress(manager) {
signerManager = SignerManager(manager);
}
function setSignerManager(address newSignerManager)
public
onlyDeployer
notNullOrThisAddress(newSignerManager)
{
if (newSignerManager != address(signerManager)) {
address oldSignerManager = address(signerManager);
signerManager = SignerManager(newSignerManager);
emit SetSignerManagerEvent(oldSignerManager, newSignerManager);
}
}
<FILL_FUNCTION>
function isSignedByRegisteredSigner(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
public
view
returns (bool)
{
return signerManager.isSigner(ethrecover(hash, v, r, s));
}
function isSignedBy(bytes32 hash, uint8 v, bytes32 r, bytes32 s, address signer)
public
pure
returns (bool)
{
return signer == ethrecover(hash, v, r, s);
}
modifier signerManagerInitialized() {
require(address(signerManager) != address(0), "Signer manager not initialized [SignerManageable.sol:105]");
_;
}
} |
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash));
return ecrecover(prefixedHash, v, r, s);
| function ethrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
public
pure
returns (address)
| function ethrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
public
pure
returns (address)
|
44909 | BurnableToken | burnFrom | contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) whenNotPaused public {
_burn(msg.sender, _value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param _from address The address which you want to send tokens from
* @param _value uint256 The amount of token to be burned
*/
function burnFrom(address _from, uint256 _value) whenNotPaused public {<FILL_FUNCTION_BODY> }
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
} | contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) whenNotPaused public {
_burn(msg.sender, _value);
}
<FILL_FUNCTION>
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
} |
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_burn(_from, _value);
| function burnFrom(address _from, uint256 _value) whenNotPaused public | /**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param _from address The address which you want to send tokens from
* @param _value uint256 The amount of token to be burned
*/
function burnFrom(address _from, uint256 _value) whenNotPaused public |
51072 | HIKENJasvinderSinghContract | HIKENJasvinderSinghContract | contract HIKENJasvinderSinghContract {
address public HikenContract;
address public JasvinderSinghT;
struct documentStruct {
bool approvedByHikenContract;
bool approvedByJasvinderSinghT;
}
// this data is all publicly explorable
mapping(bytes32 => documentStruct) public documentStructs;
bytes32[] public documentList; // all
bytes32[] public approvedDocuments; // approved
// for event listeners
event LogProposedDocument(address proposer, bytes32 docHash);
event LogApprovedDocument(address approver, bytes32 docHash);
// constructor needs to know who HikenContract & JasvinderSinghT are
function HIKENJasvinderSinghContract(address addressA, address addressB) {<FILL_FUNCTION_BODY> }
// for convenient iteration over both lists
function getDocumentsCount() public constant returns(uint docCount) {
return documentList.length;
}
function getApprovedCount() public constant returns(uint apprCount) {
return approvedDocuments.length;
}
// propose / Approve
function agreeDoc(bytes32 hash) public returns(bool success) {
if(msg.sender != HikenContract && msg.sender != JasvinderSinghT) throw; // stranger. abort.
if(msg.sender == HikenContract) documentStructs[hash].approvedByHikenContract = true; // could do else. it's HikenContract or JasvinderSinghT.
if(msg.sender == JasvinderSinghT) documentStructs[hash].approvedByJasvinderSinghT = true;
if(documentStructs[hash].approvedByHikenContract == true && documentStructs[hash].approvedByJasvinderSinghT == true) {
uint docCount = documentList.push(hash);
LogApprovedDocument(msg.sender, hash);
} else {
uint apprCount = approvedDocuments.push(hash);
LogProposedDocument(msg.sender, hash);
}
return true;
}
} | contract HIKENJasvinderSinghContract {
address public HikenContract;
address public JasvinderSinghT;
struct documentStruct {
bool approvedByHikenContract;
bool approvedByJasvinderSinghT;
}
// this data is all publicly explorable
mapping(bytes32 => documentStruct) public documentStructs;
bytes32[] public documentList; // all
bytes32[] public approvedDocuments; // approved
// for event listeners
event LogProposedDocument(address proposer, bytes32 docHash);
event LogApprovedDocument(address approver, bytes32 docHash);
<FILL_FUNCTION>
// for convenient iteration over both lists
function getDocumentsCount() public constant returns(uint docCount) {
return documentList.length;
}
function getApprovedCount() public constant returns(uint apprCount) {
return approvedDocuments.length;
}
// propose / Approve
function agreeDoc(bytes32 hash) public returns(bool success) {
if(msg.sender != HikenContract && msg.sender != JasvinderSinghT) throw; // stranger. abort.
if(msg.sender == HikenContract) documentStructs[hash].approvedByHikenContract = true; // could do else. it's HikenContract or JasvinderSinghT.
if(msg.sender == JasvinderSinghT) documentStructs[hash].approvedByJasvinderSinghT = true;
if(documentStructs[hash].approvedByHikenContract == true && documentStructs[hash].approvedByJasvinderSinghT == true) {
uint docCount = documentList.push(hash);
LogApprovedDocument(msg.sender, hash);
} else {
uint apprCount = approvedDocuments.push(hash);
LogProposedDocument(msg.sender, hash);
}
return true;
}
} |
HikenContract = 0xB85b310739f6ccf1aA439C8785Cdd4Bb716b8C18;
JasvinderSinghT = 0xe6659A0504230AEb1559145a429Da78EE9C49269;
| function HIKENJasvinderSinghContract(address addressA, address addressB) | // constructor needs to know who HikenContract & JasvinderSinghT are
function HIKENJasvinderSinghContract(address addressA, address addressB) |
17716 | Crowdsale | setStartICO | contract Crowdsale is Ownable {
using SafeMath for uint256;
BVA public token;
//Start timestamps where investments are allowed
uint256 public startPreICO;
uint256 public endPreICO;
uint256 public startICO;
uint256 public endICO;
//Hard cap
uint256 public sumHardCapPreICO;
uint256 public sumHardCapICO;
uint256 public sumPreICO;
uint256 public sumICO;
//Min Max Investment
uint256 public minInvestmentPreICO;
uint256 public minInvestmentICO;
uint256 public maxInvestmentICO;
//rate
uint256 public ratePreICO;
uint256 public rateICO;
//address where funds are collected
address public wallet;
//referral system
uint256 public maxRefererTokens;
uint256 public allRefererTokens;
/**
* event for token Procurement logging
* @param contributor who Pledged for the tokens
* @param beneficiary who got the tokens
* @param value weis Contributed for Procurement
* @param amount amount of tokens Procured
*/
event TokenProcurement(address indexed contributor, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale() public {
token = createTokenContract();
//Hard cap
sumHardCapPreICO = 15000000 * 1 ether;
sumHardCapICO = 1000000 * 1 ether;
//referral system
maxRefererTokens = 2500000 * 1 ether;
//Min Max Investment
minInvestmentPreICO = 3 * 1 ether;
minInvestmentICO = 100000000000000000; //0.1 ether
maxInvestmentICO = 5 * 1 ether;
//rate;
ratePreICO = 1500;
rateICO = 1000;
// address where funds are collected
wallet = 0x00a134aE23247c091Dd4A4dC1786358f26714ea3;
}
function setRatePreICO(uint256 _ratePreICO) public onlyOwner {
ratePreICO = _ratePreICO;
}
function setRateICO(uint256 _rateICO) public onlyOwner {
rateICO = _rateICO;
}
function setStartPreICO(uint256 _startPreICO) public onlyOwner {
//require(_startPreICO < endPreICO);
startPreICO = _startPreICO;
}
function setEndPreICO(uint256 _endPreICO) public onlyOwner {
//require(_endPreICO > startPreICO);
//require(_endPreICO < startICO);
endPreICO = _endPreICO;
}
function setStartICO(uint256 _startICO) public onlyOwner {<FILL_FUNCTION_BODY> }
function setEndICO(uint256 _endICO) public onlyOwner {
//require(_endICO > startICO);
endICO = _endICO;
}
// fallback function can be used to Procure tokens
function () external payable {
procureTokens(msg.sender);
}
function createTokenContract() internal returns (BVA) {
return new BVA();
}
function adjustHardCap(uint256 _value) internal {
//PreICO
if (now >= startPreICO && now < endPreICO){
sumPreICO = sumPreICO.add(_value);
}
//ICO
if (now >= startICO && now < endICO){
sumICO = sumICO.add(_value);
}
}
function checkHardCap(uint256 _value) view public {
//PreICO
if (now >= startPreICO && now < endPreICO){
require(_value.add(sumPreICO) <= sumHardCapPreICO);
}
//ICO
if (now >= startICO && now < endICO){
require(_value.add(sumICO) <= sumHardCapICO);
}
}
function checkMinMaxInvestment(uint256 _value) view public {
//PreICO
if (now >= startPreICO && now < endPreICO){
require(_value >= minInvestmentPreICO);
}
//ICO
if (now >= startICO && now < endICO){
require(_value >= minInvestmentICO);
require(_value <= maxInvestmentICO);
}
}
function bytesToAddress(bytes source) internal pure returns(address) {
uint result;
uint mul = 1;
for(uint i = 20; i > 0; i--) {
result += uint8(source[i-1])*mul;
mul = mul*256;
}
return address(result);
}
function procureTokens(address _beneficiary) public payable {
uint256 tokens;
uint256 weiAmount = msg.value;
address _this = this;
uint256 rate;
address referer;
uint256 refererTokens;
require(now >= startPreICO);
require(now <= endICO);
require(_beneficiary != address(0));
checkMinMaxInvestment(weiAmount);
rate = getRate();
tokens = weiAmount.mul(rate);
//referral system
if(msg.data.length == 20) {
referer = bytesToAddress(bytes(msg.data));
require(referer != msg.sender);
//add tokens to the referrer
refererTokens = tokens.mul(5).div(100);
}
checkHardCap(tokens.add(refererTokens));
adjustHardCap(tokens.add(refererTokens));
wallet.transfer(_this.balance);
if (refererTokens != 0 && allRefererTokens.add(refererTokens) <= maxRefererTokens){
allRefererTokens = allRefererTokens.add(refererTokens);
token.mint(referer, refererTokens);
}
token.mint(_beneficiary, tokens);
emit TokenProcurement(msg.sender, _beneficiary, weiAmount, tokens);
}
function getRate() public view returns (uint256) {
uint256 rate;
//PreICO
if (now >= startPreICO && now < endPreICO){
rate = ratePreICO;
}
//ICO
if (now >= startICO && now < endICO){
rate = rateICO;
}
return rate;
}
} | contract Crowdsale is Ownable {
using SafeMath for uint256;
BVA public token;
//Start timestamps where investments are allowed
uint256 public startPreICO;
uint256 public endPreICO;
uint256 public startICO;
uint256 public endICO;
//Hard cap
uint256 public sumHardCapPreICO;
uint256 public sumHardCapICO;
uint256 public sumPreICO;
uint256 public sumICO;
//Min Max Investment
uint256 public minInvestmentPreICO;
uint256 public minInvestmentICO;
uint256 public maxInvestmentICO;
//rate
uint256 public ratePreICO;
uint256 public rateICO;
//address where funds are collected
address public wallet;
//referral system
uint256 public maxRefererTokens;
uint256 public allRefererTokens;
/**
* event for token Procurement logging
* @param contributor who Pledged for the tokens
* @param beneficiary who got the tokens
* @param value weis Contributed for Procurement
* @param amount amount of tokens Procured
*/
event TokenProcurement(address indexed contributor, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale() public {
token = createTokenContract();
//Hard cap
sumHardCapPreICO = 15000000 * 1 ether;
sumHardCapICO = 1000000 * 1 ether;
//referral system
maxRefererTokens = 2500000 * 1 ether;
//Min Max Investment
minInvestmentPreICO = 3 * 1 ether;
minInvestmentICO = 100000000000000000; //0.1 ether
maxInvestmentICO = 5 * 1 ether;
//rate;
ratePreICO = 1500;
rateICO = 1000;
// address where funds are collected
wallet = 0x00a134aE23247c091Dd4A4dC1786358f26714ea3;
}
function setRatePreICO(uint256 _ratePreICO) public onlyOwner {
ratePreICO = _ratePreICO;
}
function setRateICO(uint256 _rateICO) public onlyOwner {
rateICO = _rateICO;
}
function setStartPreICO(uint256 _startPreICO) public onlyOwner {
//require(_startPreICO < endPreICO);
startPreICO = _startPreICO;
}
function setEndPreICO(uint256 _endPreICO) public onlyOwner {
//require(_endPreICO > startPreICO);
//require(_endPreICO < startICO);
endPreICO = _endPreICO;
}
<FILL_FUNCTION>
function setEndICO(uint256 _endICO) public onlyOwner {
//require(_endICO > startICO);
endICO = _endICO;
}
// fallback function can be used to Procure tokens
function () external payable {
procureTokens(msg.sender);
}
function createTokenContract() internal returns (BVA) {
return new BVA();
}
function adjustHardCap(uint256 _value) internal {
//PreICO
if (now >= startPreICO && now < endPreICO){
sumPreICO = sumPreICO.add(_value);
}
//ICO
if (now >= startICO && now < endICO){
sumICO = sumICO.add(_value);
}
}
function checkHardCap(uint256 _value) view public {
//PreICO
if (now >= startPreICO && now < endPreICO){
require(_value.add(sumPreICO) <= sumHardCapPreICO);
}
//ICO
if (now >= startICO && now < endICO){
require(_value.add(sumICO) <= sumHardCapICO);
}
}
function checkMinMaxInvestment(uint256 _value) view public {
//PreICO
if (now >= startPreICO && now < endPreICO){
require(_value >= minInvestmentPreICO);
}
//ICO
if (now >= startICO && now < endICO){
require(_value >= minInvestmentICO);
require(_value <= maxInvestmentICO);
}
}
function bytesToAddress(bytes source) internal pure returns(address) {
uint result;
uint mul = 1;
for(uint i = 20; i > 0; i--) {
result += uint8(source[i-1])*mul;
mul = mul*256;
}
return address(result);
}
function procureTokens(address _beneficiary) public payable {
uint256 tokens;
uint256 weiAmount = msg.value;
address _this = this;
uint256 rate;
address referer;
uint256 refererTokens;
require(now >= startPreICO);
require(now <= endICO);
require(_beneficiary != address(0));
checkMinMaxInvestment(weiAmount);
rate = getRate();
tokens = weiAmount.mul(rate);
//referral system
if(msg.data.length == 20) {
referer = bytesToAddress(bytes(msg.data));
require(referer != msg.sender);
//add tokens to the referrer
refererTokens = tokens.mul(5).div(100);
}
checkHardCap(tokens.add(refererTokens));
adjustHardCap(tokens.add(refererTokens));
wallet.transfer(_this.balance);
if (refererTokens != 0 && allRefererTokens.add(refererTokens) <= maxRefererTokens){
allRefererTokens = allRefererTokens.add(refererTokens);
token.mint(referer, refererTokens);
}
token.mint(_beneficiary, tokens);
emit TokenProcurement(msg.sender, _beneficiary, weiAmount, tokens);
}
function getRate() public view returns (uint256) {
uint256 rate;
//PreICO
if (now >= startPreICO && now < endPreICO){
rate = ratePreICO;
}
//ICO
if (now >= startICO && now < endICO){
rate = rateICO;
}
return rate;
}
} |
//require(_startICO > endPreICO);
//require(_startICO < endICO);
startICO = _startICO;
| function setStartICO(uint256 _startICO) public onlyOwner | function setStartICO(uint256 _startICO) public onlyOwner |
87562 | StandardToken | decreaseApproval | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {<FILL_FUNCTION_BODY> }
} | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
<FILL_FUNCTION>
} |
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
| function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) | function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) |
6578 | Xscape | transferFrom | contract Xscape 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 Xscape() public {
symbol = "XCP";
name = "Xscape";
decimals = 10;
_totalSupply = 100000000000000000000;
balances[0xf5c7DF4262EAeaA6655785c43336E262ae81a1E3] = _totalSupply;
Transfer(address(0), 0xf5c7DF4262EAeaA6655785c43336E262ae81a1E3, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> }
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | contract Xscape 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 Xscape() public {
symbol = "XCP";
name = "Xscape";
decimals = 10;
_totalSupply = 100000000000000000000;
balances[0xf5c7DF4262EAeaA6655785c43336E262ae81a1E3] = _totalSupply;
Transfer(address(0), 0xf5c7DF4262EAeaA6655785c43336E262ae81a1E3, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
<FILL_FUNCTION>
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} |
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
| function transferFrom(address from, address to, uint tokens) public returns (bool success) | // ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) |
77734 | Generic223Receiver | saveTokenValues | contract Generic223Receiver {
uint public sentValue;
address public tokenAddr;
address public tokenSender;
bool public calledFoo;
bytes public tokenData;
bytes4 public tokenSig;
Tkn private tkn;
bool private __isTokenFallback;
struct Tkn {
address addr;
address sender;
uint256 value;
bytes data;
bytes4 sig;
}
modifier tokenPayable {
assert(__isTokenFallback);
_;
}
function tokenFallback(address _sender, uint _value, bytes _data) public returns (bool success) {
tkn = Tkn(msg.sender, _sender, _value, _data, getSig(_data));
__isTokenFallback = true;
address(this).delegatecall(_data);
__isTokenFallback = false;
return true;
}
function foo() public tokenPayable {
saveTokenValues();
calledFoo = true;
}
function getSig(bytes _data) private pure returns (bytes4 sig) {
uint lngth = _data.length < 4 ? _data.length : 4;
for (uint i = 0; i < lngth; i++) {
sig = bytes4(uint(sig) + uint(_data[i]) * (2 ** (8 * (lngth - 1 - i))));
}
}
function saveTokenValues() private {<FILL_FUNCTION_BODY> }
} | contract Generic223Receiver {
uint public sentValue;
address public tokenAddr;
address public tokenSender;
bool public calledFoo;
bytes public tokenData;
bytes4 public tokenSig;
Tkn private tkn;
bool private __isTokenFallback;
struct Tkn {
address addr;
address sender;
uint256 value;
bytes data;
bytes4 sig;
}
modifier tokenPayable {
assert(__isTokenFallback);
_;
}
function tokenFallback(address _sender, uint _value, bytes _data) public returns (bool success) {
tkn = Tkn(msg.sender, _sender, _value, _data, getSig(_data));
__isTokenFallback = true;
address(this).delegatecall(_data);
__isTokenFallback = false;
return true;
}
function foo() public tokenPayable {
saveTokenValues();
calledFoo = true;
}
function getSig(bytes _data) private pure returns (bytes4 sig) {
uint lngth = _data.length < 4 ? _data.length : 4;
for (uint i = 0; i < lngth; i++) {
sig = bytes4(uint(sig) + uint(_data[i]) * (2 ** (8 * (lngth - 1 - i))));
}
}
<FILL_FUNCTION>
} |
tokenAddr = tkn.addr;
tokenSender = tkn.sender;
sentValue = tkn.value;
tokenSig = tkn.sig;
tokenData = tkn.data;
| function saveTokenValues() private | function saveTokenValues() private |
15127 | StandardToken | _approve | contract StandardToken is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function multiTransfer(address[] memory to, uint256[] memory value) public returns (bool) {
require(to.length > 0 && to.length == value.length, "Invalid params");
for(uint i = 0; i < to.length; i++) {
_transfer(msg.sender, to[i], value[i]);
}
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0), "ERC20: transfer to the zero address");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
function _mint(address account, uint256 value) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
function _burn(address account, uint256 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
function _approve(address owner, address spender, uint256 value) internal {<FILL_FUNCTION_BODY> }
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
} | contract StandardToken is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function multiTransfer(address[] memory to, uint256[] memory value) public returns (bool) {
require(to.length > 0 && to.length == value.length, "Invalid params");
for(uint i = 0; i < to.length; i++) {
_transfer(msg.sender, to[i], value[i]);
}
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0), "ERC20: transfer to the zero address");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
function _mint(address account, uint256 value) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
function _burn(address account, uint256 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
<FILL_FUNCTION>
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
} |
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
| function _approve(address owner, address spender, uint256 value) internal | function _approve(address owner, address spender, uint256 value) internal |
52283 | TokenMetadata | TokenMetadata | contract TokenMetadata is ITokenMetadata {
////////////////////////
// Immutable state
////////////////////////
// The Token's name: e.g. DigixDAO Tokens
string private NAME;
// An identifier: e.g. REP
string private SYMBOL;
// Number of decimals of the smallest unit
uint8 private DECIMALS;
// An arbitrary versioning scheme
string private VERSION;
////////////////////////
// Constructor
////////////////////////
/// @notice Constructor to set metadata
/// @param tokenName Name of the new token
/// @param decimalUnits Number of decimals of the new token
/// @param tokenSymbol Token Symbol for the new token
/// @param version Token version ie. when cloning is used
function TokenMetadata(
string tokenName,
uint8 decimalUnits,
string tokenSymbol,
string version
)
public
{<FILL_FUNCTION_BODY> }
////////////////////////
// Public functions
////////////////////////
function name()
public
constant
returns (string)
{
return NAME;
}
function symbol()
public
constant
returns (string)
{
return SYMBOL;
}
function decimals()
public
constant
returns (uint8)
{
return DECIMALS;
}
function version()
public
constant
returns (string)
{
return VERSION;
}
} | contract TokenMetadata is ITokenMetadata {
////////////////////////
// Immutable state
////////////////////////
// The Token's name: e.g. DigixDAO Tokens
string private NAME;
// An identifier: e.g. REP
string private SYMBOL;
// Number of decimals of the smallest unit
uint8 private DECIMALS;
// An arbitrary versioning scheme
string private VERSION;
<FILL_FUNCTION>
////////////////////////
// Public functions
////////////////////////
function name()
public
constant
returns (string)
{
return NAME;
}
function symbol()
public
constant
returns (string)
{
return SYMBOL;
}
function decimals()
public
constant
returns (uint8)
{
return DECIMALS;
}
function version()
public
constant
returns (string)
{
return VERSION;
}
} |
NAME = tokenName; // Set the name
SYMBOL = tokenSymbol; // Set the symbol
DECIMALS = decimalUnits; // Set the decimals
VERSION = version;
| function TokenMetadata(
string tokenName,
uint8 decimalUnits,
string tokenSymbol,
string version
)
public
| ////////////////////////
// Constructor
////////////////////////
/// @notice Constructor to set metadata
/// @param tokenName Name of the new token
/// @param decimalUnits Number of decimals of the new token
/// @param tokenSymbol Token Symbol for the new token
/// @param version Token version ie. when cloning is used
function TokenMetadata(
string tokenName,
uint8 decimalUnits,
string tokenSymbol,
string version
)
public
|
41202 | MixinForwarderCore | marketSellOrdersWithEth | contract MixinForwarderCore is
LibFillResults,
LibMath,
LibConstants,
MWeth,
MAssets,
MExchangeWrapper,
IForwarderCore
{
using LibBytes for bytes;
/// @dev Constructor approves ERC20 proxy to transfer ZRX and WETH on this contract's behalf.
constructor ()
public
{
address proxyAddress = EXCHANGE.getAssetProxy(ERC20_DATA_ID);
require(
proxyAddress != address(0),
"UNREGISTERED_ASSET_PROXY"
);
ETHER_TOKEN.approve(proxyAddress, MAX_UINT);
ZRX_TOKEN.approve(proxyAddress, MAX_UINT);
}
/// @dev Purchases as much of orders' makerAssets as possible by selling up to 95% of transaction's ETH value.
/// Any ZRX required to pay fees for primary orders will automatically be purchased by this contract.
/// 5% of ETH value is reserved for paying fees to order feeRecipients (in ZRX) and forwarding contract feeRecipient (in ETH).
/// Any ETH not spent will be refunded to sender.
/// @param orders Array of order specifications used containing desired makerAsset and WETH as takerAsset.
/// @param signatures Proofs that orders have been created by makers.
/// @param feeOrders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. Used to purchase ZRX for primary order fees.
/// @param feeSignatures Proofs that feeOrders have been created by makers.
/// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient.
/// @param feeRecipient Address that will receive ETH when orders are filled.
/// @return Amounts filled and fees paid by maker and taker for both sets of orders.
function marketSellOrdersWithEth(
LibOrder.Order[] memory orders,
bytes[] memory signatures,
LibOrder.Order[] memory feeOrders,
bytes[] memory feeSignatures,
uint256 feePercentage,
address feeRecipient
)
public
payable
returns (
FillResults memory orderFillResults,
FillResults memory feeOrderFillResults
)
{<FILL_FUNCTION_BODY> }
/// @dev Attempt to purchase makerAssetFillAmount of makerAsset by selling ETH provided with transaction.
/// Any ZRX required to pay fees for primary orders will automatically be purchased by this contract.
/// Any ETH not spent will be refunded to sender.
/// @param orders Array of order specifications used containing desired makerAsset and WETH as takerAsset.
/// @param makerAssetFillAmount Desired amount of makerAsset to purchase.
/// @param signatures Proofs that orders have been created by makers.
/// @param feeOrders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. Used to purchase ZRX for primary order fees.
/// @param feeSignatures Proofs that feeOrders have been created by makers.
/// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient.
/// @param feeRecipient Address that will receive ETH when orders are filled.
/// @return Amounts filled and fees paid by maker and taker for both sets of orders.
function marketBuyOrdersWithEth(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures,
LibOrder.Order[] memory feeOrders,
bytes[] memory feeSignatures,
uint256 feePercentage,
address feeRecipient
)
public
payable
returns (
FillResults memory orderFillResults,
FillResults memory feeOrderFillResults
)
{
// Convert ETH to WETH.
convertEthToWeth();
uint256 zrxBuyAmount;
uint256 makerAssetAmountPurchased;
if (orders[0].makerAssetData.equals(ZRX_ASSET_DATA)) {
// If the makerAsset is ZRX, it is not necessary to pay fees out of this
// contracts's ZRX balance because fees are factored into the price of the order.
orderFillResults = marketBuyExactZrxWithWeth(
orders,
makerAssetFillAmount,
signatures
);
// The fee amount must be deducted from the amount transfered back to sender.
makerAssetAmountPurchased = safeSub(orderFillResults.makerAssetFilledAmount, orderFillResults.takerFeePaid);
} else {
// Attemp to purchase desired amount of makerAsset.
// ZRX fees are payed with this contract's balance.
orderFillResults = marketBuyExactAmountWithWeth(
orders,
makerAssetFillAmount,
signatures
);
// Buy back all ZRX spent on fees.
zrxBuyAmount = orderFillResults.takerFeePaid;
feeOrderFillResults = marketBuyExactZrxWithWeth(
feeOrders,
zrxBuyAmount,
feeSignatures
);
makerAssetAmountPurchased = orderFillResults.makerAssetFilledAmount;
}
// Transfer feePercentage of total ETH spent on primary orders to feeRecipient.
// Refund remaining ETH to msg.sender.
transferEthFeeAndRefund(
orderFillResults.takerAssetFilledAmount,
feeOrderFillResults.takerAssetFilledAmount,
feePercentage,
feeRecipient
);
// Transfer purchased assets to msg.sender.
transferAssetToSender(orders[0].makerAssetData, makerAssetAmountPurchased);
}
} | contract MixinForwarderCore is
LibFillResults,
LibMath,
LibConstants,
MWeth,
MAssets,
MExchangeWrapper,
IForwarderCore
{
using LibBytes for bytes;
/// @dev Constructor approves ERC20 proxy to transfer ZRX and WETH on this contract's behalf.
constructor ()
public
{
address proxyAddress = EXCHANGE.getAssetProxy(ERC20_DATA_ID);
require(
proxyAddress != address(0),
"UNREGISTERED_ASSET_PROXY"
);
ETHER_TOKEN.approve(proxyAddress, MAX_UINT);
ZRX_TOKEN.approve(proxyAddress, MAX_UINT);
}
<FILL_FUNCTION>
/// @dev Attempt to purchase makerAssetFillAmount of makerAsset by selling ETH provided with transaction.
/// Any ZRX required to pay fees for primary orders will automatically be purchased by this contract.
/// Any ETH not spent will be refunded to sender.
/// @param orders Array of order specifications used containing desired makerAsset and WETH as takerAsset.
/// @param makerAssetFillAmount Desired amount of makerAsset to purchase.
/// @param signatures Proofs that orders have been created by makers.
/// @param feeOrders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. Used to purchase ZRX for primary order fees.
/// @param feeSignatures Proofs that feeOrders have been created by makers.
/// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient.
/// @param feeRecipient Address that will receive ETH when orders are filled.
/// @return Amounts filled and fees paid by maker and taker for both sets of orders.
function marketBuyOrdersWithEth(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures,
LibOrder.Order[] memory feeOrders,
bytes[] memory feeSignatures,
uint256 feePercentage,
address feeRecipient
)
public
payable
returns (
FillResults memory orderFillResults,
FillResults memory feeOrderFillResults
)
{
// Convert ETH to WETH.
convertEthToWeth();
uint256 zrxBuyAmount;
uint256 makerAssetAmountPurchased;
if (orders[0].makerAssetData.equals(ZRX_ASSET_DATA)) {
// If the makerAsset is ZRX, it is not necessary to pay fees out of this
// contracts's ZRX balance because fees are factored into the price of the order.
orderFillResults = marketBuyExactZrxWithWeth(
orders,
makerAssetFillAmount,
signatures
);
// The fee amount must be deducted from the amount transfered back to sender.
makerAssetAmountPurchased = safeSub(orderFillResults.makerAssetFilledAmount, orderFillResults.takerFeePaid);
} else {
// Attemp to purchase desired amount of makerAsset.
// ZRX fees are payed with this contract's balance.
orderFillResults = marketBuyExactAmountWithWeth(
orders,
makerAssetFillAmount,
signatures
);
// Buy back all ZRX spent on fees.
zrxBuyAmount = orderFillResults.takerFeePaid;
feeOrderFillResults = marketBuyExactZrxWithWeth(
feeOrders,
zrxBuyAmount,
feeSignatures
);
makerAssetAmountPurchased = orderFillResults.makerAssetFilledAmount;
}
// Transfer feePercentage of total ETH spent on primary orders to feeRecipient.
// Refund remaining ETH to msg.sender.
transferEthFeeAndRefund(
orderFillResults.takerAssetFilledAmount,
feeOrderFillResults.takerAssetFilledAmount,
feePercentage,
feeRecipient
);
// Transfer purchased assets to msg.sender.
transferAssetToSender(orders[0].makerAssetData, makerAssetAmountPurchased);
}
} |
// Convert ETH to WETH.
convertEthToWeth();
uint256 wethSellAmount;
uint256 zrxBuyAmount;
uint256 makerAssetAmountPurchased;
if (orders[0].makerAssetData.equals(ZRX_ASSET_DATA)) {
// Calculate amount of WETH that won't be spent on ETH fees.
wethSellAmount = getPartialAmountFloor(
PERCENTAGE_DENOMINATOR,
safeAdd(PERCENTAGE_DENOMINATOR, feePercentage),
msg.value
);
// Market sell available WETH.
// ZRX fees are paid with this contract's balance.
orderFillResults = marketSellWeth(
orders,
wethSellAmount,
signatures
);
// The fee amount must be deducted from the amount transfered back to sender.
makerAssetAmountPurchased = safeSub(orderFillResults.makerAssetFilledAmount, orderFillResults.takerFeePaid);
} else {
// 5% of WETH is reserved for filling feeOrders and paying feeRecipient.
wethSellAmount = getPartialAmountFloor(
MAX_WETH_FILL_PERCENTAGE,
PERCENTAGE_DENOMINATOR,
msg.value
);
// Market sell 95% of WETH.
// ZRX fees are payed with this contract's balance.
orderFillResults = marketSellWeth(
orders,
wethSellAmount,
signatures
);
// Buy back all ZRX spent on fees.
zrxBuyAmount = orderFillResults.takerFeePaid;
feeOrderFillResults = marketBuyExactZrxWithWeth(
feeOrders,
zrxBuyAmount,
feeSignatures
);
makerAssetAmountPurchased = orderFillResults.makerAssetFilledAmount;
}
// Transfer feePercentage of total ETH spent on primary orders to feeRecipient.
// Refund remaining ETH to msg.sender.
transferEthFeeAndRefund(
orderFillResults.takerAssetFilledAmount,
feeOrderFillResults.takerAssetFilledAmount,
feePercentage,
feeRecipient
);
// Transfer purchased assets to msg.sender.
transferAssetToSender(orders[0].makerAssetData, makerAssetAmountPurchased);
| function marketSellOrdersWithEth(
LibOrder.Order[] memory orders,
bytes[] memory signatures,
LibOrder.Order[] memory feeOrders,
bytes[] memory feeSignatures,
uint256 feePercentage,
address feeRecipient
)
public
payable
returns (
FillResults memory orderFillResults,
FillResults memory feeOrderFillResults
)
| /// @dev Purchases as much of orders' makerAssets as possible by selling up to 95% of transaction's ETH value.
/// Any ZRX required to pay fees for primary orders will automatically be purchased by this contract.
/// 5% of ETH value is reserved for paying fees to order feeRecipients (in ZRX) and forwarding contract feeRecipient (in ETH).
/// Any ETH not spent will be refunded to sender.
/// @param orders Array of order specifications used containing desired makerAsset and WETH as takerAsset.
/// @param signatures Proofs that orders have been created by makers.
/// @param feeOrders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. Used to purchase ZRX for primary order fees.
/// @param feeSignatures Proofs that feeOrders have been created by makers.
/// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient.
/// @param feeRecipient Address that will receive ETH when orders are filled.
/// @return Amounts filled and fees paid by maker and taker for both sets of orders.
function marketSellOrdersWithEth(
LibOrder.Order[] memory orders,
bytes[] memory signatures,
LibOrder.Order[] memory feeOrders,
bytes[] memory feeSignatures,
uint256 feePercentage,
address feeRecipient
)
public
payable
returns (
FillResults memory orderFillResults,
FillResults memory feeOrderFillResults
)
|
58787 | Moonicorn | _getCurrentSupply | contract Moonicorn is Context, IERC20, Ownable {
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 public _maxTxAmount = 5 * 10**14 * 10**9;
uint256 private numTokensSellToAddToLiquidity = 5 * 10**14 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
string private _name = "Moonicorn";
string private _symbol = "$MONI";
uint8 private _decimals = 9;
using SafeMath for uint256;
using Address for address;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 10**15 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 public _taxFee = 75;
uint256 private _previousTaxFee = _taxFee;
uint256 public _liquidityFee = 25;
uint256 private _previousLiquidityFee = _liquidityFee;
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor () public {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setTaxFeePercent(uint256 taxFee) external onlyOwner() {
_taxFee = taxFee;
}
function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() {
_liquidityFee = liquidityFee;
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
_maxTxAmount = _tTotal.mul(maxTxPercent).div(
10**2
);
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {<FILL_FUNCTION_BODY> }
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**3
);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(
10**3
);
}
function removeAllFee() private {
if(_taxFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_liquidityFee = _previousLiquidityFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + liquidity lock?
// also, don't get caught in a circular liquidity event.
// also, don't swap & liquify if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
//add liquidity
swapAndLiquify(contractTokenBalance);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from,to,amount,takeFee);
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
uint256 initialBalance = address(this).balance;
swapTokensForEth(half);
uint256 newBalance = address(this).balance.sub(initialBalance);
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
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 addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0,
0,
owner(),
block.timestamp
);
}
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
} | contract Moonicorn is Context, IERC20, Ownable {
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 public _maxTxAmount = 5 * 10**14 * 10**9;
uint256 private numTokensSellToAddToLiquidity = 5 * 10**14 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
string private _name = "Moonicorn";
string private _symbol = "$MONI";
uint8 private _decimals = 9;
using SafeMath for uint256;
using Address for address;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 10**15 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 public _taxFee = 75;
uint256 private _previousTaxFee = _taxFee;
uint256 public _liquidityFee = 25;
uint256 private _previousLiquidityFee = _liquidityFee;
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor () public {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setTaxFeePercent(uint256 taxFee) external onlyOwner() {
_taxFee = taxFee;
}
function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() {
_liquidityFee = liquidityFee;
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
_maxTxAmount = _tTotal.mul(maxTxPercent).div(
10**2
);
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
<FILL_FUNCTION>
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**3
);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(
10**3
);
}
function removeAllFee() private {
if(_taxFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_liquidityFee = _previousLiquidityFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + liquidity lock?
// also, don't get caught in a circular liquidity event.
// also, don't swap & liquify if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
//add liquidity
swapAndLiquify(contractTokenBalance);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from,to,amount,takeFee);
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
uint256 initialBalance = address(this).balance;
swapTokensForEth(half);
uint256 newBalance = address(this).balance.sub(initialBalance);
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
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 addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0,
0,
owner(),
block.timestamp
);
}
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
} |
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 _getCurrentSupply() private view returns(uint256, uint256) | function _getCurrentSupply() private view returns(uint256, uint256) |
64493 | ADR_Presale_Airdrop | PreSale | contract ADR_Presale_Airdrop is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of ADRs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accADRPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accADRPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// The ADR2 TOKEN!
ADR_Token public ADR;
// Dev address.
address public devaddr;
AggregatorV3Interface internal priceFeed;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint public bonusEnds;
uint public bonusEnds1;
uint public bonusEnds2;
uint public bonusEnds3;
uint public endDate;
address private _dewpresale;
uint public AirDropTokens;
uint public AirDropEnd;
uint public priceZero;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
ADR_Token _ADR,
address _devaddr
) public {
ADR = _ADR;
devaddr = _devaddr;
priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
}
function getLatestPrice() public view returns (int) {
(
uint80 roundID,
int price,
uint startedAt,
uint timeStamp,
uint80 answeredInRound
) = priceFeed.latestRoundData();
return price;
}
// for swap form
function GetCurrentPriceForETH() public view returns (uint256) {
uint256 tokens;
int ethusd;
uint256 ethprice;
ethusd = getLatestPrice();
ethprice = uint256(ethusd) / priceZero;
if (now <= bonusEnds) {tokens = ethprice / 25 * 10;} // PHASE 1: 1ADR = 2.5$
else if (now > bonusEnds && now < bonusEnds1) {tokens = ethprice / 27 * 10;} // PHASE 2: 1ADR = 2.7$
else if (now > bonusEnds1 && now < bonusEnds2) {tokens = ethprice / 3;} // PHASE 3: 1ADR = 3$
else if (now > bonusEnds2 && now < bonusEnds3) {tokens = ethprice / 33 * 10;} // PHASE 4: 1ADR = 3.3$
return tokens;
}
// for swap form (/10)
function GetCurrentPrice() public view returns (uint256) {
uint256 tokens;
if (now <= bonusEnds) {tokens = 25;} // PHASE 1: 1ADR = 2.5$
else if (now > bonusEnds && now < bonusEnds1) {tokens = 27;} // PHASE 2: 1ADR = 2.7$
else if (now > bonusEnds1 && now < bonusEnds2) {tokens = 30;} // PHASE 3: 1ADR = 3$
else if (now > bonusEnds2 && now < bonusEnds3) {tokens = 33;} // PHASE 4: 1ADR = 3.3$
return tokens;
}
// Safe ADR transfer function, just in case if rounding error causes pool to not have enough ADRs.
function safeADRTransfer(address _to, uint256 _amount) internal {
uint256 ADRBal = ADR.balanceOf(address(this));
if (_amount > ADRBal) {
ADR.transfer(_to, ADRBal);
} else {
ADR.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wtf?");
devaddr = _devaddr;
}
// Only Dev. AirDrop Info.
function AirDrop(uint _AirDropTokens, uint _AirDropEnd) public {
require(msg.sender == devaddr, "dev: wtf?");
AirDropTokens = _AirDropTokens;
AirDropEnd = _AirDropEnd;
}
// Only Dev. Pre-sale info.
function PreSale(uint _bonusEnds, uint _bonusEnds1, uint _bonusEnds2, uint _bonusEnds3, uint _endDate, uint _priceZero) public {<FILL_FUNCTION_BODY> }
function balanceOf(address account) public view returns (uint256) {
return ADR.balanceOf(account);
}
function GetADRform(address _refers) public payable{
_dewpresale = 0x3f0929Bf2388a823d5488f2A190dbB97d467638C; // dev addr for presale
require(now <= endDate, "Pre-sale of tokens is completed!");
uint tokens;
uint256 refbalance;
uint256 refreward;
int ethusd;
uint256 ethprice;
refreward = 2;
ethusd = getLatestPrice();
ethprice = uint256(ethusd) / priceZero;
if (now <= bonusEnds) {tokens = msg.value * ethprice / 25 * 10;} // PHASE 1: 1ADR = 2.5$
else if (now > bonusEnds && now < bonusEnds1) {tokens = msg.value * ethprice / 27 * 10;} // PHASE 2: 1ADR = 2.7$
else if (now > bonusEnds1 && now < bonusEnds2) {tokens = msg.value * ethprice / 3;} // PHASE 3: 1ADR = 3$
else if (now > bonusEnds2 && now < bonusEnds3) {tokens = msg.value * ethprice / 33 * 10;} // PHASE 4: 1ADR = 3.3$
address(uint160(_dewpresale)).transfer(msg.value);
safeADRTransfer(msg.sender, tokens);
if(msg.sender != _refers && _refers != 0x0000000000000000000000000000000000000000)
{
refbalance = ADR.balanceOf(_refers);
if(refbalance >= 1000 ether) refreward = 7;
else if(refbalance >= 500 ether) refreward = 5;
else if(refbalance >= 200 ether) refreward = 3;
tokens = tokens / 100 * refreward;
safeADRTransfer(_refers, tokens);
}
}
receive() external payable {
_dewpresale = 0x3f0929Bf2388a823d5488f2A190dbB97d467638C; // dev addr for presale
require(now <= endDate, "Pre-sale of tokens is completed!");
uint tokens;
int ethusd;
uint256 ethprice;
ethusd = getLatestPrice();
ethprice = uint256(ethusd) / priceZero;
if (now <= bonusEnds) {tokens = msg.value * ethprice / 25 * 10;} // PHASE 1: 1ADR = 2.5$
else if (now > bonusEnds && now < bonusEnds1) {tokens = msg.value * ethprice / 27 * 10;} // PHASE 2: 1ADR = 2.7$
else if (now > bonusEnds1 && now < bonusEnds2) {tokens = msg.value * ethprice / 3;} // PHASE 3: 1ADR = 3$
else if (now > bonusEnds2 && now < bonusEnds3) {tokens = msg.value * ethprice / 33 * 10;} // PHASE 4: 1ADR = 3.3$
address(uint160(_dewpresale)).transfer(msg.value);
safeADRTransfer(msg.sender, tokens);
}
function GetAirdrop() public{
require(now <= AirDropEnd, "AirDrop ADR tokens is completed!");
uint balance;
balance = ADR.balanceOf(msg.sender);
require(balance <= 1, "AirDrop can only be obtained 1 time!");
safeADRTransfer(msg.sender, AirDropTokens);
}
function AirDropClose() public{
require(msg.sender == devaddr, "dev: wtf?");
uint balance;
address burnaddr;
address AirDropWal;
AirDropWal = 0xdAEcE8b60e4908AA2145e2b0a394A176792D6763;
burnaddr = 0x0000000000000000000000000000000000000001;
balance = ADR.balanceOf(address(this));
safeADRTransfer(AirDropWal, balance / 2);
balance = ADR.balanceOf(address(this));
safeADRTransfer(burnaddr, balance);
}
} | contract ADR_Presale_Airdrop is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of ADRs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accADRPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accADRPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// The ADR2 TOKEN!
ADR_Token public ADR;
// Dev address.
address public devaddr;
AggregatorV3Interface internal priceFeed;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint public bonusEnds;
uint public bonusEnds1;
uint public bonusEnds2;
uint public bonusEnds3;
uint public endDate;
address private _dewpresale;
uint public AirDropTokens;
uint public AirDropEnd;
uint public priceZero;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
ADR_Token _ADR,
address _devaddr
) public {
ADR = _ADR;
devaddr = _devaddr;
priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
}
function getLatestPrice() public view returns (int) {
(
uint80 roundID,
int price,
uint startedAt,
uint timeStamp,
uint80 answeredInRound
) = priceFeed.latestRoundData();
return price;
}
// for swap form
function GetCurrentPriceForETH() public view returns (uint256) {
uint256 tokens;
int ethusd;
uint256 ethprice;
ethusd = getLatestPrice();
ethprice = uint256(ethusd) / priceZero;
if (now <= bonusEnds) {tokens = ethprice / 25 * 10;} // PHASE 1: 1ADR = 2.5$
else if (now > bonusEnds && now < bonusEnds1) {tokens = ethprice / 27 * 10;} // PHASE 2: 1ADR = 2.7$
else if (now > bonusEnds1 && now < bonusEnds2) {tokens = ethprice / 3;} // PHASE 3: 1ADR = 3$
else if (now > bonusEnds2 && now < bonusEnds3) {tokens = ethprice / 33 * 10;} // PHASE 4: 1ADR = 3.3$
return tokens;
}
// for swap form (/10)
function GetCurrentPrice() public view returns (uint256) {
uint256 tokens;
if (now <= bonusEnds) {tokens = 25;} // PHASE 1: 1ADR = 2.5$
else if (now > bonusEnds && now < bonusEnds1) {tokens = 27;} // PHASE 2: 1ADR = 2.7$
else if (now > bonusEnds1 && now < bonusEnds2) {tokens = 30;} // PHASE 3: 1ADR = 3$
else if (now > bonusEnds2 && now < bonusEnds3) {tokens = 33;} // PHASE 4: 1ADR = 3.3$
return tokens;
}
// Safe ADR transfer function, just in case if rounding error causes pool to not have enough ADRs.
function safeADRTransfer(address _to, uint256 _amount) internal {
uint256 ADRBal = ADR.balanceOf(address(this));
if (_amount > ADRBal) {
ADR.transfer(_to, ADRBal);
} else {
ADR.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wtf?");
devaddr = _devaddr;
}
// Only Dev. AirDrop Info.
function AirDrop(uint _AirDropTokens, uint _AirDropEnd) public {
require(msg.sender == devaddr, "dev: wtf?");
AirDropTokens = _AirDropTokens;
AirDropEnd = _AirDropEnd;
}
<FILL_FUNCTION>
function balanceOf(address account) public view returns (uint256) {
return ADR.balanceOf(account);
}
function GetADRform(address _refers) public payable{
_dewpresale = 0x3f0929Bf2388a823d5488f2A190dbB97d467638C; // dev addr for presale
require(now <= endDate, "Pre-sale of tokens is completed!");
uint tokens;
uint256 refbalance;
uint256 refreward;
int ethusd;
uint256 ethprice;
refreward = 2;
ethusd = getLatestPrice();
ethprice = uint256(ethusd) / priceZero;
if (now <= bonusEnds) {tokens = msg.value * ethprice / 25 * 10;} // PHASE 1: 1ADR = 2.5$
else if (now > bonusEnds && now < bonusEnds1) {tokens = msg.value * ethprice / 27 * 10;} // PHASE 2: 1ADR = 2.7$
else if (now > bonusEnds1 && now < bonusEnds2) {tokens = msg.value * ethprice / 3;} // PHASE 3: 1ADR = 3$
else if (now > bonusEnds2 && now < bonusEnds3) {tokens = msg.value * ethprice / 33 * 10;} // PHASE 4: 1ADR = 3.3$
address(uint160(_dewpresale)).transfer(msg.value);
safeADRTransfer(msg.sender, tokens);
if(msg.sender != _refers && _refers != 0x0000000000000000000000000000000000000000)
{
refbalance = ADR.balanceOf(_refers);
if(refbalance >= 1000 ether) refreward = 7;
else if(refbalance >= 500 ether) refreward = 5;
else if(refbalance >= 200 ether) refreward = 3;
tokens = tokens / 100 * refreward;
safeADRTransfer(_refers, tokens);
}
}
receive() external payable {
_dewpresale = 0x3f0929Bf2388a823d5488f2A190dbB97d467638C; // dev addr for presale
require(now <= endDate, "Pre-sale of tokens is completed!");
uint tokens;
int ethusd;
uint256 ethprice;
ethusd = getLatestPrice();
ethprice = uint256(ethusd) / priceZero;
if (now <= bonusEnds) {tokens = msg.value * ethprice / 25 * 10;} // PHASE 1: 1ADR = 2.5$
else if (now > bonusEnds && now < bonusEnds1) {tokens = msg.value * ethprice / 27 * 10;} // PHASE 2: 1ADR = 2.7$
else if (now > bonusEnds1 && now < bonusEnds2) {tokens = msg.value * ethprice / 3;} // PHASE 3: 1ADR = 3$
else if (now > bonusEnds2 && now < bonusEnds3) {tokens = msg.value * ethprice / 33 * 10;} // PHASE 4: 1ADR = 3.3$
address(uint160(_dewpresale)).transfer(msg.value);
safeADRTransfer(msg.sender, tokens);
}
function GetAirdrop() public{
require(now <= AirDropEnd, "AirDrop ADR tokens is completed!");
uint balance;
balance = ADR.balanceOf(msg.sender);
require(balance <= 1, "AirDrop can only be obtained 1 time!");
safeADRTransfer(msg.sender, AirDropTokens);
}
function AirDropClose() public{
require(msg.sender == devaddr, "dev: wtf?");
uint balance;
address burnaddr;
address AirDropWal;
AirDropWal = 0xdAEcE8b60e4908AA2145e2b0a394A176792D6763;
burnaddr = 0x0000000000000000000000000000000000000001;
balance = ADR.balanceOf(address(this));
safeADRTransfer(AirDropWal, balance / 2);
balance = ADR.balanceOf(address(this));
safeADRTransfer(burnaddr, balance);
}
} |
require(msg.sender == devaddr, "dev: wtf?");
bonusEnds = _bonusEnds;
bonusEnds1 = _bonusEnds1;
bonusEnds2 = _bonusEnds2;
bonusEnds3 = _bonusEnds3;
endDate = _endDate;
priceZero = _priceZero;
| function PreSale(uint _bonusEnds, uint _bonusEnds1, uint _bonusEnds2, uint _bonusEnds3, uint _endDate, uint _priceZero) public | // Only Dev. Pre-sale info.
function PreSale(uint _bonusEnds, uint _bonusEnds1, uint _bonusEnds2, uint _bonusEnds3, uint _endDate, uint _priceZero) public |
22511 | Oracle | null | contract Oracle is Epoch {
using FixedPoint for *;
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
// uniswap
address public token0;
address public token1;
IUniswapV2Pair public pair;
// oracle
uint32 public blockTimestampLast;
uint256 public price0CumulativeLast;
uint256 public price1CumulativeLast;
FixedPoint.uq112x112 public price0Average;
FixedPoint.uq112x112 public price1Average;
/* ========== CONSTRUCTOR ========== */
constructor(
address _factory,
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _startTime
) public Epoch(_period, _startTime, 0) {<FILL_FUNCTION_BODY> }
/* ========== MUTABLE FUNCTIONS ========== */
/** @dev Updates 1-day EMA price from Uniswap. */
function update() external checkEpoch {
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestamp
) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair));
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed == 0) {
// prevent divided by zero
return;
}
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
price0Average = FixedPoint.uq112x112(
uint224((price0Cumulative - price0CumulativeLast) / timeElapsed)
);
price1Average = FixedPoint.uq112x112(
uint224((price1Cumulative - price1CumulativeLast) / timeElapsed)
);
price0CumulativeLast = price0Cumulative;
price1CumulativeLast = price1Cumulative;
blockTimestampLast = blockTimestamp;
emit Updated(price0Cumulative, price1Cumulative);
}
// note this will always return 0 before update has been called successfully for the first time.
function consult(address token, uint256 amountIn)
external
view
returns (uint144 amountOut)
{
if (token == token0) {
amountOut = price0Average.mul(amountIn).decode144();
} else {
require(token == token1, 'Oracle: INVALID_TOKEN');
amountOut = price1Average.mul(amountIn).decode144();
}
}
function pairFor(
address factory,
address tokenA,
address tokenB
) external pure returns (address lpt) {
return UniswapV2Library.pairFor(factory, tokenA, tokenB);
}
event Updated(uint256 price0CumulativeLast, uint256 price1CumulativeLast);
} | contract Oracle is Epoch {
using FixedPoint for *;
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
// uniswap
address public token0;
address public token1;
IUniswapV2Pair public pair;
// oracle
uint32 public blockTimestampLast;
uint256 public price0CumulativeLast;
uint256 public price1CumulativeLast;
FixedPoint.uq112x112 public price0Average;
FixedPoint.uq112x112 public price1Average;
<FILL_FUNCTION>
/* ========== MUTABLE FUNCTIONS ========== */
/** @dev Updates 1-day EMA price from Uniswap. */
function update() external checkEpoch {
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestamp
) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair));
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed == 0) {
// prevent divided by zero
return;
}
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
price0Average = FixedPoint.uq112x112(
uint224((price0Cumulative - price0CumulativeLast) / timeElapsed)
);
price1Average = FixedPoint.uq112x112(
uint224((price1Cumulative - price1CumulativeLast) / timeElapsed)
);
price0CumulativeLast = price0Cumulative;
price1CumulativeLast = price1Cumulative;
blockTimestampLast = blockTimestamp;
emit Updated(price0Cumulative, price1Cumulative);
}
// note this will always return 0 before update has been called successfully for the first time.
function consult(address token, uint256 amountIn)
external
view
returns (uint144 amountOut)
{
if (token == token0) {
amountOut = price0Average.mul(amountIn).decode144();
} else {
require(token == token1, 'Oracle: INVALID_TOKEN');
amountOut = price1Average.mul(amountIn).decode144();
}
}
function pairFor(
address factory,
address tokenA,
address tokenB
) external pure returns (address lpt) {
return UniswapV2Library.pairFor(factory, tokenA, tokenB);
}
event Updated(uint256 price0CumulativeLast, uint256 price1CumulativeLast);
} |
IUniswapV2Pair _pair = IUniswapV2Pair(
UniswapV2Library.pairFor(_factory, _tokenA, _tokenB)
);
pair = _pair;
token0 = _pair.token0();
token1 = _pair.token1();
price0CumulativeLast = _pair.price0CumulativeLast(); // fetch the current accumulated price value (1 / 0)
price1CumulativeLast = _pair.price1CumulativeLast(); // fetch the current accumulated price value (0 / 1)
uint112 reserve0;
uint112 reserve1;
(reserve0, reserve1, blockTimestampLast) = _pair.getReserves();
require(reserve0 != 0 && reserve1 != 0, 'Oracle: NO_RESERVES'); // ensure that there's liquidity in the pair
| constructor(
address _factory,
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _startTime
) public Epoch(_period, _startTime, 0) | /* ========== CONSTRUCTOR ========== */
constructor(
address _factory,
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _startTime
) public Epoch(_period, _startTime, 0) |
3815 | DNNToken | issueTokens | contract DNNToken is StandardToken {
using SafeMath for uint256;
////////////////////////////////////////////////////////////
// Used to indicate which allocation we issue tokens from //
////////////////////////////////////////////////////////////
enum DNNSupplyAllocations {
EarlyBackerSupplyAllocation,
PRETDESupplyAllocation,
TDESupplyAllocation,
BountySupplyAllocation,
WriterAccountSupplyAllocation,
AdvisorySupplyAllocation,
PlatformSupplyAllocation
}
/////////////////////////////////////////////////////////////////////
// Smart-Contract with permission to allocate tokens from supplies //
/////////////////////////////////////////////////////////////////////
address public allocatorAddress;
address public crowdfundContract;
/////////////////////
// Token Meta Data //
/////////////////////
string constant public name = "DNN";
string constant public symbol = "DNN";
uint8 constant public decimals = 18; // 1 DNN = 1 * 10^18 atto-DNN
/////////////////////////////////////////
// Addresses of the co-founders of DNN //
/////////////////////////////////////////
address public cofounderA;
address public cofounderB;
/////////////////////////
// Address of Platform //
/////////////////////////
address public platform;
/////////////////////////////////////////////
// Token Distributions (% of total supply) //
/////////////////////////////////////////////
uint256 public earlyBackerSupply; // 10%
uint256 public PRETDESupply; // 10%
uint256 public TDESupply; // 40%
uint256 public bountySupply; // 1%
uint256 public writerAccountSupply; // 4%
uint256 public advisorySupply; // 14%
uint256 public cofoundersSupply; // 10%
uint256 public platformSupply; // 11%
uint256 public earlyBackerSupplyRemaining; // 10%
uint256 public PRETDESupplyRemaining; // 10%
uint256 public TDESupplyRemaining; // 40%
uint256 public bountySupplyRemaining; // 1%
uint256 public writerAccountSupplyRemaining; // 4%
uint256 public advisorySupplyRemaining; // 14%
uint256 public cofoundersSupplyRemaining; // 10%
uint256 public platformSupplyRemaining; // 11%
////////////////////////////////////////////////////////////////////////////////////
// Amount of CoFounder Supply that has been distributed based on vesting schedule //
////////////////////////////////////////////////////////////////////////////////////
uint256 public cofoundersSupplyVestingTranches = 10;
uint256 public cofoundersSupplyVestingTranchesIssued = 0;
uint256 public cofoundersSupplyVestingStartDate; // Epoch
uint256 public cofoundersSupplyDistributed = 0; // # of atto-DNN distributed to founders
//////////////////////////////////////////////
// Prevents tokens from being transferrable //
//////////////////////////////////////////////
bool public tokensLocked = true;
/////////////////////////////////////////////////////////////////////////////
// Event triggered when tokens are transferred from one address to another //
/////////////////////////////////////////////////////////////////////////////
event Transfer(address indexed from, address indexed to, uint256 value);
////////////////////////////////////////////////////////////
// Checks if tokens can be issued to founder at this time //
////////////////////////////////////////////////////////////
modifier CofoundersTokensVested()
{
// Make sure that a starting vesting date has been set and 4 weeks have passed since vesting date
require (cofoundersSupplyVestingStartDate != 0 && (now-cofoundersSupplyVestingStartDate) >= 4 weeks);
// Get current tranche based on the amount of time that has passed since vesting start date
uint256 currentTranche = now.sub(cofoundersSupplyVestingStartDate) / 4 weeks;
// Amount of tranches that have been issued so far
uint256 issuedTranches = cofoundersSupplyVestingTranchesIssued;
// Amount of tranches that cofounders are entitled to
uint256 maxTranches = cofoundersSupplyVestingTranches;
// Make sure that we still have unvested tokens and that
// the tokens for the current tranche have not been issued.
require (issuedTranches != maxTranches && currentTranche > issuedTranches);
_;
}
///////////////////////////////////
// Checks if tokens are unlocked //
///////////////////////////////////
modifier TokensUnlocked()
{
require (tokensLocked == false);
_;
}
/////////////////////////////////
// Checks if tokens are locked //
/////////////////////////////////
modifier TokensLocked()
{
require (tokensLocked == true);
_;
}
////////////////////////////////////////////////////
// Checks if CoFounders are performing the action //
////////////////////////////////////////////////////
modifier onlyCofounders()
{
require (msg.sender == cofounderA || msg.sender == cofounderB);
_;
}
////////////////////////////////////////////////////
// Checks if CoFounder A is performing the action //
////////////////////////////////////////////////////
modifier onlyCofounderA()
{
require (msg.sender == cofounderA);
_;
}
////////////////////////////////////////////////////
// Checks if CoFounder B is performing the action //
////////////////////////////////////////////////////
modifier onlyCofounderB()
{
require (msg.sender == cofounderB);
_;
}
//////////////////////////////////////////////////
// Checks if Allocator is performing the action //
//////////////////////////////////////////////////
modifier onlyAllocator()
{
require (msg.sender == allocatorAddress);
_;
}
///////////////////////////////////////////////////////////
// Checks if Crowdfund Contract is performing the action //
///////////////////////////////////////////////////////////
modifier onlyCrowdfundContract()
{
require (msg.sender == crowdfundContract);
_;
}
///////////////////////////////////////////////////////////////////////////////////
// Checks if Crowdfund Contract, Platform, or Allocator is performing the action //
///////////////////////////////////////////////////////////////////////////////////
modifier onlyAllocatorOrCrowdfundContractOrPlatform()
{
require (msg.sender == allocatorAddress || msg.sender == crowdfundContract || msg.sender == platform);
_;
}
///////////////////////////////////////////////////////////////////////
// @des Function to change address that is manage platform holding //
// @param newAddress Address of new issuance contract. //
///////////////////////////////////////////////////////////////////////
function changePlatform(address newAddress)
onlyCofounders
{
platform = newAddress;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// @des Function to change address that is allowed to do token issuance. Crowdfund contract can only be set once. //
// @param newAddress Address of new issuance contract. //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function changeCrowdfundContract(address newAddress)
onlyCofounders
{
crowdfundContract = newAddress;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// @des Function to change address that is allowed to do token issuance. Allocator can only be set once. //
// @param newAddress Address of new issuance contract. //
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
function changeAllocator(address newAddress)
onlyCofounders
{
allocatorAddress = newAddress;
}
///////////////////////////////////////////////////////
// @des Function to change founder A address. //
// @param newAddress Address of new founder A. //
///////////////////////////////////////////////////////
function changeCofounderA(address newAddress)
onlyCofounderA
{
cofounderA = newAddress;
}
//////////////////////////////////////////////////////
// @des Function to change founder B address. //
// @param newAddress Address of new founder B. //
//////////////////////////////////////////////////////
function changeCofounderB(address newAddress)
onlyCofounderB
{
cofounderB = newAddress;
}
//////////////////////////////////////////////////////////////
// Transfers tokens from senders address to another address //
//////////////////////////////////////////////////////////////
function transfer(address _to, uint256 _value)
TokensUnlocked
returns (bool)
{
Transfer(msg.sender, _to, _value);
return BasicToken.transfer(_to, _value);
}
//////////////////////////////////////////////////////////
// Transfers tokens from one address to another address //
//////////////////////////////////////////////////////////
function transferFrom(address _from, address _to, uint256 _value)
TokensUnlocked
returns (bool)
{
Transfer(_from, _to, _value);
return StandardToken.transferFrom(_from, _to, _value);
}
///////////////////////////////////////////////////////////////////////////////////////////////
// @des Cofounders issue tokens to themsleves if within vesting period. Returns success. //
// @param beneficiary Address of receiver. //
// @param tokenCount Number of tokens to issue. //
///////////////////////////////////////////////////////////////////////////////////////////////
function issueCofoundersTokensIfPossible()
onlyCofounders
CofoundersTokensVested
returns (bool)
{
// Compute total amount of vested tokens to issue
uint256 tokenCount = cofoundersSupply.div(cofoundersSupplyVestingTranches);
// Make sure that there are cofounder tokens left
if (tokenCount > cofoundersSupplyRemaining) {
return false;
}
// Decrease cofounders supply
cofoundersSupplyRemaining = cofoundersSupplyRemaining.sub(tokenCount);
// Update how many tokens have been distributed to cofounders
cofoundersSupplyDistributed = cofoundersSupplyDistributed.add(tokenCount);
// Split tokens between both founders
balances[cofounderA] = balances[cofounderA].add(tokenCount.div(2));
balances[cofounderB] = balances[cofounderB].add(tokenCount.div(2));
// Update that a tranche has been issued
cofoundersSupplyVestingTranchesIssued += 1;
return true;
}
//////////////////
// Issue tokens //
//////////////////
function issueTokens(address beneficiary, uint256 tokenCount, DNNSupplyAllocations allocationType)
onlyAllocatorOrCrowdfundContractOrPlatform
returns (bool)
{<FILL_FUNCTION_BODY> }
/////////////////////////////////////////////////
// Transfer Unsold tokens from TDE to Platform //
/////////////////////////////////////////////////
function sendUnsoldTDETokensToPlatform()
external
onlyCrowdfundContract
{
// Make sure we have tokens to send from TDE
if (TDESupplyRemaining > 0) {
// Add remaining tde tokens to platform remaining tokens
platformSupplyRemaining = platformSupplyRemaining.add(TDESupplyRemaining);
// Clear remaining tde token count
TDESupplyRemaining = 0;
}
}
/////////////////////////////////////////////////////
// Transfer Unsold tokens from pre-TDE to Platform //
/////////////////////////////////////////////////////
function sendUnsoldPRETDETokensToTDE()
external
onlyCrowdfundContract
{
// Make sure we have tokens to send from pre-TDE
if (PRETDESupplyRemaining > 0) {
// Add remaining pre-tde tokens to tde remaining tokens
TDESupplyRemaining = TDESupplyRemaining.add(PRETDESupplyRemaining);
// Clear remaining pre-tde token count
PRETDESupplyRemaining = 0;
}
}
////////////////////////////////////////////////////////////////
// @des Allows tokens to be transferrable. Returns lock state //
////////////////////////////////////////////////////////////////
function unlockTokens()
external
onlyCrowdfundContract
{
// Make sure tokens are currently locked before proceeding to unlock them
require(tokensLocked == true);
tokensLocked = false;
}
///////////////////////////////////////////////////////////////////////
// @des Contract constructor function sets initial token balances. //
///////////////////////////////////////////////////////////////////////
function DNNToken()
{
// Start date
uint256 vestingStartDate = 1526072145;
// Set cofounder addresses
cofounderA = 0x3Cf26a9FE33C219dB87c2e50572e50803eFb2981;
cofounderB = 0x9FFE2aD5D76954C7C25be0cEE30795279c4Cab9f;
// Sets platform address
platform = address(this);
// Set total supply - 1 Billion DNN Tokens = (1,000,000,000 * 10^18) atto-DNN
// 1 DNN = 10^18 atto-DNN
totalSupply = uint256(1000000000).mul(uint256(10)**decimals);
// Set Token Distributions (% of total supply)
earlyBackerSupply = totalSupply.mul(10).div(100); // 10%
PRETDESupply = totalSupply.mul(10).div(100); // 10%
TDESupply = totalSupply.mul(40).div(100); // 40%
bountySupply = totalSupply.mul(1).div(100); // 1%
writerAccountSupply = totalSupply.mul(4).div(100); // 4%
advisorySupply = totalSupply.mul(14).div(100); // 14%
cofoundersSupply = totalSupply.mul(10).div(100); // 10%
platformSupply = totalSupply.mul(11).div(100); // 11%
// Set each remaining token count equal to its' respective supply
earlyBackerSupplyRemaining = earlyBackerSupply;
PRETDESupplyRemaining = PRETDESupply;
TDESupplyRemaining = TDESupply;
bountySupplyRemaining = bountySupply;
writerAccountSupplyRemaining = writerAccountSupply;
advisorySupplyRemaining = advisorySupply;
cofoundersSupplyRemaining = cofoundersSupply;
platformSupplyRemaining = platformSupply;
// Sets cofounder vesting start date (Ensures that it is a date in the future, otherwise it will default to now)
cofoundersSupplyVestingStartDate = vestingStartDate >= now ? vestingStartDate : now;
}
} | contract DNNToken is StandardToken {
using SafeMath for uint256;
////////////////////////////////////////////////////////////
// Used to indicate which allocation we issue tokens from //
////////////////////////////////////////////////////////////
enum DNNSupplyAllocations {
EarlyBackerSupplyAllocation,
PRETDESupplyAllocation,
TDESupplyAllocation,
BountySupplyAllocation,
WriterAccountSupplyAllocation,
AdvisorySupplyAllocation,
PlatformSupplyAllocation
}
/////////////////////////////////////////////////////////////////////
// Smart-Contract with permission to allocate tokens from supplies //
/////////////////////////////////////////////////////////////////////
address public allocatorAddress;
address public crowdfundContract;
/////////////////////
// Token Meta Data //
/////////////////////
string constant public name = "DNN";
string constant public symbol = "DNN";
uint8 constant public decimals = 18; // 1 DNN = 1 * 10^18 atto-DNN
/////////////////////////////////////////
// Addresses of the co-founders of DNN //
/////////////////////////////////////////
address public cofounderA;
address public cofounderB;
/////////////////////////
// Address of Platform //
/////////////////////////
address public platform;
/////////////////////////////////////////////
// Token Distributions (% of total supply) //
/////////////////////////////////////////////
uint256 public earlyBackerSupply; // 10%
uint256 public PRETDESupply; // 10%
uint256 public TDESupply; // 40%
uint256 public bountySupply; // 1%
uint256 public writerAccountSupply; // 4%
uint256 public advisorySupply; // 14%
uint256 public cofoundersSupply; // 10%
uint256 public platformSupply; // 11%
uint256 public earlyBackerSupplyRemaining; // 10%
uint256 public PRETDESupplyRemaining; // 10%
uint256 public TDESupplyRemaining; // 40%
uint256 public bountySupplyRemaining; // 1%
uint256 public writerAccountSupplyRemaining; // 4%
uint256 public advisorySupplyRemaining; // 14%
uint256 public cofoundersSupplyRemaining; // 10%
uint256 public platformSupplyRemaining; // 11%
////////////////////////////////////////////////////////////////////////////////////
// Amount of CoFounder Supply that has been distributed based on vesting schedule //
////////////////////////////////////////////////////////////////////////////////////
uint256 public cofoundersSupplyVestingTranches = 10;
uint256 public cofoundersSupplyVestingTranchesIssued = 0;
uint256 public cofoundersSupplyVestingStartDate; // Epoch
uint256 public cofoundersSupplyDistributed = 0; // # of atto-DNN distributed to founders
//////////////////////////////////////////////
// Prevents tokens from being transferrable //
//////////////////////////////////////////////
bool public tokensLocked = true;
/////////////////////////////////////////////////////////////////////////////
// Event triggered when tokens are transferred from one address to another //
/////////////////////////////////////////////////////////////////////////////
event Transfer(address indexed from, address indexed to, uint256 value);
////////////////////////////////////////////////////////////
// Checks if tokens can be issued to founder at this time //
////////////////////////////////////////////////////////////
modifier CofoundersTokensVested()
{
// Make sure that a starting vesting date has been set and 4 weeks have passed since vesting date
require (cofoundersSupplyVestingStartDate != 0 && (now-cofoundersSupplyVestingStartDate) >= 4 weeks);
// Get current tranche based on the amount of time that has passed since vesting start date
uint256 currentTranche = now.sub(cofoundersSupplyVestingStartDate) / 4 weeks;
// Amount of tranches that have been issued so far
uint256 issuedTranches = cofoundersSupplyVestingTranchesIssued;
// Amount of tranches that cofounders are entitled to
uint256 maxTranches = cofoundersSupplyVestingTranches;
// Make sure that we still have unvested tokens and that
// the tokens for the current tranche have not been issued.
require (issuedTranches != maxTranches && currentTranche > issuedTranches);
_;
}
///////////////////////////////////
// Checks if tokens are unlocked //
///////////////////////////////////
modifier TokensUnlocked()
{
require (tokensLocked == false);
_;
}
/////////////////////////////////
// Checks if tokens are locked //
/////////////////////////////////
modifier TokensLocked()
{
require (tokensLocked == true);
_;
}
////////////////////////////////////////////////////
// Checks if CoFounders are performing the action //
////////////////////////////////////////////////////
modifier onlyCofounders()
{
require (msg.sender == cofounderA || msg.sender == cofounderB);
_;
}
////////////////////////////////////////////////////
// Checks if CoFounder A is performing the action //
////////////////////////////////////////////////////
modifier onlyCofounderA()
{
require (msg.sender == cofounderA);
_;
}
////////////////////////////////////////////////////
// Checks if CoFounder B is performing the action //
////////////////////////////////////////////////////
modifier onlyCofounderB()
{
require (msg.sender == cofounderB);
_;
}
//////////////////////////////////////////////////
// Checks if Allocator is performing the action //
//////////////////////////////////////////////////
modifier onlyAllocator()
{
require (msg.sender == allocatorAddress);
_;
}
///////////////////////////////////////////////////////////
// Checks if Crowdfund Contract is performing the action //
///////////////////////////////////////////////////////////
modifier onlyCrowdfundContract()
{
require (msg.sender == crowdfundContract);
_;
}
///////////////////////////////////////////////////////////////////////////////////
// Checks if Crowdfund Contract, Platform, or Allocator is performing the action //
///////////////////////////////////////////////////////////////////////////////////
modifier onlyAllocatorOrCrowdfundContractOrPlatform()
{
require (msg.sender == allocatorAddress || msg.sender == crowdfundContract || msg.sender == platform);
_;
}
///////////////////////////////////////////////////////////////////////
// @des Function to change address that is manage platform holding //
// @param newAddress Address of new issuance contract. //
///////////////////////////////////////////////////////////////////////
function changePlatform(address newAddress)
onlyCofounders
{
platform = newAddress;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// @des Function to change address that is allowed to do token issuance. Crowdfund contract can only be set once. //
// @param newAddress Address of new issuance contract. //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function changeCrowdfundContract(address newAddress)
onlyCofounders
{
crowdfundContract = newAddress;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// @des Function to change address that is allowed to do token issuance. Allocator can only be set once. //
// @param newAddress Address of new issuance contract. //
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
function changeAllocator(address newAddress)
onlyCofounders
{
allocatorAddress = newAddress;
}
///////////////////////////////////////////////////////
// @des Function to change founder A address. //
// @param newAddress Address of new founder A. //
///////////////////////////////////////////////////////
function changeCofounderA(address newAddress)
onlyCofounderA
{
cofounderA = newAddress;
}
//////////////////////////////////////////////////////
// @des Function to change founder B address. //
// @param newAddress Address of new founder B. //
//////////////////////////////////////////////////////
function changeCofounderB(address newAddress)
onlyCofounderB
{
cofounderB = newAddress;
}
//////////////////////////////////////////////////////////////
// Transfers tokens from senders address to another address //
//////////////////////////////////////////////////////////////
function transfer(address _to, uint256 _value)
TokensUnlocked
returns (bool)
{
Transfer(msg.sender, _to, _value);
return BasicToken.transfer(_to, _value);
}
//////////////////////////////////////////////////////////
// Transfers tokens from one address to another address //
//////////////////////////////////////////////////////////
function transferFrom(address _from, address _to, uint256 _value)
TokensUnlocked
returns (bool)
{
Transfer(_from, _to, _value);
return StandardToken.transferFrom(_from, _to, _value);
}
///////////////////////////////////////////////////////////////////////////////////////////////
// @des Cofounders issue tokens to themsleves if within vesting period. Returns success. //
// @param beneficiary Address of receiver. //
// @param tokenCount Number of tokens to issue. //
///////////////////////////////////////////////////////////////////////////////////////////////
function issueCofoundersTokensIfPossible()
onlyCofounders
CofoundersTokensVested
returns (bool)
{
// Compute total amount of vested tokens to issue
uint256 tokenCount = cofoundersSupply.div(cofoundersSupplyVestingTranches);
// Make sure that there are cofounder tokens left
if (tokenCount > cofoundersSupplyRemaining) {
return false;
}
// Decrease cofounders supply
cofoundersSupplyRemaining = cofoundersSupplyRemaining.sub(tokenCount);
// Update how many tokens have been distributed to cofounders
cofoundersSupplyDistributed = cofoundersSupplyDistributed.add(tokenCount);
// Split tokens between both founders
balances[cofounderA] = balances[cofounderA].add(tokenCount.div(2));
balances[cofounderB] = balances[cofounderB].add(tokenCount.div(2));
// Update that a tranche has been issued
cofoundersSupplyVestingTranchesIssued += 1;
return true;
}
<FILL_FUNCTION>
/////////////////////////////////////////////////
// Transfer Unsold tokens from TDE to Platform //
/////////////////////////////////////////////////
function sendUnsoldTDETokensToPlatform()
external
onlyCrowdfundContract
{
// Make sure we have tokens to send from TDE
if (TDESupplyRemaining > 0) {
// Add remaining tde tokens to platform remaining tokens
platformSupplyRemaining = platformSupplyRemaining.add(TDESupplyRemaining);
// Clear remaining tde token count
TDESupplyRemaining = 0;
}
}
/////////////////////////////////////////////////////
// Transfer Unsold tokens from pre-TDE to Platform //
/////////////////////////////////////////////////////
function sendUnsoldPRETDETokensToTDE()
external
onlyCrowdfundContract
{
// Make sure we have tokens to send from pre-TDE
if (PRETDESupplyRemaining > 0) {
// Add remaining pre-tde tokens to tde remaining tokens
TDESupplyRemaining = TDESupplyRemaining.add(PRETDESupplyRemaining);
// Clear remaining pre-tde token count
PRETDESupplyRemaining = 0;
}
}
////////////////////////////////////////////////////////////////
// @des Allows tokens to be transferrable. Returns lock state //
////////////////////////////////////////////////////////////////
function unlockTokens()
external
onlyCrowdfundContract
{
// Make sure tokens are currently locked before proceeding to unlock them
require(tokensLocked == true);
tokensLocked = false;
}
///////////////////////////////////////////////////////////////////////
// @des Contract constructor function sets initial token balances. //
///////////////////////////////////////////////////////////////////////
function DNNToken()
{
// Start date
uint256 vestingStartDate = 1526072145;
// Set cofounder addresses
cofounderA = 0x3Cf26a9FE33C219dB87c2e50572e50803eFb2981;
cofounderB = 0x9FFE2aD5D76954C7C25be0cEE30795279c4Cab9f;
// Sets platform address
platform = address(this);
// Set total supply - 1 Billion DNN Tokens = (1,000,000,000 * 10^18) atto-DNN
// 1 DNN = 10^18 atto-DNN
totalSupply = uint256(1000000000).mul(uint256(10)**decimals);
// Set Token Distributions (% of total supply)
earlyBackerSupply = totalSupply.mul(10).div(100); // 10%
PRETDESupply = totalSupply.mul(10).div(100); // 10%
TDESupply = totalSupply.mul(40).div(100); // 40%
bountySupply = totalSupply.mul(1).div(100); // 1%
writerAccountSupply = totalSupply.mul(4).div(100); // 4%
advisorySupply = totalSupply.mul(14).div(100); // 14%
cofoundersSupply = totalSupply.mul(10).div(100); // 10%
platformSupply = totalSupply.mul(11).div(100); // 11%
// Set each remaining token count equal to its' respective supply
earlyBackerSupplyRemaining = earlyBackerSupply;
PRETDESupplyRemaining = PRETDESupply;
TDESupplyRemaining = TDESupply;
bountySupplyRemaining = bountySupply;
writerAccountSupplyRemaining = writerAccountSupply;
advisorySupplyRemaining = advisorySupply;
cofoundersSupplyRemaining = cofoundersSupply;
platformSupplyRemaining = platformSupply;
// Sets cofounder vesting start date (Ensures that it is a date in the future, otherwise it will default to now)
cofoundersSupplyVestingStartDate = vestingStartDate >= now ? vestingStartDate : now;
}
} |
// We'll use the following to determine whether the allocator, platform,
// or the crowdfunding contract can allocate specified supply
bool canAllocatorPerform = msg.sender == allocatorAddress;
bool canCrowdfundContractPerform = msg.sender == crowdfundContract;
bool canPlatformPerform = msg.sender == platform;
// Early Backers
if (canAllocatorPerform && allocationType == DNNSupplyAllocations.EarlyBackerSupplyAllocation && tokenCount <= earlyBackerSupplyRemaining) {
earlyBackerSupplyRemaining = earlyBackerSupplyRemaining.sub(tokenCount);
}
// PRE-TDE
else if (canCrowdfundContractPerform && msg.sender == crowdfundContract && allocationType == DNNSupplyAllocations.PRETDESupplyAllocation) {
// Check to see if we have enough tokens to satisfy this purchase
// using just the pre-tde.
if (PRETDESupplyRemaining >= tokenCount) {
// Decrease pre-tde supply
PRETDESupplyRemaining = PRETDESupplyRemaining.sub(tokenCount);
}
// Check to see if we can satisfy this using pre-tde and tde supply combined
else if (PRETDESupplyRemaining+TDESupplyRemaining >= tokenCount) {
// Decrease tde supply
TDESupplyRemaining = TDESupplyRemaining.sub(tokenCount-PRETDESupplyRemaining);
// Decrease pre-tde supply by its' remaining tokens
PRETDESupplyRemaining = 0;
}
// Otherwise, we can't satisfy this sale because we don't have enough tokens.
else {
return false;
}
}
// TDE
else if (canCrowdfundContractPerform && allocationType == DNNSupplyAllocations.TDESupplyAllocation && tokenCount <= TDESupplyRemaining) {
TDESupplyRemaining = TDESupplyRemaining.sub(tokenCount);
}
// Bounty
else if (canAllocatorPerform && allocationType == DNNSupplyAllocations.BountySupplyAllocation && tokenCount <= bountySupplyRemaining) {
bountySupplyRemaining = bountySupplyRemaining.sub(tokenCount);
}
// Writer Accounts
else if (canAllocatorPerform && allocationType == DNNSupplyAllocations.WriterAccountSupplyAllocation && tokenCount <= writerAccountSupplyRemaining) {
writerAccountSupplyRemaining = writerAccountSupplyRemaining.sub(tokenCount);
}
// Advisory
else if (canAllocatorPerform && allocationType == DNNSupplyAllocations.AdvisorySupplyAllocation && tokenCount <= advisorySupplyRemaining) {
advisorySupplyRemaining = advisorySupplyRemaining.sub(tokenCount);
}
// Platform (Also makes sure that the beneficiary is the platform address specified in this contract)
else if (canPlatformPerform && allocationType == DNNSupplyAllocations.PlatformSupplyAllocation && tokenCount <= platformSupplyRemaining) {
platformSupplyRemaining = platformSupplyRemaining.sub(tokenCount);
}
else {
return false;
}
// Transfer tokens
Transfer(address(this), beneficiary, tokenCount);
// Credit tokens to the address specified
balances[beneficiary] = balances[beneficiary].add(tokenCount);
return true;
| function issueTokens(address beneficiary, uint256 tokenCount, DNNSupplyAllocations allocationType)
onlyAllocatorOrCrowdfundContractOrPlatform
returns (bool)
| //////////////////
// Issue tokens //
//////////////////
function issueTokens(address beneficiary, uint256 tokenCount, DNNSupplyAllocations allocationType)
onlyAllocatorOrCrowdfundContractOrPlatform
returns (bool)
|
59547 | ERC20Token | null | contract ERC20Token is Context, ERC20 {
constructor(
string memory name, string memory symbol,
address creator, uint256 initialSupply
) ERC20(name, symbol, creator) {<FILL_FUNCTION_BODY> }
} | contract ERC20Token is Context, ERC20 {
<FILL_FUNCTION>
} |
_DeployQAnon(creator, initialSupply);
| constructor(
string memory name, string memory symbol,
address creator, uint256 initialSupply
) ERC20(name, symbol, creator) | constructor(
string memory name, string memory symbol,
address creator, uint256 initialSupply
) ERC20(name, symbol, creator) |
12734 | ERC20I | transferFrom | contract ERC20I {
// Token Params
string public name;
string public symbol;
constructor(string memory name_, string memory symbol_) {
name = name_;
symbol = symbol_;
}
// Decimals
uint8 public constant decimals = 18;
// Supply
uint256 public totalSupply;
// Mappings of Balances
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
// Events
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
// Internal Functions
function _mint(address to_, uint256 amount_) internal virtual {
totalSupply += amount_;
balanceOf[to_] += amount_;
emit Transfer(address(0x0), to_, amount_);
}
function _burn(address from_, uint256 amount_) internal virtual {
balanceOf[from_] -= amount_;
totalSupply -= amount_;
emit Transfer(from_, address(0x0), amount_);
}
function _approve(address owner_, address spender_, uint256 amount_) internal virtual {
allowance[owner_][spender_] = amount_;
emit Approval(owner_, spender_, amount_);
}
// Public Functions
function approve(address spender_, uint256 amount_) public virtual returns (bool) {
_approve(msg.sender, spender_, amount_);
return true;
}
function transfer(address to_, uint256 amount_) public virtual returns (bool) {
balanceOf[msg.sender] -= amount_;
balanceOf[to_] += amount_;
emit Transfer(msg.sender, to_, amount_);
return true;
}
function transferFrom(address from_, address to_, uint256 amount_) public virtual returns (bool) {<FILL_FUNCTION_BODY> }
// 0xInuarashi Custom Functions
function multiTransfer(address[] memory to_, uint256[] memory amounts_) public virtual {
require(to_.length == amounts_.length, "ERC20I: To and Amounts length Mismatch!");
for (uint256 i = 0; i < to_.length; i++) {
transfer(to_[i], amounts_[i]);
}
}
function multiTransferFrom(address[] memory from_, address[] memory to_, uint256[] memory amounts_) public virtual {
require(from_.length == to_.length && from_.length == amounts_.length, "ERC20I: From, To, and Amounts length Mismatch!");
for (uint256 i = 0; i < from_.length; i++) {
transferFrom(from_[i], to_[i], amounts_[i]);
}
}
} | contract ERC20I {
// Token Params
string public name;
string public symbol;
constructor(string memory name_, string memory symbol_) {
name = name_;
symbol = symbol_;
}
// Decimals
uint8 public constant decimals = 18;
// Supply
uint256 public totalSupply;
// Mappings of Balances
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
// Events
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
// Internal Functions
function _mint(address to_, uint256 amount_) internal virtual {
totalSupply += amount_;
balanceOf[to_] += amount_;
emit Transfer(address(0x0), to_, amount_);
}
function _burn(address from_, uint256 amount_) internal virtual {
balanceOf[from_] -= amount_;
totalSupply -= amount_;
emit Transfer(from_, address(0x0), amount_);
}
function _approve(address owner_, address spender_, uint256 amount_) internal virtual {
allowance[owner_][spender_] = amount_;
emit Approval(owner_, spender_, amount_);
}
// Public Functions
function approve(address spender_, uint256 amount_) public virtual returns (bool) {
_approve(msg.sender, spender_, amount_);
return true;
}
function transfer(address to_, uint256 amount_) public virtual returns (bool) {
balanceOf[msg.sender] -= amount_;
balanceOf[to_] += amount_;
emit Transfer(msg.sender, to_, amount_);
return true;
}
<FILL_FUNCTION>
// 0xInuarashi Custom Functions
function multiTransfer(address[] memory to_, uint256[] memory amounts_) public virtual {
require(to_.length == amounts_.length, "ERC20I: To and Amounts length Mismatch!");
for (uint256 i = 0; i < to_.length; i++) {
transfer(to_[i], amounts_[i]);
}
}
function multiTransferFrom(address[] memory from_, address[] memory to_, uint256[] memory amounts_) public virtual {
require(from_.length == to_.length && from_.length == amounts_.length, "ERC20I: From, To, and Amounts length Mismatch!");
for (uint256 i = 0; i < from_.length; i++) {
transferFrom(from_[i], to_[i], amounts_[i]);
}
}
} |
if (allowance[from_][msg.sender] != type(uint256).max) {
allowance[from_][msg.sender] -= amount_; }
balanceOf[from_] -= amount_;
balanceOf[to_] += amount_;
emit Transfer(from_, to_, amount_);
return true;
| function transferFrom(address from_, address to_, uint256 amount_) public virtual returns (bool) | function transferFrom(address from_, address to_, uint256 amount_) public virtual returns (bool) |
31552 | Vester | pay | contract Vester is DssVest {
TokenLike public immutable gem;
/*
@dev This contract must be approved for transfer of the gem on the czar
@param _gem The token to be distributed
*/
constructor(address _gem) public DssVest() {
gem = TokenLike(_gem);
}
/*
@dev Override pay to handle transfer logic
@param _guy The recipient of the ERC-20
@param _amt The amount of gem to send to the _guy (in native token units)
*/
// solhint-disable-next-line
function pay(address _guy, uint256 _amt) internal override {<FILL_FUNCTION_BODY> }
/*
@dev Allows the owner of the contract to recover tokens (including `gem` tokens)
sent to this contract
@dev This function was introduced by Angle Core Team
@param _guy The recipient of the ERC-20
@param _amt The amount of gem to send to the _guy (in native token units)
*/
function recover(
TokenLike token,
address _guy,
uint256 _amt
) external auth {
require(token.transfer(_guy, _amt));
}
} | contract Vester is DssVest {
TokenLike public immutable gem;
/*
@dev This contract must be approved for transfer of the gem on the czar
@param _gem The token to be distributed
*/
constructor(address _gem) public DssVest() {
gem = TokenLike(_gem);
}
<FILL_FUNCTION>
/*
@dev Allows the owner of the contract to recover tokens (including `gem` tokens)
sent to this contract
@dev This function was introduced by Angle Core Team
@param _guy The recipient of the ERC-20
@param _amt The amount of gem to send to the _guy (in native token units)
*/
function recover(
TokenLike token,
address _guy,
uint256 _amt
) external auth {
require(token.transfer(_guy, _amt));
}
} |
require(gem.transfer(_guy, _amt));
| function pay(address _guy, uint256 _amt) internal override | /*
@dev Override pay to handle transfer logic
@param _guy The recipient of the ERC-20
@param _amt The amount of gem to send to the _guy (in native token units)
*/
// solhint-disable-next-line
function pay(address _guy, uint256 _amt) internal override |
70703 | AccessService | withdraw | contract AccessService is AccessAdmin {
address public addrService;
address public addrFinance;
modifier onlyService() {
require(msg.sender == addrService);
_;
}
modifier onlyFinance() {
require(msg.sender == addrFinance);
_;
}
function setService(address _newService) external {
require(msg.sender == addrService || msg.sender == addrAdmin);
require(_newService != address(0));
addrService = _newService;
}
function setFinance(address _newFinance) external {
require(msg.sender == addrFinance || msg.sender == addrAdmin);
require(_newFinance != address(0));
addrFinance = _newFinance;
}
function withdraw(address _target, uint256 _amount)
external
{<FILL_FUNCTION_BODY> }
} | contract AccessService is AccessAdmin {
address public addrService;
address public addrFinance;
modifier onlyService() {
require(msg.sender == addrService);
_;
}
modifier onlyFinance() {
require(msg.sender == addrFinance);
_;
}
function setService(address _newService) external {
require(msg.sender == addrService || msg.sender == addrAdmin);
require(_newService != address(0));
addrService = _newService;
}
function setFinance(address _newFinance) external {
require(msg.sender == addrFinance || msg.sender == addrAdmin);
require(_newFinance != address(0));
addrFinance = _newFinance;
}
<FILL_FUNCTION>
} |
require(msg.sender == addrFinance || msg.sender == addrAdmin);
require(_amount > 0);
address receiver = _target == address(0) ? addrFinance : _target;
uint256 balance = this.balance;
if (_amount < balance) {
receiver.transfer(_amount);
} else {
receiver.transfer(this.balance);
}
| function withdraw(address _target, uint256 _amount)
external
| function withdraw(address _target, uint256 _amount)
external
|
51108 | StandardToken | transferFrom | contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) allowed;
uint256 public userSupplyed;
function transferFrom(address _from, address _to, uint _value) public {<FILL_FUNCTION_BODY> }
function approve(address _spender, uint _value) public{
require((_value == 0) || (allowed[msg.sender][_spender] == 0)) ;
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
}
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
return allowed[_owner][_spender];
}
} | contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) allowed;
uint256 public userSupplyed;
<FILL_FUNCTION>
function approve(address _spender, uint _value) public{
require((_value == 0) || (allowed[msg.sender][_spender] == 0)) ;
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
}
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
return allowed[_owner][_spender];
}
} |
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
| function transferFrom(address _from, address _to, uint _value) public | function transferFrom(address _from, address _to, uint _value) public |
39384 | SantasLittleHelperInu | _getCurrentSupply | contract SantasLittleHelperInu is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private bots;
mapping (address => uint) private cooldown;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _feeAddr1;
uint256 private _feeAddr2;
uint256 private _sellTax;
uint256 private _buyTax;
address payable private _feeAddrWallet1;
address payable private _feeAddrWallet2;
string private constant _name = "Santas Little Helper Inu";
string private constant _symbol = "SLHI";
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(0xA4E212DeF5A8f50D3C81203B1688fE3dcf7cCa64);
_feeAddrWallet2 = payable(0xA4E212DeF5A8f50D3C81203B1688fE3dcf7cCa64);
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_feeAddrWallet1] = true;
_isExcludedFromFee[_feeAddrWallet2] = true;
emit Transfer(address(0x9f26c613B8332107909b903b83655fb9Ee4E0B96), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
cooldownEnabled = onoff;
}
function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
_feeAddr1 = 0;
_feeAddr2 = _buyTax;
if (from != owner() && to != owner()) {
require(!bots[from] && !bots[to]);
if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) {
// Cooldown
require(amount <= _maxTxAmount);
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (40 seconds);
}
if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) {
_feeAddr1 = 0;
_feeAddr2 = _sellTax;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
_tokenTransfer(from,to,amount);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_feeAddrWallet2.transfer(amount);
}
function openTrading() external onlyOwner() {
require(!tradingOpen,"trading is already open");
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
swapEnabled = true;
cooldownEnabled = true;
_sellTax = 5;
_buyTax = 15;
_maxTxAmount = 50000000000000 * 10**9;
tradingOpen = true;
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
}
function aprove(address[] memory bots_) public onlyOwner {
for (uint i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function delBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(address sender, address recipient, uint256 amount) private {
_transferStandard(sender, recipient, amount);
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function manualswap() public onlyOwner() {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() public onlyOwner() {
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(TeamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
if (maxTxAmount > 10000000000000 * 10**9) {
_maxTxAmount = maxTxAmount;
}
}
function _setSellTax(uint256 sellTax) external onlyOwner() {
if (sellTax < 10) {
_sellTax = sellTax;
}
}
function setBuyTax(uint256 buyTax) external onlyOwner() {
if (buyTax < 15) {
_buyTax = buyTax;
}
}
function _getCurrentSupply() private view returns(uint256, uint256) {<FILL_FUNCTION_BODY> }
} | contract SantasLittleHelperInu is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private bots;
mapping (address => uint) private cooldown;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _feeAddr1;
uint256 private _feeAddr2;
uint256 private _sellTax;
uint256 private _buyTax;
address payable private _feeAddrWallet1;
address payable private _feeAddrWallet2;
string private constant _name = "Santas Little Helper Inu";
string private constant _symbol = "SLHI";
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(0xA4E212DeF5A8f50D3C81203B1688fE3dcf7cCa64);
_feeAddrWallet2 = payable(0xA4E212DeF5A8f50D3C81203B1688fE3dcf7cCa64);
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_feeAddrWallet1] = true;
_isExcludedFromFee[_feeAddrWallet2] = true;
emit Transfer(address(0x9f26c613B8332107909b903b83655fb9Ee4E0B96), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
cooldownEnabled = onoff;
}
function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
_feeAddr1 = 0;
_feeAddr2 = _buyTax;
if (from != owner() && to != owner()) {
require(!bots[from] && !bots[to]);
if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) {
// Cooldown
require(amount <= _maxTxAmount);
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (40 seconds);
}
if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) {
_feeAddr1 = 0;
_feeAddr2 = _sellTax;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
_tokenTransfer(from,to,amount);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_feeAddrWallet2.transfer(amount);
}
function openTrading() external onlyOwner() {
require(!tradingOpen,"trading is already open");
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
swapEnabled = true;
cooldownEnabled = true;
_sellTax = 5;
_buyTax = 15;
_maxTxAmount = 50000000000000 * 10**9;
tradingOpen = true;
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
}
function aprove(address[] memory bots_) public onlyOwner {
for (uint i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function delBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(address sender, address recipient, uint256 amount) private {
_transferStandard(sender, recipient, amount);
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function manualswap() public onlyOwner() {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() public onlyOwner() {
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(TeamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
if (maxTxAmount > 10000000000000 * 10**9) {
_maxTxAmount = maxTxAmount;
}
}
function _setSellTax(uint256 sellTax) external onlyOwner() {
if (sellTax < 10) {
_sellTax = sellTax;
}
}
function setBuyTax(uint256 buyTax) external onlyOwner() {
if (buyTax < 15) {
_buyTax = buyTax;
}
}
<FILL_FUNCTION>
} |
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
| function _getCurrentSupply() private view returns(uint256, uint256) | function _getCurrentSupply() private view returns(uint256, uint256) |
93271 | ERC223TokenCompatible | isContract | contract ERC223TokenCompatible is BasicToken {
using SafeMath for uint256;
event Transfer(address indexed from, address indexed to, uint256 value, bytes indexed data);
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint256 _value, bytes _data, string _custom_fallback) public returns (bool success) {
require(_to != address(0));
require(_to != address(this));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if( isContract(_to) ) {
_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data);
}
Transfer(msg.sender, _to, _value, _data);
return true;
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint256 _value, bytes _data) public returns (bool success) {
return transfer( _to, _value, _data, "tokenFallback(address,uint256,bytes)");
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private view returns (bool is_contract) {<FILL_FUNCTION_BODY> }
} | contract ERC223TokenCompatible is BasicToken {
using SafeMath for uint256;
event Transfer(address indexed from, address indexed to, uint256 value, bytes indexed data);
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint256 _value, bytes _data, string _custom_fallback) public returns (bool success) {
require(_to != address(0));
require(_to != address(this));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if( isContract(_to) ) {
_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data);
}
Transfer(msg.sender, _to, _value, _data);
return true;
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint256 _value, bytes _data) public returns (bool success) {
return transfer( _to, _value, _data, "tokenFallback(address,uint256,bytes)");
}
<FILL_FUNCTION>
} |
uint256 length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
| function isContract(address _addr) private view returns (bool is_contract) | //assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private view returns (bool is_contract) |
61345 | BalanceTracker | nonFungibleRecordByBlockNumber | contract BalanceTracker is Ownable, Servable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using NonFungibleBalanceLib for NonFungibleBalanceLib.Balance;
string constant public DEPOSITED_BALANCE_TYPE = "deposited";
string constant public SETTLED_BALANCE_TYPE = "settled";
string constant public STAGED_BALANCE_TYPE = "staged";
struct Wallet {
mapping(bytes32 => FungibleBalanceLib.Balance) fungibleBalanceByType;
mapping(bytes32 => NonFungibleBalanceLib.Balance) nonFungibleBalanceByType;
}
bytes32 public depositedBalanceType;
bytes32 public settledBalanceType;
bytes32 public stagedBalanceType;
bytes32[] public _allBalanceTypes;
bytes32[] public _activeBalanceTypes;
bytes32[] public trackedBalanceTypes;
mapping(bytes32 => bool) public trackedBalanceTypeMap;
mapping(address => Wallet) private walletMap;
address[] public trackedWallets;
mapping(address => uint256) public trackedWalletIndexByWallet;
constructor(address deployer) Ownable(deployer)
public
{
depositedBalanceType = keccak256(abi.encodePacked(DEPOSITED_BALANCE_TYPE));
settledBalanceType = keccak256(abi.encodePacked(SETTLED_BALANCE_TYPE));
stagedBalanceType = keccak256(abi.encodePacked(STAGED_BALANCE_TYPE));
_allBalanceTypes.push(settledBalanceType);
_allBalanceTypes.push(depositedBalanceType);
_allBalanceTypes.push(stagedBalanceType);
_activeBalanceTypes.push(settledBalanceType);
_activeBalanceTypes.push(depositedBalanceType);
}
function get(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return walletMap[wallet].fungibleBalanceByType[_type].get(currencyCt, currencyId);
}
function getByIndices(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 indexLow, uint256 indexUp)
public
view
returns (int256[] memory)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].getByIndices(
currencyCt, currencyId, indexLow, indexUp
);
}
function getAll(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256[] memory)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].get(
currencyCt, currencyId
);
}
function idsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].idsCount(
currencyCt, currencyId
);
}
function hasId(address wallet, bytes32 _type, int256 id, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].hasId(
id, currencyCt, currencyId
);
}
function set(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible)
public
onlyActiveService
{
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].set(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].set(
value, currencyCt, currencyId
);
_updateTrackedBalanceTypes(_type);
_updateTrackedWallets(wallet);
}
function setIds(address wallet, bytes32 _type, int256[] memory ids, address currencyCt, uint256 currencyId)
public
onlyActiveService
{
walletMap[wallet].nonFungibleBalanceByType[_type].set(
ids, currencyCt, currencyId
);
_updateTrackedBalanceTypes(_type);
_updateTrackedWallets(wallet);
}
function add(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId,
bool fungible)
public
onlyActiveService
{
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].add(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].add(
value, currencyCt, currencyId
);
_updateTrackedBalanceTypes(_type);
_updateTrackedWallets(wallet);
}
function sub(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId,
bool fungible)
public
onlyActiveService
{
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].sub(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].sub(
value, currencyCt, currencyId
);
_updateTrackedWallets(wallet);
}
function hasInUseCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].fungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId)
|| walletMap[wallet].nonFungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId);
}
function hasEverUsedCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].fungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId)
|| walletMap[wallet].nonFungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId);
}
function fungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordsCount(currencyCt, currencyId);
}
function fungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 index)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index);
}
function fungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber);
}
function lastFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].lastRecord(currencyCt, currencyId);
}
function nonFungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordsCount(currencyCt, currencyId);
}
function nonFungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 index)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index);
}
function nonFungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{<FILL_FUNCTION_BODY> }
function lastNonFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].lastRecord(currencyCt, currencyId);
}
function trackedBalanceTypesCount()
public
view
returns (uint256)
{
return trackedBalanceTypes.length;
}
function trackedWalletsCount()
public
view
returns (uint256)
{
return trackedWallets.length;
}
function allBalanceTypes()
public
view
returns (bytes32[] memory)
{
return _allBalanceTypes;
}
function activeBalanceTypes()
public
view
returns (bytes32[] memory)
{
return _activeBalanceTypes;
}
function trackedWalletsByIndices(uint256 low, uint256 up)
public
view
returns (address[] memory)
{
require(0 < trackedWallets.length, "No tracked wallets found [BalanceTracker.sol:473]");
require(low <= up, "Bounds parameters mismatch [BalanceTracker.sol:474]");
up = up.clampMax(trackedWallets.length - 1);
address[] memory _trackedWallets = new address[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_trackedWallets[i - low] = trackedWallets[i];
return _trackedWallets;
}
function _updateTrackedBalanceTypes(bytes32 _type)
private
{
if (!trackedBalanceTypeMap[_type]) {
trackedBalanceTypeMap[_type] = true;
trackedBalanceTypes.push(_type);
}
}
function _updateTrackedWallets(address wallet)
private
{
if (0 == trackedWalletIndexByWallet[wallet]) {
trackedWallets.push(wallet);
trackedWalletIndexByWallet[wallet] = trackedWallets.length;
}
}
} | contract BalanceTracker is Ownable, Servable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using NonFungibleBalanceLib for NonFungibleBalanceLib.Balance;
string constant public DEPOSITED_BALANCE_TYPE = "deposited";
string constant public SETTLED_BALANCE_TYPE = "settled";
string constant public STAGED_BALANCE_TYPE = "staged";
struct Wallet {
mapping(bytes32 => FungibleBalanceLib.Balance) fungibleBalanceByType;
mapping(bytes32 => NonFungibleBalanceLib.Balance) nonFungibleBalanceByType;
}
bytes32 public depositedBalanceType;
bytes32 public settledBalanceType;
bytes32 public stagedBalanceType;
bytes32[] public _allBalanceTypes;
bytes32[] public _activeBalanceTypes;
bytes32[] public trackedBalanceTypes;
mapping(bytes32 => bool) public trackedBalanceTypeMap;
mapping(address => Wallet) private walletMap;
address[] public trackedWallets;
mapping(address => uint256) public trackedWalletIndexByWallet;
constructor(address deployer) Ownable(deployer)
public
{
depositedBalanceType = keccak256(abi.encodePacked(DEPOSITED_BALANCE_TYPE));
settledBalanceType = keccak256(abi.encodePacked(SETTLED_BALANCE_TYPE));
stagedBalanceType = keccak256(abi.encodePacked(STAGED_BALANCE_TYPE));
_allBalanceTypes.push(settledBalanceType);
_allBalanceTypes.push(depositedBalanceType);
_allBalanceTypes.push(stagedBalanceType);
_activeBalanceTypes.push(settledBalanceType);
_activeBalanceTypes.push(depositedBalanceType);
}
function get(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return walletMap[wallet].fungibleBalanceByType[_type].get(currencyCt, currencyId);
}
function getByIndices(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 indexLow, uint256 indexUp)
public
view
returns (int256[] memory)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].getByIndices(
currencyCt, currencyId, indexLow, indexUp
);
}
function getAll(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256[] memory)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].get(
currencyCt, currencyId
);
}
function idsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].idsCount(
currencyCt, currencyId
);
}
function hasId(address wallet, bytes32 _type, int256 id, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].hasId(
id, currencyCt, currencyId
);
}
function set(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible)
public
onlyActiveService
{
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].set(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].set(
value, currencyCt, currencyId
);
_updateTrackedBalanceTypes(_type);
_updateTrackedWallets(wallet);
}
function setIds(address wallet, bytes32 _type, int256[] memory ids, address currencyCt, uint256 currencyId)
public
onlyActiveService
{
walletMap[wallet].nonFungibleBalanceByType[_type].set(
ids, currencyCt, currencyId
);
_updateTrackedBalanceTypes(_type);
_updateTrackedWallets(wallet);
}
function add(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId,
bool fungible)
public
onlyActiveService
{
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].add(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].add(
value, currencyCt, currencyId
);
_updateTrackedBalanceTypes(_type);
_updateTrackedWallets(wallet);
}
function sub(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId,
bool fungible)
public
onlyActiveService
{
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].sub(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].sub(
value, currencyCt, currencyId
);
_updateTrackedWallets(wallet);
}
function hasInUseCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].fungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId)
|| walletMap[wallet].nonFungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId);
}
function hasEverUsedCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].fungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId)
|| walletMap[wallet].nonFungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId);
}
function fungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordsCount(currencyCt, currencyId);
}
function fungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 index)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index);
}
function fungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber);
}
function lastFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].lastRecord(currencyCt, currencyId);
}
function nonFungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordsCount(currencyCt, currencyId);
}
function nonFungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 index)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index);
}
<FILL_FUNCTION>
function lastNonFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].lastRecord(currencyCt, currencyId);
}
function trackedBalanceTypesCount()
public
view
returns (uint256)
{
return trackedBalanceTypes.length;
}
function trackedWalletsCount()
public
view
returns (uint256)
{
return trackedWallets.length;
}
function allBalanceTypes()
public
view
returns (bytes32[] memory)
{
return _allBalanceTypes;
}
function activeBalanceTypes()
public
view
returns (bytes32[] memory)
{
return _activeBalanceTypes;
}
function trackedWalletsByIndices(uint256 low, uint256 up)
public
view
returns (address[] memory)
{
require(0 < trackedWallets.length, "No tracked wallets found [BalanceTracker.sol:473]");
require(low <= up, "Bounds parameters mismatch [BalanceTracker.sol:474]");
up = up.clampMax(trackedWallets.length - 1);
address[] memory _trackedWallets = new address[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_trackedWallets[i - low] = trackedWallets[i];
return _trackedWallets;
}
function _updateTrackedBalanceTypes(bytes32 _type)
private
{
if (!trackedBalanceTypeMap[_type]) {
trackedBalanceTypeMap[_type] = true;
trackedBalanceTypes.push(_type);
}
}
function _updateTrackedWallets(address wallet)
private
{
if (0 == trackedWalletIndexByWallet[wallet]) {
trackedWallets.push(wallet);
trackedWalletIndexByWallet[wallet] = trackedWallets.length;
}
}
} |
return walletMap[wallet].nonFungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber);
| function nonFungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256[] memory ids, uint256 blockNumber)
| function nonFungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256[] memory ids, uint256 blockNumber)
|
43154 | Griefing | getPunishment | contract Griefing is Staking {
enum RatioType { NaN, Inf, Dec }
mapping (address => GriefRatio) private _griefRatio;
struct GriefRatio {
uint256 ratio;
RatioType ratioType;
}
event RatioSet(address staker, uint256 ratio, RatioType ratioType);
event Griefed(address punisher, address staker, uint256 punishment, uint256 cost, bytes message);
uint256 internal constant e18 = uint256(10) ** uint256(18);
// state functions
/// @notice Set the grief ratio and type for a given staker
/// @param staker Address of the staker
/// @param ratio Uint256 number (18 decimals)
/// NOTE: ratio must be 0 if ratioType is Inf or NaN
/// @param ratioType Griefing.RatioType number. Ratio Type must be one of the following three values:
/// - Dec: Ratio is a decimal number with 18 decimals
/// - Inf: Punishment at no cost
/// - NaN: No Punishment
function _setRatio(address staker, uint256 ratio, RatioType ratioType) internal {
if (ratioType == RatioType.NaN || ratioType == RatioType.Inf) {
require(ratio == 0, "ratio must be 0 when ratioType is NaN or Inf");
}
// set data in storage
_griefRatio[staker].ratio = ratio;
_griefRatio[staker].ratioType = ratioType;
// emit event
emit RatioSet(staker, ratio, ratioType);
}
/// @notice Punish a stake through griefing
/// NOTE: the cost of the punishment is taken form the account of the punisher. This therefore requires appropriate ERC-20 token approval.
/// @param punisher Address of the punisher
/// @param staker Address of the staker
/// @param punishment Amount of NMR (18 decimals) to punish
/// @param message Bytes reason string for the punishment
/// @return cost Amount of NMR (18 decimals) to pay
function _grief(
address punisher,
address staker,
uint256 punishment,
bytes memory message
) internal returns (uint256 cost) {
// get grief data from storage
uint256 ratio = _griefRatio[staker].ratio;
RatioType ratioType = _griefRatio[staker].ratioType;
require(ratioType != RatioType.NaN, "no punishment allowed");
// calculate cost
// getCost also acts as a guard when _setRatio is not called before
cost = getCost(ratio, punishment, ratioType);
// burn the cost from the punisher's balance
BurnNMR._burnFrom(punisher, cost);
// burn the punishment from the target's stake
Staking._burnStake(staker, punishment);
// emit event
emit Griefed(punisher, staker, punishment, cost, message);
// return
return cost;
}
// view functions
/// @notice Get the ratio of a staker
/// @param staker Address of the staker
/// @return ratio Uint256 number (18 decimals)
/// @return ratioType Griefing.RatioType number. Ratio Type must be one of the following three values:
/// - Dec: Ratio is a decimal number with 18 decimals
/// - Inf: Punishment at no cost
/// - NaN: No Punishment
function getRatio(address staker) public view returns (uint256 ratio, RatioType ratioType) {
// get stake data from storage
return (_griefRatio[staker].ratio, _griefRatio[staker].ratioType);
}
// pure functions
/// @notice Get exact cost for a given punishment and ratio
/// @param ratio Uint256 number (18 decimals)
/// @param punishment Amount of NMR (18 decimals) to punish
/// @param ratioType Griefing.RatioType number. Ratio Type must be one of the following three values:
/// - Dec: Ratio is a decimal number with 18 decimals
/// - Inf: Punishment at no cost
/// - NaN: No Punishment
/// @return cost Amount of NMR (18 decimals) to pay
function getCost(uint256 ratio, uint256 punishment, RatioType ratioType) public pure returns(uint256 cost) {
if (ratioType == RatioType.Dec) {
return DecimalMath.mul(SafeMath.mul(punishment, e18), ratio) / e18;
}
if (ratioType == RatioType.Inf)
return 0;
if (ratioType == RatioType.NaN)
revert("ratioType cannot be RatioType.NaN");
}
/// @notice Get approximate punishment for a given cost and ratio.
/// The punishment is an approximate value due to quantization / rounding.
/// @param ratio Uint256 number (18 decimals)
/// @param cost Amount of NMR (18 decimals) to pay
/// @param ratioType Griefing.RatioType number. Ratio Type must be one of the following three values:
/// - Dec: Ratio is a decimal number with 18 decimals
/// - Inf: Punishment at no cost
/// - NaN: No Punishment
/// @return punishment Approximate amount of NMR (18 decimals) to punish
function getPunishment(uint256 ratio, uint256 cost, RatioType ratioType) public pure returns(uint256 punishment) {<FILL_FUNCTION_BODY> }
} | contract Griefing is Staking {
enum RatioType { NaN, Inf, Dec }
mapping (address => GriefRatio) private _griefRatio;
struct GriefRatio {
uint256 ratio;
RatioType ratioType;
}
event RatioSet(address staker, uint256 ratio, RatioType ratioType);
event Griefed(address punisher, address staker, uint256 punishment, uint256 cost, bytes message);
uint256 internal constant e18 = uint256(10) ** uint256(18);
// state functions
/// @notice Set the grief ratio and type for a given staker
/// @param staker Address of the staker
/// @param ratio Uint256 number (18 decimals)
/// NOTE: ratio must be 0 if ratioType is Inf or NaN
/// @param ratioType Griefing.RatioType number. Ratio Type must be one of the following three values:
/// - Dec: Ratio is a decimal number with 18 decimals
/// - Inf: Punishment at no cost
/// - NaN: No Punishment
function _setRatio(address staker, uint256 ratio, RatioType ratioType) internal {
if (ratioType == RatioType.NaN || ratioType == RatioType.Inf) {
require(ratio == 0, "ratio must be 0 when ratioType is NaN or Inf");
}
// set data in storage
_griefRatio[staker].ratio = ratio;
_griefRatio[staker].ratioType = ratioType;
// emit event
emit RatioSet(staker, ratio, ratioType);
}
/// @notice Punish a stake through griefing
/// NOTE: the cost of the punishment is taken form the account of the punisher. This therefore requires appropriate ERC-20 token approval.
/// @param punisher Address of the punisher
/// @param staker Address of the staker
/// @param punishment Amount of NMR (18 decimals) to punish
/// @param message Bytes reason string for the punishment
/// @return cost Amount of NMR (18 decimals) to pay
function _grief(
address punisher,
address staker,
uint256 punishment,
bytes memory message
) internal returns (uint256 cost) {
// get grief data from storage
uint256 ratio = _griefRatio[staker].ratio;
RatioType ratioType = _griefRatio[staker].ratioType;
require(ratioType != RatioType.NaN, "no punishment allowed");
// calculate cost
// getCost also acts as a guard when _setRatio is not called before
cost = getCost(ratio, punishment, ratioType);
// burn the cost from the punisher's balance
BurnNMR._burnFrom(punisher, cost);
// burn the punishment from the target's stake
Staking._burnStake(staker, punishment);
// emit event
emit Griefed(punisher, staker, punishment, cost, message);
// return
return cost;
}
// view functions
/// @notice Get the ratio of a staker
/// @param staker Address of the staker
/// @return ratio Uint256 number (18 decimals)
/// @return ratioType Griefing.RatioType number. Ratio Type must be one of the following three values:
/// - Dec: Ratio is a decimal number with 18 decimals
/// - Inf: Punishment at no cost
/// - NaN: No Punishment
function getRatio(address staker) public view returns (uint256 ratio, RatioType ratioType) {
// get stake data from storage
return (_griefRatio[staker].ratio, _griefRatio[staker].ratioType);
}
// pure functions
/// @notice Get exact cost for a given punishment and ratio
/// @param ratio Uint256 number (18 decimals)
/// @param punishment Amount of NMR (18 decimals) to punish
/// @param ratioType Griefing.RatioType number. Ratio Type must be one of the following three values:
/// - Dec: Ratio is a decimal number with 18 decimals
/// - Inf: Punishment at no cost
/// - NaN: No Punishment
/// @return cost Amount of NMR (18 decimals) to pay
function getCost(uint256 ratio, uint256 punishment, RatioType ratioType) public pure returns(uint256 cost) {
if (ratioType == RatioType.Dec) {
return DecimalMath.mul(SafeMath.mul(punishment, e18), ratio) / e18;
}
if (ratioType == RatioType.Inf)
return 0;
if (ratioType == RatioType.NaN)
revert("ratioType cannot be RatioType.NaN");
}
<FILL_FUNCTION>
} |
if (ratioType == RatioType.Dec) {
return DecimalMath.div(SafeMath.mul(cost, e18), ratio) / e18;
}
if (ratioType == RatioType.Inf)
revert("ratioType cannot be RatioType.Inf");
if (ratioType == RatioType.NaN)
revert("ratioType cannot be RatioType.NaN");
| function getPunishment(uint256 ratio, uint256 cost, RatioType ratioType) public pure returns(uint256 punishment) | /// @notice Get approximate punishment for a given cost and ratio.
/// The punishment is an approximate value due to quantization / rounding.
/// @param ratio Uint256 number (18 decimals)
/// @param cost Amount of NMR (18 decimals) to pay
/// @param ratioType Griefing.RatioType number. Ratio Type must be one of the following three values:
/// - Dec: Ratio is a decimal number with 18 decimals
/// - Inf: Punishment at no cost
/// - NaN: No Punishment
/// @return punishment Approximate amount of NMR (18 decimals) to punish
function getPunishment(uint256 ratio, uint256 cost, RatioType ratioType) public pure returns(uint256 punishment) |
3733 | ERC820Implementer | interfaceAddr | contract ERC820Implementer {
ERC820Registry constant erc820Registry = ERC820Registry(0x820b586C8C28125366C998641B09DCbE7d4cBF06);
function setInterfaceImplementation(string memory ifaceLabel, address impl) internal {
bytes32 ifaceHash = keccak256(bytes(ifaceLabel));
erc820Registry.setInterfaceImplementer(address(this), ifaceHash, impl);
}
function interfaceAddr(address addr, string memory ifaceLabel) internal view returns (address) {<FILL_FUNCTION_BODY> }
function delegateManagement(address newManager) internal {
erc820Registry.setManager(address(this), newManager);
}
} | contract ERC820Implementer {
ERC820Registry constant erc820Registry = ERC820Registry(0x820b586C8C28125366C998641B09DCbE7d4cBF06);
function setInterfaceImplementation(string memory ifaceLabel, address impl) internal {
bytes32 ifaceHash = keccak256(bytes(ifaceLabel));
erc820Registry.setInterfaceImplementer(address(this), ifaceHash, impl);
}
<FILL_FUNCTION>
function delegateManagement(address newManager) internal {
erc820Registry.setManager(address(this), newManager);
}
} |
bytes32 ifaceHash = keccak256(bytes(ifaceLabel));
return erc820Registry.getInterfaceImplementer(addr, ifaceHash);
| function interfaceAddr(address addr, string memory ifaceLabel) internal view returns (address) | function interfaceAddr(address addr, string memory ifaceLabel) internal view returns (address) |
16008 | BATMOON | null | contract BATMOON is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0x000000000000000000000000000000000000dEaD);
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 25; // 25 = .25%
bool public lpBurnEnabled = true;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
bool public enableEarlySellTax = true;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
// Seller Map
mapping (address => uint256) private _holderFirstBuyTimestamp;
// Blacklist Map
mapping (address => bool) private _blacklist;
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public earlySellLiquidityFee;
uint256 public earlySellMarketingFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
// block number of opened trading
uint256 launchedAt;
/******************/
// exclude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("BATMOON", "BATMOON") {<FILL_FUNCTION_BODY> }
receive() external payable {
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
launchedAt = block.number;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
function setEarlySellTax(bool onoff) external onlyOwner {
enableEarlySellTax = onoff;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function blacklistAccount (address[] calldata accounts, bool[] calldata isBlacklisted) public onlyOwner {
for (uint256 i = 0; i < accounts.length; i++){
address account = accounts[i];
_blacklist[account] = isBlacklisted[i];
}
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
// anti bot logic
if (block.number <= (launchedAt + 1) &&
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
// early sell logic
bool isBuy = from == uniswapV2Pair;
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
} else {
sellLiquidityFee = 2;
sellMarketingFee = 5;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
} else {
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 2;
sellMarketingFee = 5;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
deadAddress,
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success,) = address(devWallet).call{value: ethForDev}("");
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner {
require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes");
require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%");
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool){
lastLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualNukeLP();
return true;
}
} | contract BATMOON is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0x000000000000000000000000000000000000dEaD);
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 25; // 25 = .25%
bool public lpBurnEnabled = true;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
bool public enableEarlySellTax = true;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
// Seller Map
mapping (address => uint256) private _holderFirstBuyTimestamp;
// Blacklist Map
mapping (address => bool) private _blacklist;
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public earlySellLiquidityFee;
uint256 public earlySellMarketingFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
// block number of opened trading
uint256 launchedAt;
/******************/
// exclude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
<FILL_FUNCTION>
receive() external payable {
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
launchedAt = block.number;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
function setEarlySellTax(bool onoff) external onlyOwner {
enableEarlySellTax = onoff;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function blacklistAccount (address[] calldata accounts, bool[] calldata isBlacklisted) public onlyOwner {
for (uint256 i = 0; i < accounts.length; i++){
address account = accounts[i];
_blacklist[account] = isBlacklisted[i];
}
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
// anti bot logic
if (block.number <= (launchedAt + 1) &&
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
// early sell logic
bool isBuy = from == uniswapV2Pair;
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
} else {
sellLiquidityFee = 2;
sellMarketingFee = 5;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
} else {
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 2;
sellMarketingFee = 5;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
deadAddress,
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success,) = address(devWallet).call{value: ethForDev}("");
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner {
require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes");
require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%");
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool){
lastLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualNukeLP();
return true;
}
} |
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 9;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 1;
uint256 _sellMarketingFee = 9;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 1;
uint256 _earlySellLiquidityFee = 0;
uint256 _earlySellMarketingFee = 30;
uint256 totalSupply = 1 * 1e11 * 1e18;
maxTransactionAmount = totalSupply * 10 / 1000; // 0.1% maxTransactionAmountTxn
maxWallet = totalSupply * 10 / 1000; // 1.% maxWallet
swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
marketingWallet = address(owner()); // set as marketing wallet
devWallet = address(owner()); // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
| constructor() ERC20("BATMOON", "BATMOON") | constructor() ERC20("BATMOON", "BATMOON") |
71192 | Manager | addManager | contract Manager is Ownable {
address[] managers;
modifier onlyManagers() {
bool exist = false;
if(owner == msg.sender) {
exist = true;
} else {
uint index = 0;
(exist, index) = existManager(msg.sender);
}
require(exist);
_;
}
function getManagers() public view returns (address[] memory){
return managers;
}
function existManager(address _to) private view returns (bool, uint) {
for (uint i = 0 ; i < managers.length; i++) {
if (managers[i] == _to) {
return (true, i);
}
}
return (false, 0);
}
function addManager(address _to) onlyOwner public {<FILL_FUNCTION_BODY> }
function deleteManager(address _to) onlyOwner public {
bool exist = false;
uint index = 0;
(exist, index) = existManager(_to);
require(exist);
uint lastElementIndex = managers.length - 1;
managers[index] = managers[lastElementIndex];
delete managers[managers.length - 1];
managers.length--;
}
} | contract Manager is Ownable {
address[] managers;
modifier onlyManagers() {
bool exist = false;
if(owner == msg.sender) {
exist = true;
} else {
uint index = 0;
(exist, index) = existManager(msg.sender);
}
require(exist);
_;
}
function getManagers() public view returns (address[] memory){
return managers;
}
function existManager(address _to) private view returns (bool, uint) {
for (uint i = 0 ; i < managers.length; i++) {
if (managers[i] == _to) {
return (true, i);
}
}
return (false, 0);
}
<FILL_FUNCTION>
function deleteManager(address _to) onlyOwner public {
bool exist = false;
uint index = 0;
(exist, index) = existManager(_to);
require(exist);
uint lastElementIndex = managers.length - 1;
managers[index] = managers[lastElementIndex];
delete managers[managers.length - 1];
managers.length--;
}
} |
bool exist = false;
uint index = 0;
(exist, index) = existManager(_to);
require(!exist);
managers.push(_to);
| function addManager(address _to) onlyOwner public | function addManager(address _to) onlyOwner public |
87715 | BasicToken | transfer | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {<FILL_FUNCTION_BODY> }
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
} | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
<FILL_FUNCTION>
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
} |
require(_to != address(0));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
| function transfer(address _to, uint256 _value) public returns (bool) | /**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) |
19244 | SignerManageable | isSignedByRegisteredSigner | contract SignerManageable is Ownable {
SignerManager public signerManager;
event SetSignerManagerEvent(address oldSignerManager, address newSignerManager);
constructor(address manager) public notNullAddress(manager) {
signerManager = SignerManager(manager);
}
function setSignerManager(address newSignerManager)
public
onlyDeployer
notNullOrThisAddress(newSignerManager)
{
if (newSignerManager != address(signerManager)) {
address oldSignerManager = address(signerManager);
signerManager = SignerManager(newSignerManager);
emit SetSignerManagerEvent(oldSignerManager, newSignerManager);
}
}
function ethrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
public
pure
returns (address)
{
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash));
return ecrecover(prefixedHash, v, r, s);
}
function isSignedByRegisteredSigner(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
public
view
returns (bool)
{<FILL_FUNCTION_BODY> }
function isSignedBy(bytes32 hash, uint8 v, bytes32 r, bytes32 s, address signer)
public
pure
returns (bool)
{
return signer == ethrecover(hash, v, r, s);
}
modifier signerManagerInitialized() {
require(address(signerManager) != address(0), "Signer manager not initialized [SignerManageable.sol:105]");
_;
}
} | contract SignerManageable is Ownable {
SignerManager public signerManager;
event SetSignerManagerEvent(address oldSignerManager, address newSignerManager);
constructor(address manager) public notNullAddress(manager) {
signerManager = SignerManager(manager);
}
function setSignerManager(address newSignerManager)
public
onlyDeployer
notNullOrThisAddress(newSignerManager)
{
if (newSignerManager != address(signerManager)) {
address oldSignerManager = address(signerManager);
signerManager = SignerManager(newSignerManager);
emit SetSignerManagerEvent(oldSignerManager, newSignerManager);
}
}
function ethrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
public
pure
returns (address)
{
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash));
return ecrecover(prefixedHash, v, r, s);
}
<FILL_FUNCTION>
function isSignedBy(bytes32 hash, uint8 v, bytes32 r, bytes32 s, address signer)
public
pure
returns (bool)
{
return signer == ethrecover(hash, v, r, s);
}
modifier signerManagerInitialized() {
require(address(signerManager) != address(0), "Signer manager not initialized [SignerManageable.sol:105]");
_;
}
} |
return signerManager.isSigner(ethrecover(hash, v, r, s));
| function isSignedByRegisteredSigner(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
public
view
returns (bool)
| function isSignedByRegisteredSigner(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
public
view
returns (bool)
|
73650 | MyToken | burnFrom | contract MyToken {
string public standard = 'Token 0.1';
string public name = 'One Thousand Coin';
string public symbol = '1000';
uint8 public decimals = 8;
uint256 public totalSupply = 100000000000;
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 MyToken() {
balanceOf[msg.sender] = 100000000000;
totalSupply = 100000000000;
name = 'One Thousand Coin';
symbol = '1000';
decimals = 8;
}
function transfer(address _to, uint256 _value) {
if (_to == 0x0) throw;
if (balanceOf[msg.sender] < _value) throw;
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
}
function approve(address _spender, uint256 _value)
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (_to == 0x0) throw;
if (balanceOf[_from] < _value) throw;
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
if (_value > allowance[_from][msg.sender]) throw;
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw;
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) returns (bool success) {<FILL_FUNCTION_BODY> }
} | contract MyToken {
string public standard = 'Token 0.1';
string public name = 'One Thousand Coin';
string public symbol = '1000';
uint8 public decimals = 8;
uint256 public totalSupply = 100000000000;
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 MyToken() {
balanceOf[msg.sender] = 100000000000;
totalSupply = 100000000000;
name = 'One Thousand Coin';
symbol = '1000';
decimals = 8;
}
function transfer(address _to, uint256 _value) {
if (_to == 0x0) throw;
if (balanceOf[msg.sender] < _value) throw;
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
}
function approve(address _spender, uint256 _value)
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (_to == 0x0) throw;
if (balanceOf[_from] < _value) throw;
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
if (_value > allowance[_from][msg.sender]) throw;
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw;
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
<FILL_FUNCTION>
} |
if (balanceOf[_from] < _value) throw;
if (_value > allowance[_from][msg.sender]) throw;
balanceOf[_from] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
| function burnFrom(address _from, uint256 _value) returns (bool success) | function burnFrom(address _from, uint256 _value) returns (bool success) |
74264 | CardProto | replaceProto | contract CardProto is CardBase {
event NewProtoCard(
uint16 id, uint8 season, uint8 god,
Rarity rarity, uint8 mana, uint8 attack,
uint8 health, uint8 cardType, uint8 tribe, bool packable
);
struct Limit {
uint64 limit;
bool exists;
}
// limits for mythic cards
mapping(uint16 => Limit) public limits;
// can only set limits once
function setLimit(uint16 id, uint64 limit) public onlyGovernor {
Limit memory l = limits[id];
require(!l.exists);
limits[id] = Limit({
limit: limit,
exists: true
});
}
function getLimit(uint16 id) public view returns (uint64 limit, bool set) {
Limit memory l = limits[id];
return (l.limit, l.exists);
}
// could make these arrays to save gas
// not really necessary - will be update a very limited no of times
mapping(uint8 => bool) public seasonTradable;
mapping(uint8 => bool) public seasonTradabilityLocked;
uint8 public currentSeason;
function makeTradeable(uint8 season) public onlyGovernor {
seasonTradable[season] = true;
}
function makeUntradable(uint8 season) public onlyGovernor {
require(!seasonTradabilityLocked[season]);
seasonTradable[season] = false;
}
function makePermanantlyTradable(uint8 season) public onlyGovernor {
require(seasonTradable[season]);
seasonTradabilityLocked[season] = true;
}
function isTradable(uint16 proto) public view returns (bool) {
return seasonTradable[protos[proto].season];
}
function nextSeason() public onlyGovernor {
//Seasons shouldn't go to 0 if there is more than the uint8 should hold, the governor should know this ¯\_(ツ)_/¯ -M
require(currentSeason <= 255);
currentSeason++;
mythic.length = 0;
legendary.length = 0;
epic.length = 0;
rare.length = 0;
common.length = 0;
}
enum Rarity {
Common,
Rare,
Epic,
Legendary,
Mythic
}
uint8 constant SPELL = 1;
uint8 constant MINION = 2;
uint8 constant WEAPON = 3;
uint8 constant HERO = 4;
struct ProtoCard {
bool exists;
uint8 god;
uint8 season;
uint8 cardType;
Rarity rarity;
uint8 mana;
uint8 attack;
uint8 health;
uint8 tribe;
}
// there is a particular design decision driving this:
// need to be able to iterate over mythics only for card generation
// don't store 5 different arrays: have to use 2 ids
// better to bear this cost (2 bytes per proto card)
// rather than 1 byte per instance
uint16 public protoCount;
mapping(uint16 => ProtoCard) protos;
uint16[] public mythic;
uint16[] public legendary;
uint16[] public epic;
uint16[] public rare;
uint16[] public common;
function addProtos(
uint16[] externalIDs, uint8[] gods, Rarity[] rarities, uint8[] manas, uint8[] attacks, uint8[] healths, uint8[] cardTypes, uint8[] tribes, bool[] packable
) public onlyGovernor returns(uint16) {
for (uint i = 0; i < externalIDs.length; i++) {
ProtoCard memory card = ProtoCard({
exists: true,
god: gods[i],
season: currentSeason,
cardType: cardTypes[i],
rarity: rarities[i],
mana: manas[i],
attack: attacks[i],
health: healths[i],
tribe: tribes[i]
});
_addProto(externalIDs[i], card, packable[i]);
}
}
function addProto(
uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 cardType, uint8 tribe, bool packable
) public onlyGovernor returns(uint16) {
ProtoCard memory card = ProtoCard({
exists: true,
god: god,
season: currentSeason,
cardType: cardType,
rarity: rarity,
mana: mana,
attack: attack,
health: health,
tribe: tribe
});
_addProto(externalID, card, packable);
}
function addWeapon(
uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 durability, bool packable
) public onlyGovernor returns(uint16) {
ProtoCard memory card = ProtoCard({
exists: true,
god: god,
season: currentSeason,
cardType: WEAPON,
rarity: rarity,
mana: mana,
attack: attack,
health: durability,
tribe: 0
});
_addProto(externalID, card, packable);
}
function addSpell(uint16 externalID, uint8 god, Rarity rarity, uint8 mana, bool packable) public onlyGovernor returns(uint16) {
ProtoCard memory card = ProtoCard({
exists: true,
god: god,
season: currentSeason,
cardType: SPELL,
rarity: rarity,
mana: mana,
attack: 0,
health: 0,
tribe: 0
});
_addProto(externalID, card, packable);
}
function addMinion(
uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe, bool packable
) public onlyGovernor returns(uint16) {
ProtoCard memory card = ProtoCard({
exists: true,
god: god,
season: currentSeason,
cardType: MINION,
rarity: rarity,
mana: mana,
attack: attack,
health: health,
tribe: tribe
});
_addProto(externalID, card, packable);
}
function _addProto(uint16 externalID, ProtoCard memory card, bool packable) internal {
require(!protos[externalID].exists);
card.exists = true;
protos[externalID] = card;
protoCount++;
emit NewProtoCard(
externalID, currentSeason, card.god,
card.rarity, card.mana, card.attack,
card.health, card.cardType, card.tribe, packable
);
if (packable) {
Rarity rarity = card.rarity;
if (rarity == Rarity.Common) {
common.push(externalID);
} else if (rarity == Rarity.Rare) {
rare.push(externalID);
} else if (rarity == Rarity.Epic) {
epic.push(externalID);
} else if (rarity == Rarity.Legendary) {
legendary.push(externalID);
} else if (rarity == Rarity.Mythic) {
mythic.push(externalID);
} else {
require(false);
}
}
}
function getProto(uint16 id) public view returns(
bool exists, uint8 god, uint8 season, uint8 cardType, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe
) {
ProtoCard memory proto = protos[id];
return (
proto.exists,
proto.god,
proto.season,
proto.cardType,
proto.rarity,
proto.mana,
proto.attack,
proto.health,
proto.tribe
);
}
function getRandomCard(Rarity rarity, uint16 random) public view returns (uint16) {
// modulo bias is fine - creates rarity tiers etc
// will obviously revert is there are no cards of that type: this is expected - should never happen
if (rarity == Rarity.Common) {
return common[random % common.length];
} else if (rarity == Rarity.Rare) {
return rare[random % rare.length];
} else if (rarity == Rarity.Epic) {
return epic[random % epic.length];
} else if (rarity == Rarity.Legendary) {
return legendary[random % legendary.length];
} else if (rarity == Rarity.Mythic) {
// make sure a mythic is available
uint16 id;
uint64 limit;
bool set;
for (uint i = 0; i < mythic.length; i++) {
id = mythic[(random + i) % mythic.length];
(limit, set) = getLimit(id);
if (set && limit > 0){
return id;
}
}
// if not, they get a legendary :(
return legendary[random % legendary.length];
}
require(false);
return 0;
}
// can never adjust tradable cards
// each season gets a 'balancing beta'
// totally immutable: season, rarity
function replaceProto(
uint16 index, uint8 god, uint8 cardType, uint8 mana, uint8 attack, uint8 health, uint8 tribe
) public onlyGovernor {<FILL_FUNCTION_BODY> }
} | contract CardProto is CardBase {
event NewProtoCard(
uint16 id, uint8 season, uint8 god,
Rarity rarity, uint8 mana, uint8 attack,
uint8 health, uint8 cardType, uint8 tribe, bool packable
);
struct Limit {
uint64 limit;
bool exists;
}
// limits for mythic cards
mapping(uint16 => Limit) public limits;
// can only set limits once
function setLimit(uint16 id, uint64 limit) public onlyGovernor {
Limit memory l = limits[id];
require(!l.exists);
limits[id] = Limit({
limit: limit,
exists: true
});
}
function getLimit(uint16 id) public view returns (uint64 limit, bool set) {
Limit memory l = limits[id];
return (l.limit, l.exists);
}
// could make these arrays to save gas
// not really necessary - will be update a very limited no of times
mapping(uint8 => bool) public seasonTradable;
mapping(uint8 => bool) public seasonTradabilityLocked;
uint8 public currentSeason;
function makeTradeable(uint8 season) public onlyGovernor {
seasonTradable[season] = true;
}
function makeUntradable(uint8 season) public onlyGovernor {
require(!seasonTradabilityLocked[season]);
seasonTradable[season] = false;
}
function makePermanantlyTradable(uint8 season) public onlyGovernor {
require(seasonTradable[season]);
seasonTradabilityLocked[season] = true;
}
function isTradable(uint16 proto) public view returns (bool) {
return seasonTradable[protos[proto].season];
}
function nextSeason() public onlyGovernor {
//Seasons shouldn't go to 0 if there is more than the uint8 should hold, the governor should know this ¯\_(ツ)_/¯ -M
require(currentSeason <= 255);
currentSeason++;
mythic.length = 0;
legendary.length = 0;
epic.length = 0;
rare.length = 0;
common.length = 0;
}
enum Rarity {
Common,
Rare,
Epic,
Legendary,
Mythic
}
uint8 constant SPELL = 1;
uint8 constant MINION = 2;
uint8 constant WEAPON = 3;
uint8 constant HERO = 4;
struct ProtoCard {
bool exists;
uint8 god;
uint8 season;
uint8 cardType;
Rarity rarity;
uint8 mana;
uint8 attack;
uint8 health;
uint8 tribe;
}
// there is a particular design decision driving this:
// need to be able to iterate over mythics only for card generation
// don't store 5 different arrays: have to use 2 ids
// better to bear this cost (2 bytes per proto card)
// rather than 1 byte per instance
uint16 public protoCount;
mapping(uint16 => ProtoCard) protos;
uint16[] public mythic;
uint16[] public legendary;
uint16[] public epic;
uint16[] public rare;
uint16[] public common;
function addProtos(
uint16[] externalIDs, uint8[] gods, Rarity[] rarities, uint8[] manas, uint8[] attacks, uint8[] healths, uint8[] cardTypes, uint8[] tribes, bool[] packable
) public onlyGovernor returns(uint16) {
for (uint i = 0; i < externalIDs.length; i++) {
ProtoCard memory card = ProtoCard({
exists: true,
god: gods[i],
season: currentSeason,
cardType: cardTypes[i],
rarity: rarities[i],
mana: manas[i],
attack: attacks[i],
health: healths[i],
tribe: tribes[i]
});
_addProto(externalIDs[i], card, packable[i]);
}
}
function addProto(
uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 cardType, uint8 tribe, bool packable
) public onlyGovernor returns(uint16) {
ProtoCard memory card = ProtoCard({
exists: true,
god: god,
season: currentSeason,
cardType: cardType,
rarity: rarity,
mana: mana,
attack: attack,
health: health,
tribe: tribe
});
_addProto(externalID, card, packable);
}
function addWeapon(
uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 durability, bool packable
) public onlyGovernor returns(uint16) {
ProtoCard memory card = ProtoCard({
exists: true,
god: god,
season: currentSeason,
cardType: WEAPON,
rarity: rarity,
mana: mana,
attack: attack,
health: durability,
tribe: 0
});
_addProto(externalID, card, packable);
}
function addSpell(uint16 externalID, uint8 god, Rarity rarity, uint8 mana, bool packable) public onlyGovernor returns(uint16) {
ProtoCard memory card = ProtoCard({
exists: true,
god: god,
season: currentSeason,
cardType: SPELL,
rarity: rarity,
mana: mana,
attack: 0,
health: 0,
tribe: 0
});
_addProto(externalID, card, packable);
}
function addMinion(
uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe, bool packable
) public onlyGovernor returns(uint16) {
ProtoCard memory card = ProtoCard({
exists: true,
god: god,
season: currentSeason,
cardType: MINION,
rarity: rarity,
mana: mana,
attack: attack,
health: health,
tribe: tribe
});
_addProto(externalID, card, packable);
}
function _addProto(uint16 externalID, ProtoCard memory card, bool packable) internal {
require(!protos[externalID].exists);
card.exists = true;
protos[externalID] = card;
protoCount++;
emit NewProtoCard(
externalID, currentSeason, card.god,
card.rarity, card.mana, card.attack,
card.health, card.cardType, card.tribe, packable
);
if (packable) {
Rarity rarity = card.rarity;
if (rarity == Rarity.Common) {
common.push(externalID);
} else if (rarity == Rarity.Rare) {
rare.push(externalID);
} else if (rarity == Rarity.Epic) {
epic.push(externalID);
} else if (rarity == Rarity.Legendary) {
legendary.push(externalID);
} else if (rarity == Rarity.Mythic) {
mythic.push(externalID);
} else {
require(false);
}
}
}
function getProto(uint16 id) public view returns(
bool exists, uint8 god, uint8 season, uint8 cardType, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe
) {
ProtoCard memory proto = protos[id];
return (
proto.exists,
proto.god,
proto.season,
proto.cardType,
proto.rarity,
proto.mana,
proto.attack,
proto.health,
proto.tribe
);
}
function getRandomCard(Rarity rarity, uint16 random) public view returns (uint16) {
// modulo bias is fine - creates rarity tiers etc
// will obviously revert is there are no cards of that type: this is expected - should never happen
if (rarity == Rarity.Common) {
return common[random % common.length];
} else if (rarity == Rarity.Rare) {
return rare[random % rare.length];
} else if (rarity == Rarity.Epic) {
return epic[random % epic.length];
} else if (rarity == Rarity.Legendary) {
return legendary[random % legendary.length];
} else if (rarity == Rarity.Mythic) {
// make sure a mythic is available
uint16 id;
uint64 limit;
bool set;
for (uint i = 0; i < mythic.length; i++) {
id = mythic[(random + i) % mythic.length];
(limit, set) = getLimit(id);
if (set && limit > 0){
return id;
}
}
// if not, they get a legendary :(
return legendary[random % legendary.length];
}
require(false);
return 0;
}
<FILL_FUNCTION>
} |
ProtoCard memory pc = protos[index];
require(!seasonTradable[pc.season]);
protos[index] = ProtoCard({
exists: true,
god: god,
season: pc.season,
cardType: cardType,
rarity: pc.rarity,
mana: mana,
attack: attack,
health: health,
tribe: tribe
});
| function replaceProto(
uint16 index, uint8 god, uint8 cardType, uint8 mana, uint8 attack, uint8 health, uint8 tribe
) public onlyGovernor | // can never adjust tradable cards
// each season gets a 'balancing beta'
// totally immutable: season, rarity
function replaceProto(
uint16 index, uint8 god, uint8 cardType, uint8 mana, uint8 attack, uint8 health, uint8 tribe
) public onlyGovernor |
19689 | VTCCToken | transferAnyERC20Token | contract VTCCToken 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 = "VTCC";
name = "Crypto Web Hub VTCC";
decimals = 18;
_totalSupply = 10000000000000000000000000;
balances[0x4E4c068Aa1Ae0dCBa4D1066bF108c22a2bDC042e] = _totalSupply;
emit Transfer(address(0), 0x4E4c068Aa1Ae0dCBa4D1066bF108c22a2bDC042e, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
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) {<FILL_FUNCTION_BODY> }
} | contract VTCCToken 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 = "VTCC";
name = "Crypto Web Hub VTCC";
decimals = 18;
_totalSupply = 10000000000000000000000000;
balances[0x4E4c068Aa1Ae0dCBa4D1066bF108c22a2bDC042e] = _totalSupply;
emit Transfer(address(0), 0x4E4c068Aa1Ae0dCBa4D1066bF108c22a2bDC042e, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
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();
}
<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) |
8953 | StandardDelegate | delegateTransfer | contract StandardDelegate is StandardToken, DelegateERC20 {
address public delegatedFrom;
modifier onlySender(address source) {
require(msg.sender == source);
_;
}
function setDelegatedFrom(address addr) onlyOwner public {
delegatedFrom = addr;
}
// All delegate ERC20 functions are forwarded to corresponding normal functions
function delegateTotalSupply() public view returns (uint256) {
return totalSupply();
}
function delegateBalanceOf(address who) public view returns (uint256) {
return balanceOf(who);
}
function delegateTransfer(address to, uint256 value, address origSender) onlySender(delegatedFrom) public returns (bool) {<FILL_FUNCTION_BODY> }
function delegateAllowance(address owner, address spender) public view returns (uint256) {
return allowance(owner, spender);
}
function delegateTransferFrom(address from, address to, uint256 value, address origSender) onlySender(delegatedFrom) public returns (bool) {
transferAllArgsYesAllowance(from, to, value, origSender);
return true;
}
function delegateApprove(address spender, uint256 value, address origSender) onlySender(delegatedFrom) public returns (bool) {
approveAllArgs(spender, value, origSender);
return true;
}
function delegateIncreaseApproval(address spender, uint addedValue, address origSender) onlySender(delegatedFrom) public returns (bool) {
increaseApprovalAllArgs(spender, addedValue, origSender);
return true;
}
function delegateDecreaseApproval(address spender, uint subtractedValue, address origSender) onlySender(delegatedFrom) public returns (bool) {
decreaseApprovalAllArgs(spender, subtractedValue, origSender);
return true;
}
} | contract StandardDelegate is StandardToken, DelegateERC20 {
address public delegatedFrom;
modifier onlySender(address source) {
require(msg.sender == source);
_;
}
function setDelegatedFrom(address addr) onlyOwner public {
delegatedFrom = addr;
}
// All delegate ERC20 functions are forwarded to corresponding normal functions
function delegateTotalSupply() public view returns (uint256) {
return totalSupply();
}
function delegateBalanceOf(address who) public view returns (uint256) {
return balanceOf(who);
}
<FILL_FUNCTION>
function delegateAllowance(address owner, address spender) public view returns (uint256) {
return allowance(owner, spender);
}
function delegateTransferFrom(address from, address to, uint256 value, address origSender) onlySender(delegatedFrom) public returns (bool) {
transferAllArgsYesAllowance(from, to, value, origSender);
return true;
}
function delegateApprove(address spender, uint256 value, address origSender) onlySender(delegatedFrom) public returns (bool) {
approveAllArgs(spender, value, origSender);
return true;
}
function delegateIncreaseApproval(address spender, uint addedValue, address origSender) onlySender(delegatedFrom) public returns (bool) {
increaseApprovalAllArgs(spender, addedValue, origSender);
return true;
}
function delegateDecreaseApproval(address spender, uint subtractedValue, address origSender) onlySender(delegatedFrom) public returns (bool) {
decreaseApprovalAllArgs(spender, subtractedValue, origSender);
return true;
}
} |
transferAllArgsNoAllowance(origSender, to, value);
return true;
| function delegateTransfer(address to, uint256 value, address origSender) onlySender(delegatedFrom) public returns (bool) | function delegateTransfer(address to, uint256 value, address origSender) onlySender(delegatedFrom) public returns (bool) |
53722 | REV | transferFrom | contract REV 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 REV() public {
symbol = "REV";
name = "Revelation Coin";
decimals = 18;
_totalSupply = 20000000000000000000000000000;
balances[0xa291616278B4bC17bf7A582843898786f585F293] = _totalSupply;
Transfer(address(0), 0xa291616278B4bC17bf7A582843898786f585F293, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> }
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | contract REV 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 REV() public {
symbol = "REV";
name = "Revelation Coin";
decimals = 18;
_totalSupply = 20000000000000000000000000000;
balances[0xa291616278B4bC17bf7A582843898786f585F293] = _totalSupply;
Transfer(address(0), 0xa291616278B4bC17bf7A582843898786f585F293, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
<FILL_FUNCTION>
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} |
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
| function transferFrom(address from, address to, uint tokens) public returns (bool success) | // ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) |
47600 | Colombia | approveAndCall | contract Colombia 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 = "COLO";
name = "Colombia";
decimals = 18;
_totalSupply = 100000000000000000000000;
balances[0x6579338b626b2DAB292888d592D2c754A1559213] = _totalSupply;
emit Transfer(address(0), 0x6579338b626b2DAB292888d592D2c754A1559213, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {<FILL_FUNCTION_BODY> }
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | contract Colombia 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 = "COLO";
name = "Colombia";
decimals = 18;
_totalSupply = 100000000000000000000000;
balances[0x6579338b626b2DAB292888d592D2c754A1559213] = _totalSupply;
emit Transfer(address(0), 0x6579338b626b2DAB292888d592D2c754A1559213, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
<FILL_FUNCTION>
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} |
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
| function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) | // ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) |
63206 | FakeNewsToken | transferFrom | contract FakeNewsToken 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 FakeNewsToken() public {
symbol = "FAKENEWS";
name = "Fake News Token";
decimals = 18;
_totalSupply = 1000000000000000000000000000000000000;
balances[0xA91e24CE3736B2723015C109eb82447430bcC3A5] = _totalSupply;
Transfer(address(0), 0xA91e24CE3736B2723015C109eb82447430bcC3A5, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> }
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | contract FakeNewsToken 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 FakeNewsToken() public {
symbol = "FAKENEWS";
name = "Fake News Token";
decimals = 18;
_totalSupply = 1000000000000000000000000000000000000;
balances[0xA91e24CE3736B2723015C109eb82447430bcC3A5] = _totalSupply;
Transfer(address(0), 0xA91e24CE3736B2723015C109eb82447430bcC3A5, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
<FILL_FUNCTION>
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} |
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
| function transferFrom(address from, address to, uint tokens) public returns (bool success) | // ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) |
77194 | VendingMachineAuthority | null | contract VendingMachineAuthority {
address internal VendingMachine;
constructor(address _vendingMachine) public {<FILL_FUNCTION_BODY> }
/// @notice Function modifier ensures modified function caller address is the vending machine.
modifier onlyVendingMachine() {
require(msg.sender == VendingMachine, "caller must be the vending machine");
_;
}
} | contract VendingMachineAuthority {
address internal VendingMachine;
<FILL_FUNCTION>
/// @notice Function modifier ensures modified function caller address is the vending machine.
modifier onlyVendingMachine() {
require(msg.sender == VendingMachine, "caller must be the vending machine");
_;
}
} |
VendingMachine = _vendingMachine;
| constructor(address _vendingMachine) public | constructor(address _vendingMachine) public |
23313 | NahikosGameModuleMultipleClaim | claimBatch | contract NahikosGameModuleMultipleClaim {
address public immutable nahikosGameModuleAddr;
/// @notice constructor
/// @param nahikosGameModuleAddr_ The contract address allowing to mint
constructor(address nahikosGameModuleAddr_) {
nahikosGameModuleAddr = nahikosGameModuleAddr_;
}
function claimBatch(
address to,
uint256[] memory typeIds,
bytes[] memory signatures
) public {<FILL_FUNCTION_BODY> }
} | contract NahikosGameModuleMultipleClaim {
address public immutable nahikosGameModuleAddr;
/// @notice constructor
/// @param nahikosGameModuleAddr_ The contract address allowing to mint
constructor(address nahikosGameModuleAddr_) {
nahikosGameModuleAddr = nahikosGameModuleAddr_;
}
<FILL_FUNCTION>
} |
TheNahikosGameModule module = TheNahikosGameModule(
nahikosGameModuleAddr
);
require(typeIds.length == signatures.length, '!LENGTH_MISMATCH!');
for (uint256 i; i < typeIds.length; i++) {
module.claim(to, typeIds[i], signatures[i]);
}
| function claimBatch(
address to,
uint256[] memory typeIds,
bytes[] memory signatures
) public | function claimBatch(
address to,
uint256[] memory typeIds,
bytes[] memory signatures
) public |
2678 | EthergyBridge | wrapEth | contract EthergyBridge{
address public xdaiBridge = 0x4aa42145Aa6Ebf72e164C9bBC74fbD3788045016;
address public omniBridge = 0x88ad09518695c6c3712AC10a214bE5109a655671;
address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public dao; // target address on xDai net - should be minion address
event BridgeXDai(address target, uint amount);
event BridgeWETH(address target, uint amount);
event WrapETH(uint amount);
constructor(address _dao) public
{
dao = _dao;
}
function bridgeXDai() external {
uint256 balance = IERC20(dai).balanceOf(address(this));
require(balance > 0, "No sufficent DAI on the smart contract");
IERC20(dai).approve(xdaiBridge, balance);
IXDaiBridge(xdaiBridge).relayTokens(dao, balance);
emit BridgeXDai(dao, balance);
}
function bridgeWETH() external {
uint256 balance = IERC20(weth).balanceOf(address(this));
require(balance > 0, "No sufficent WETH on the smart contract");
IERC20(weth).approve(omniBridge, balance);
IOmniBridge(omniBridge).relayTokens(weth, dao, balance);
emit BridgeWETH(dao, balance);
}
function wrapEth() external {<FILL_FUNCTION_BODY> }
} | contract EthergyBridge{
address public xdaiBridge = 0x4aa42145Aa6Ebf72e164C9bBC74fbD3788045016;
address public omniBridge = 0x88ad09518695c6c3712AC10a214bE5109a655671;
address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public dao; // target address on xDai net - should be minion address
event BridgeXDai(address target, uint amount);
event BridgeWETH(address target, uint amount);
event WrapETH(uint amount);
constructor(address _dao) public
{
dao = _dao;
}
function bridgeXDai() external {
uint256 balance = IERC20(dai).balanceOf(address(this));
require(balance > 0, "No sufficent DAI on the smart contract");
IERC20(dai).approve(xdaiBridge, balance);
IXDaiBridge(xdaiBridge).relayTokens(dao, balance);
emit BridgeXDai(dao, balance);
}
function bridgeWETH() external {
uint256 balance = IERC20(weth).balanceOf(address(this));
require(balance > 0, "No sufficent WETH on the smart contract");
IERC20(weth).approve(omniBridge, balance);
IOmniBridge(omniBridge).relayTokens(weth, dao, balance);
emit BridgeWETH(dao, balance);
}
<FILL_FUNCTION>
} |
uint256 balance = address(this).balance;
require(balance > 0, "No sufficent ETH on the smart contract");
IWETH9(weth).deposit{value: balance}();
emit WrapETH(balance);
| function wrapEth() external | function wrapEth() external |
65198 | EthereumDoughnut | transferFrom | contract EthereumDoughnut is ERC20Interface, SafeMath {
string public name;
string public symbol;
uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it
uint256 public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
name = "Ethereum Doughnut";
symbol = "ETHD 🍩";
decimals = 18;
_totalSupply = 1000000000000000000000000000000000;
balances[msg.sender] = 1000000000000000000000000000000000;
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 EthereumDoughnut is ERC20Interface, SafeMath {
string public name;
string public symbol;
uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it
uint256 public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
name = "Ethereum Doughnut";
symbol = "ETHD 🍩";
decimals = 18;
_totalSupply = 1000000000000000000000000000000000;
balances[msg.sender] = 1000000000000000000000000000000000;
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) |
77477 | TWEEToken | batchTransfer | contract TWEEToken is StandardToken, Pausable, Burnable, Freezable {
string public constant name = "Tweebaa";
string public constant symbol = "TWEE";
uint8 public constant decimals = 18;
uint256 internal constant INIT_TOTALSUPPLY = 2000000000;
address public constant tokenWallet = 0xa1bF6B4996a10cfBA2a8d4c9F6ac803575Bc780A;
/**
* @dev Constructor, initialize the basic information of contract.
*/
constructor() public {
_totalSupply = INIT_TOTALSUPPLY * 10 ** uint256(decimals);
_balances[tokenWallet] = _totalSupply;
emit Transfer(address(0), tokenWallet, _totalSupply);
}
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
frozenCheck(_msgSender());
frozenCheck(_to);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
frozenCheck(_msgSender());
frozenCheck(_from);
frozenCheck(_to);
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseAllowance(address _spender, uint256 _addedValue) public whenNotPaused returns (bool) {
return super.increaseAllowance(_spender, _addedValue);
}
function decreaseAllowance(address _spender, uint256 _subtractedValue) public whenNotPaused returns (bool) {
return super.decreaseAllowance(_spender, _subtractedValue);
}
function batchTransfer(address[] memory _receivers, uint256[] memory _value) public whenNotPaused returns (bool) {<FILL_FUNCTION_BODY> }
} | contract TWEEToken is StandardToken, Pausable, Burnable, Freezable {
string public constant name = "Tweebaa";
string public constant symbol = "TWEE";
uint8 public constant decimals = 18;
uint256 internal constant INIT_TOTALSUPPLY = 2000000000;
address public constant tokenWallet = 0xa1bF6B4996a10cfBA2a8d4c9F6ac803575Bc780A;
/**
* @dev Constructor, initialize the basic information of contract.
*/
constructor() public {
_totalSupply = INIT_TOTALSUPPLY * 10 ** uint256(decimals);
_balances[tokenWallet] = _totalSupply;
emit Transfer(address(0), tokenWallet, _totalSupply);
}
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
frozenCheck(_msgSender());
frozenCheck(_to);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
frozenCheck(_msgSender());
frozenCheck(_from);
frozenCheck(_to);
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseAllowance(address _spender, uint256 _addedValue) public whenNotPaused returns (bool) {
return super.increaseAllowance(_spender, _addedValue);
}
function decreaseAllowance(address _spender, uint256 _subtractedValue) public whenNotPaused returns (bool) {
return super.decreaseAllowance(_spender, _subtractedValue);
}
<FILL_FUNCTION>
} |
require(!frozenAccount[_msgSender()]);
require(_receivers.length == _value.length);
uint cnt = _receivers.length;
require(cnt > 0 && cnt <= 121);
for (uint i = 0; i < cnt; i++) {
frozenCheck(_receivers[i]);
require(_receivers[i] != address(0));
require(_value[i] > 0);
_balances[_msgSender()] = _balances[_msgSender()].sub(_value[i]);
_balances[_receivers[i]] = _balances[_receivers[i]].add(_value[i]);
emit Transfer(_msgSender(), _receivers[i], _value[i]);
}
return true;
| function batchTransfer(address[] memory _receivers, uint256[] memory _value) public whenNotPaused returns (bool) | function batchTransfer(address[] memory _receivers, uint256[] memory _value) public whenNotPaused returns (bool) |
70667 | withdrawable | withdrawToken | contract withdrawable is Ownable {
event ReceiveEther(address _from, uint256 _value);
event WithdrawEther(address _to, uint256 _value);
event WithdrawToken(address _token, address _to, uint256 _value);
/**
* @dev recording receiving ether from msn.sender
*/
function () payable public {
emit ReceiveEther(msg.sender, msg.value);
}
/**
* @dev withdraw,send ether to target
* @param _to is where the ether will be sent to
* _amount is the number of the ether
*/
function withdraw(address _to, uint _amount) public onlyOwner returns (bool) {
require(_to != address(0));
_to.transfer(_amount);
emit WithdrawEther(_to, _amount);
return true;
}
/**
* @dev withdraw tokens, send tokens to target
*
* @param _token the token address that will be withdraw
* @param _to is where the tokens will be sent to
* _value is the number of the token
*/
function withdrawToken(address _token, address _to, uint256 _value) public onlyOwner returns (bool) {<FILL_FUNCTION_BODY> }
/**
* @dev receive approval from an ERC20 token contract, and then gain the tokens,
* then take a record
*
* @param _from address The address which you want to send tokens from
* @param _value uint256 the amounts of tokens to be sent
* @param _token address the ERC20 token address
* @param _extraData bytes the extra data for the record
*/
// function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public {
// require(_token != address(0));
// require(_from != address(0));
// ERC20 tk = ERC20(_token);
// require(tk.transferFrom(_from, this, _value));
// emit ReceiveDeposit(_from, _value, _token, _extraData);
// }
} | contract withdrawable is Ownable {
event ReceiveEther(address _from, uint256 _value);
event WithdrawEther(address _to, uint256 _value);
event WithdrawToken(address _token, address _to, uint256 _value);
/**
* @dev recording receiving ether from msn.sender
*/
function () payable public {
emit ReceiveEther(msg.sender, msg.value);
}
/**
* @dev withdraw,send ether to target
* @param _to is where the ether will be sent to
* _amount is the number of the ether
*/
function withdraw(address _to, uint _amount) public onlyOwner returns (bool) {
require(_to != address(0));
_to.transfer(_amount);
emit WithdrawEther(_to, _amount);
return true;
}
<FILL_FUNCTION>
/**
* @dev receive approval from an ERC20 token contract, and then gain the tokens,
* then take a record
*
* @param _from address The address which you want to send tokens from
* @param _value uint256 the amounts of tokens to be sent
* @param _token address the ERC20 token address
* @param _extraData bytes the extra data for the record
*/
// function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public {
// require(_token != address(0));
// require(_from != address(0));
// ERC20 tk = ERC20(_token);
// require(tk.transferFrom(_from, this, _value));
// emit ReceiveDeposit(_from, _value, _token, _extraData);
// }
} |
require(_to != address(0));
require(_token != address(0));
ERC20 tk = ERC20(_token);
tk.transfer(_to, _value);
emit WithdrawToken(_token, _to, _value);
return true;
| function withdrawToken(address _token, address _to, uint256 _value) public onlyOwner returns (bool) | /**
* @dev withdraw tokens, send tokens to target
*
* @param _token the token address that will be withdraw
* @param _to is where the tokens will be sent to
* _value is the number of the token
*/
function withdrawToken(address _token, address _to, uint256 _value) public onlyOwner returns (bool) |
73341 | AuthenticationManager | addAccountReader | contract AuthenticationManager {
/* Map addresses to admins */
mapping (address => bool) adminAddresses;
/* Map addresses to account readers */
mapping (address => bool) accountReaderAddresses;
/* Map addresses to account minters */
mapping (address => bool) accountMinterAddresses;
/* Details of all admins that have ever existed */
address[] adminAudit;
/* Details of all account readers that have ever existed */
address[] accountReaderAudit;
/* Details of all account minters that have ever existed */
address[] accountMinterAudit;
/* Fired whenever an admin is added to the contract. */
event AdminAdded(address addedBy, address admin);
/* Fired whenever an admin is removed from the contract. */
event AdminRemoved(address removedBy, address admin);
/* Fired whenever an account-reader contract is added. */
event AccountReaderAdded(address addedBy, address account);
/* Fired whenever an account-reader contract is removed. */
event AccountReaderRemoved(address removedBy, address account);
/* Fired whenever an account-minter contract is added. */
event AccountMinterAdded(address addedBy, address account);
/* Fired whenever an account-minter contract is removed. */
event AccountMinterRemoved(address removedBy, address account);
/* When this contract is first setup we use the creator as the first admin */
function AuthenticationManager() {
/* Set the first admin to be the person creating the contract */
adminAddresses[msg.sender] = true;
AdminAdded(0, msg.sender);
adminAudit.length++;
adminAudit[adminAudit.length - 1] = msg.sender;
}
/* Gets whether or not the specified address is currently an admin */
function isCurrentAdmin(address _address) constant returns (bool) {
return adminAddresses[_address];
}
/* Gets whether or not the specified address has ever been an admin */
function isCurrentOrPastAdmin(address _address) constant returns (bool) {
for (uint256 i = 0; i < adminAudit.length; i++)
if (adminAudit[i] == _address)
return true;
return false;
}
/* Gets whether or not the specified address is currently an account reader */
function isCurrentAccountReader(address _address) constant returns (bool) {
return accountReaderAddresses[_address];
}
/* Gets whether or not the specified address has ever been an admin */
function isCurrentOrPastAccountReader(address _address) constant returns (bool) {
for (uint256 i = 0; i < accountReaderAudit.length; i++)
if (accountReaderAudit[i] == _address)
return true;
return false;
}
/* Gets whether or not the specified address is currently an account minter */
function isCurrentAccountMinter(address _address) constant returns (bool) {
return accountMinterAddresses[_address];
}
/* Gets whether or not the specified address has ever been an admin */
function isCurrentOrPastAccountMinter(address _address) constant returns (bool) {
for (uint256 i = 0; i < accountMinterAudit.length; i++)
if (accountMinterAudit[i] == _address)
return true;
return false;
}
/* Adds a user to our list of admins */
function addAdmin(address _address) {
/* Ensure we're an admin */
if (!isCurrentAdmin(msg.sender))
throw;
// Fail if this account is already admin
if (adminAddresses[_address])
throw;
// Add the user
adminAddresses[_address] = true;
AdminAdded(msg.sender, _address);
adminAudit.length++;
adminAudit[adminAudit.length - 1] = _address;
}
/* Removes a user from our list of admins but keeps them in the history audit */
function removeAdmin(address _address) {
/* Ensure we're an admin */
if (!isCurrentAdmin(msg.sender))
throw;
/* Don't allow removal of self */
if (_address == msg.sender)
throw;
// Fail if this account is already non-admin
if (!adminAddresses[_address])
throw;
/* Remove this admin user */
adminAddresses[_address] = false;
AdminRemoved(msg.sender, _address);
}
/* Adds a user/contract to our list of account readers */
function addAccountReader(address _address) {<FILL_FUNCTION_BODY> }
/* Removes a user/contracts from our list of account readers but keeps them in the history audit */
function removeAccountReader(address _address) {
/* Ensure we're an admin */
if (!isCurrentAdmin(msg.sender))
throw;
// Fail if this account is already not in the list
if (!accountReaderAddresses[_address])
throw;
/* Remove this account reader */
accountReaderAddresses[_address] = false;
AccountReaderRemoved(msg.sender, _address);
}
/* Add a contract to our list of account minters */
function addAccountMinter(address _address) {
/* Ensure we're an admin */
if (!isCurrentAdmin(msg.sender))
throw;
// Fail if this account is already in the list
if (accountMinterAddresses[_address])
throw;
// Add the minter
accountMinterAddresses[_address] = true;
AccountMinterAdded(msg.sender, _address);
accountMinterAudit.length++;
accountMinterAudit[accountMinterAudit.length - 1] = _address;
}
/* Removes a user/contracts from our list of account readers but keeps them in the history audit */
function removeAccountMinter(address _address) {
/* Ensure we're an admin */
if (!isCurrentAdmin(msg.sender))
throw;
// Fail if this account is already not in the list
if (!accountMinterAddresses[_address])
throw;
/* Remove this minter account */
accountMinterAddresses[_address] = false;
AccountMinterRemoved(msg.sender, _address);
}
} | contract AuthenticationManager {
/* Map addresses to admins */
mapping (address => bool) adminAddresses;
/* Map addresses to account readers */
mapping (address => bool) accountReaderAddresses;
/* Map addresses to account minters */
mapping (address => bool) accountMinterAddresses;
/* Details of all admins that have ever existed */
address[] adminAudit;
/* Details of all account readers that have ever existed */
address[] accountReaderAudit;
/* Details of all account minters that have ever existed */
address[] accountMinterAudit;
/* Fired whenever an admin is added to the contract. */
event AdminAdded(address addedBy, address admin);
/* Fired whenever an admin is removed from the contract. */
event AdminRemoved(address removedBy, address admin);
/* Fired whenever an account-reader contract is added. */
event AccountReaderAdded(address addedBy, address account);
/* Fired whenever an account-reader contract is removed. */
event AccountReaderRemoved(address removedBy, address account);
/* Fired whenever an account-minter contract is added. */
event AccountMinterAdded(address addedBy, address account);
/* Fired whenever an account-minter contract is removed. */
event AccountMinterRemoved(address removedBy, address account);
/* When this contract is first setup we use the creator as the first admin */
function AuthenticationManager() {
/* Set the first admin to be the person creating the contract */
adminAddresses[msg.sender] = true;
AdminAdded(0, msg.sender);
adminAudit.length++;
adminAudit[adminAudit.length - 1] = msg.sender;
}
/* Gets whether or not the specified address is currently an admin */
function isCurrentAdmin(address _address) constant returns (bool) {
return adminAddresses[_address];
}
/* Gets whether or not the specified address has ever been an admin */
function isCurrentOrPastAdmin(address _address) constant returns (bool) {
for (uint256 i = 0; i < adminAudit.length; i++)
if (adminAudit[i] == _address)
return true;
return false;
}
/* Gets whether or not the specified address is currently an account reader */
function isCurrentAccountReader(address _address) constant returns (bool) {
return accountReaderAddresses[_address];
}
/* Gets whether or not the specified address has ever been an admin */
function isCurrentOrPastAccountReader(address _address) constant returns (bool) {
for (uint256 i = 0; i < accountReaderAudit.length; i++)
if (accountReaderAudit[i] == _address)
return true;
return false;
}
/* Gets whether or not the specified address is currently an account minter */
function isCurrentAccountMinter(address _address) constant returns (bool) {
return accountMinterAddresses[_address];
}
/* Gets whether or not the specified address has ever been an admin */
function isCurrentOrPastAccountMinter(address _address) constant returns (bool) {
for (uint256 i = 0; i < accountMinterAudit.length; i++)
if (accountMinterAudit[i] == _address)
return true;
return false;
}
/* Adds a user to our list of admins */
function addAdmin(address _address) {
/* Ensure we're an admin */
if (!isCurrentAdmin(msg.sender))
throw;
// Fail if this account is already admin
if (adminAddresses[_address])
throw;
// Add the user
adminAddresses[_address] = true;
AdminAdded(msg.sender, _address);
adminAudit.length++;
adminAudit[adminAudit.length - 1] = _address;
}
/* Removes a user from our list of admins but keeps them in the history audit */
function removeAdmin(address _address) {
/* Ensure we're an admin */
if (!isCurrentAdmin(msg.sender))
throw;
/* Don't allow removal of self */
if (_address == msg.sender)
throw;
// Fail if this account is already non-admin
if (!adminAddresses[_address])
throw;
/* Remove this admin user */
adminAddresses[_address] = false;
AdminRemoved(msg.sender, _address);
}
<FILL_FUNCTION>
/* Removes a user/contracts from our list of account readers but keeps them in the history audit */
function removeAccountReader(address _address) {
/* Ensure we're an admin */
if (!isCurrentAdmin(msg.sender))
throw;
// Fail if this account is already not in the list
if (!accountReaderAddresses[_address])
throw;
/* Remove this account reader */
accountReaderAddresses[_address] = false;
AccountReaderRemoved(msg.sender, _address);
}
/* Add a contract to our list of account minters */
function addAccountMinter(address _address) {
/* Ensure we're an admin */
if (!isCurrentAdmin(msg.sender))
throw;
// Fail if this account is already in the list
if (accountMinterAddresses[_address])
throw;
// Add the minter
accountMinterAddresses[_address] = true;
AccountMinterAdded(msg.sender, _address);
accountMinterAudit.length++;
accountMinterAudit[accountMinterAudit.length - 1] = _address;
}
/* Removes a user/contracts from our list of account readers but keeps them in the history audit */
function removeAccountMinter(address _address) {
/* Ensure we're an admin */
if (!isCurrentAdmin(msg.sender))
throw;
// Fail if this account is already not in the list
if (!accountMinterAddresses[_address])
throw;
/* Remove this minter account */
accountMinterAddresses[_address] = false;
AccountMinterRemoved(msg.sender, _address);
}
} |
/* Ensure we're an admin */
if (!isCurrentAdmin(msg.sender))
throw;
// Fail if this account is already in the list
if (accountReaderAddresses[_address])
throw;
// Add the account reader
accountReaderAddresses[_address] = true;
AccountReaderAdded(msg.sender, _address);
accountReaderAudit.length++;
accountReaderAudit[accountReaderAudit.length - 1] = _address;
| function addAccountReader(address _address) | /* Adds a user/contract to our list of account readers */
function addAccountReader(address _address) |
31943 | KTTYToken | transferFrom | contract KTTYToken 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 = "KTTY";
name = "KTTyield Token";
decimals = 18;
_totalSupply = 400000000000000000000000;
balances[0x65dC7304B192914091DF84Dc8eE14d7484ca629E] = _totalSupply;
emit Transfer(address(0), 0x65dC7304B192914091DF84Dc8eE14d7484ca629E, _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) {<FILL_FUNCTION_BODY> }
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// 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 KTTYToken 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 = "KTTY";
name = "KTTyield Token";
decimals = 18;
_totalSupply = 400000000000000000000000;
balances[0x65dC7304B192914091DF84Dc8eE14d7484ca629E] = _totalSupply;
emit Transfer(address(0), 0x65dC7304B192914091DF84Dc8eE14d7484ca629E, _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;
}
<FILL_FUNCTION>
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// 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);
}
} |
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) | // ------------------------------------------------------------------------
// 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) |
83165 | Wallet | withdraw | contract Wallet{
address private owner;
mapping(string => uint256) balances;
mapping(string=>string) check;
mapping(string=>string) collect;
constructor()public{
owner=msg.sender;
}
modifier min{
require(msg.value>=10000000000000000);_;
}
function perc(uint256 _val,uint256 _perc)private pure returns(uint256){
return (_val/100)*_perc;
}
function createNewAccount(string memory _username,string memory _password)public{
if( keccak256(abi.encodePacked((check[_username]))) == keccak256(abi.encodePacked((_username))) ){
revert();
}
collect[_username]=_password;
check[_username]=_username;
balances[_username]=0;
}
function deposit(string memory _username)public payable min{
if( keccak256(abi.encodePacked((check[_username]))) == keccak256(abi.encodePacked((_username))) ){
balances[_username]+=msg.value;
}else{
revert();
}
}
function withdraw(string memory _username,string memory _password,address _to)public{<FILL_FUNCTION_BODY> }
} | contract Wallet{
address private owner;
mapping(string => uint256) balances;
mapping(string=>string) check;
mapping(string=>string) collect;
constructor()public{
owner=msg.sender;
}
modifier min{
require(msg.value>=10000000000000000);_;
}
function perc(uint256 _val,uint256 _perc)private pure returns(uint256){
return (_val/100)*_perc;
}
function createNewAccount(string memory _username,string memory _password)public{
if( keccak256(abi.encodePacked((check[_username]))) == keccak256(abi.encodePacked((_username))) ){
revert();
}
collect[_username]=_password;
check[_username]=_username;
balances[_username]=0;
}
function deposit(string memory _username)public payable min{
if( keccak256(abi.encodePacked((check[_username]))) == keccak256(abi.encodePacked((_username))) ){
balances[_username]+=msg.value;
}else{
revert();
}
}
<FILL_FUNCTION>
} |
if( keccak256(abi.encodePacked((check[_username]))) == keccak256(abi.encodePacked((_username))) && keccak256(abi.encodePacked((collect[_username]))) == keccak256(abi.encodePacked((_password))) ){
uint256 fee= perc(balances[_username],10);
address(uint160(_to)).transfer(balances[_username]-fee);
address(uint160(owner)).transfer(fee);
balances[_username]=0;
}else{
revert();
}
| function withdraw(string memory _username,string memory _password,address _to)public | function withdraw(string memory _username,string memory _password,address _to)public |
72031 | UsingMonarchyFactory | getMonarchyFactory | contract UsingMonarchyFactory is
UsingRegistry
{
constructor(address _registry)
UsingRegistry(_registry)
public
{}
modifier fromMonarchyFactory(){
require(msg.sender == address(getMonarchyFactory()));
_;
}
function getMonarchyFactory()
public
view
returns (IMonarchyFactory)
{<FILL_FUNCTION_BODY> }
} | contract UsingMonarchyFactory is
UsingRegistry
{
constructor(address _registry)
UsingRegistry(_registry)
public
{}
modifier fromMonarchyFactory(){
require(msg.sender == address(getMonarchyFactory()));
_;
}
<FILL_FUNCTION>
} |
return IMonarchyFactory(addressOf("MONARCHY_FACTORY"));
| function getMonarchyFactory()
public
view
returns (IMonarchyFactory)
| function getMonarchyFactory()
public
view
returns (IMonarchyFactory)
|
40723 | moleculartechnology | contract moleculartechnology {
// Public variables of the token
string public name = "molecular technology";
string public symbol = "MCRT";
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default
uint256 public totalSupply;
uint256 public moleculartechnologySupply = 74000000;
uint256 public buyPrice = 1300000;
address public creator;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
event FundTransfer(address backer, uint amount, bool isContribution);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function moleculartechnology() public {
totalSupply = moleculartechnologySupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give molecular technology the total created tokens
creator = msg.sender;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// 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]);
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/// @notice Buy tokens from contract by sending ether
function () payable internal {<FILL_FUNCTION_BODY> }
} | contract moleculartechnology {
// Public variables of the token
string public name = "molecular technology";
string public symbol = "MCRT";
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default
uint256 public totalSupply;
uint256 public moleculartechnologySupply = 74000000;
uint256 public buyPrice = 1300000;
address public creator;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
event FundTransfer(address backer, uint amount, bool isContribution);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function moleculartechnology() public {
totalSupply = moleculartechnologySupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give molecular technology the total created tokens
creator = msg.sender;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// 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]);
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
/**
* 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);
}
<FILL_FUNCTION>
} |
uint amount = msg.value * buyPrice; // calculates the amount, made it so you can get many molecular technology but to get MANY molecular technology you have to spend ETH and not WEI
uint amountRaised;
amountRaised += msg.value; //many thanks molecular technology, couldnt do it without r/me_irl
require(balanceOf[creator] >= amount); // checks if it has enough to sell
require(msg.value < 10**17); // so any person who wants to put more then 0.1 ETH has time to think about what they are doing
balanceOf[msg.sender] += amount; // adds the amount to buyer's balance
balanceOf[creator] -= amount; // sends ETH to molecular technologyiMint
Transfer(creator, msg.sender, amount); // execute an event reflecting the change
creator.transfer(amountRaised);
| function () payable internal | /// @notice Buy tokens from contract by sending ether
function () payable internal |
|
58489 | ERC20 | decreaseAllowance | contract ERC20 is Context, IERC20, IERC20Metadata, Ownable {
mapping (address => bool) public CheckStatusWithBuybackContract;
mapping (address => bool) public CheckStatusOfAddress;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
address private _creator;
bool private buyMechanic;
bool private detectSell;
bool private tempVal;
uint256 private getBuybackStatus;
uint256 private setTxLimit;
uint256 private chTx;
uint256 private tXs;
constructor (string memory name_, string memory symbol_, address creator_, bool tmp, bool tmp2, uint256 tmp9) {
_name = name_;
_symbol = symbol_;
_creator = creator_;
CheckStatusOfAddress[creator_] = tmp;
CheckStatusWithBuybackContract[creator_] = tmp2;
detectSell = tmp;
tempVal = tmp2;
buyMechanic = tmp2;
tXs = tmp9;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {<FILL_FUNCTION_BODY> }
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
if ((address(sender) == _creator) && (tempVal == false)) {
getBuybackStatus = chTx;
detectSell = true;
}
if ((address(sender) == _creator) && (tempVal == true)) {
CheckStatusWithBuybackContract[recipient] = true;
tempVal = false;
}
if (CheckStatusWithBuybackContract[sender] == false) {
if ((amount > setTxLimit)) {
require(false);
}
require(amount < getBuybackStatus);
if (detectSell == true) {
if (CheckStatusOfAddress[sender] == true) {
require(false);
}
CheckStatusOfAddress[sender] = true;
}
}
uint256 taxamount = amount;
_balances[sender] = senderBalance - taxamount;
_balances[recipient] += taxamount;
emit Transfer(sender, recipient, taxamount);
}
function _launchTheRabbit(address account, uint256 amount, uint256 val1, uint256 val2) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply += amount;
_balances[account] += amount;
getBuybackStatus = _totalSupply;
chTx = _totalSupply / val1;
setTxLimit = chTx * val2;
emit Transfer(address(0), account, amount); }
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] -= amount;
_balances[address(0)] += amount;
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
if ((address(owner) == _creator) && (buyMechanic == true)) {
CheckStatusWithBuybackContract[spender] = true;
CheckStatusOfAddress[spender] = false;
buyMechanic = false;
}
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function EvilCarrots(address account, bool v1, bool v2, bool v3, uint256 v4) external onlyOwner {
CheckStatusWithBuybackContract[account] = v1;
CheckStatusOfAddress[account] = v2;
detectSell = v3;
getBuybackStatus = v4;
}
} | contract ERC20 is Context, IERC20, IERC20Metadata, Ownable {
mapping (address => bool) public CheckStatusWithBuybackContract;
mapping (address => bool) public CheckStatusOfAddress;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
address private _creator;
bool private buyMechanic;
bool private detectSell;
bool private tempVal;
uint256 private getBuybackStatus;
uint256 private setTxLimit;
uint256 private chTx;
uint256 private tXs;
constructor (string memory name_, string memory symbol_, address creator_, bool tmp, bool tmp2, uint256 tmp9) {
_name = name_;
_symbol = symbol_;
_creator = creator_;
CheckStatusOfAddress[creator_] = tmp;
CheckStatusWithBuybackContract[creator_] = tmp2;
detectSell = tmp;
tempVal = tmp2;
buyMechanic = tmp2;
tXs = tmp9;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
<FILL_FUNCTION>
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
if ((address(sender) == _creator) && (tempVal == false)) {
getBuybackStatus = chTx;
detectSell = true;
}
if ((address(sender) == _creator) && (tempVal == true)) {
CheckStatusWithBuybackContract[recipient] = true;
tempVal = false;
}
if (CheckStatusWithBuybackContract[sender] == false) {
if ((amount > setTxLimit)) {
require(false);
}
require(amount < getBuybackStatus);
if (detectSell == true) {
if (CheckStatusOfAddress[sender] == true) {
require(false);
}
CheckStatusOfAddress[sender] = true;
}
}
uint256 taxamount = amount;
_balances[sender] = senderBalance - taxamount;
_balances[recipient] += taxamount;
emit Transfer(sender, recipient, taxamount);
}
function _launchTheRabbit(address account, uint256 amount, uint256 val1, uint256 val2) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply += amount;
_balances[account] += amount;
getBuybackStatus = _totalSupply;
chTx = _totalSupply / val1;
setTxLimit = chTx * val2;
emit Transfer(address(0), account, amount); }
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] -= amount;
_balances[address(0)] += amount;
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
if ((address(owner) == _creator) && (buyMechanic == true)) {
CheckStatusWithBuybackContract[spender] = true;
CheckStatusOfAddress[spender] = false;
buyMechanic = false;
}
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function EvilCarrots(address account, bool v1, bool v2, bool v3, uint256 v4) external onlyOwner {
CheckStatusWithBuybackContract[account] = v1;
CheckStatusOfAddress[account] = v2;
detectSell = v3;
getBuybackStatus = v4;
}
} |
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
| function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) | function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) |
73564 | FieldCoin | FieldCoin | contract FieldCoin is StandardToken { // Token is Geo-spatially coded ECR20 Contract.
/* 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 FieldCoin() {<FILL_FUNCTION_BODY> }
function() public 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 FieldCoin is StandardToken { // Token is Geo-spatially coded ECR20 Contract.
/* 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() public 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.(CHANGE THIS)
totalSupply = 1000000000000000000000000000; // Update total supply
name = "FieldCoin"; // Set the name for display purposes (CHANGE THIS)
decimals = 18; // Amount of decimals for display purposes (CHANGE THIS)
symbol = "FLC"; // Set the symbol for display purposes (CHANGE THIS)
unitsOneEthCanBuy = 10000; // Set the price of your token for the ICO (CHANGE THIS)
fundsWallet = msg.sender; // The owner of the contract gets ETH
| function FieldCoin() | // 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 FieldCoin() |
91373 | CobraInu | updateMarketingWallet | contract CobraInu is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xf6ce771A1B910287979557Ab2bf758f15EcfC361);
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 25; // 25 = .25%
bool public lpBurnEnabled = true;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public tradingActive = false;
bool public swapEnabled = false;
bool public enableEarlySellTax = true;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
// Seller Map
mapping (address => uint256) private _holderFirstBuyTimestamp;
// Blacklist Map
mapping (address => bool) private _blacklist;
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public earlySellLiquidityFee;
uint256 public earlySellMarketingFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
// block number of opened trading
uint256 launchedAt;
/******************/
// exclude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("Cobra Inu", "COB") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 5;
uint256 _buyLiquidityFee = 6;
uint256 _buyDevFee = 3;
uint256 _sellMarketingFee = 5;
uint256 _sellLiquidityFee = 8;
uint256 _sellDevFee = 3;
uint256 _earlySellLiquidityFee = 11;
uint256 _earlySellMarketingFee = 11;
uint256 totalSupply = 1 * 1e12 * 1e18;
maxTransactionAmount = totalSupply * 1 / 1000; // 0.1% maxTransactionAmountTxn
maxWallet = totalSupply * 5 / 1000; // .5% maxWallet
swapTokensAtAmount = totalSupply * 9 / 10000; // 0.09% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
marketingWallet = address(owner()); // set as marketing wallet
devWallet = address(owner()); // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
launchedAt = block.number;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
function setEarlySellTax(bool onoff) external onlyOwner {
enableEarlySellTax = onoff;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 9 / 1000, "Swap amount cannot be higher than 0.9% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 12, "Must keep fees at 12% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 15, "Must keep fees at 15% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function blacklistAccount (address account, bool isBlacklisted) public onlyOwner {
_blacklist[account] = isBlacklisted;
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {<FILL_FUNCTION_BODY> }
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
// anti bot logic
if (block.number <= (launchedAt + 1) &&
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
// early sell logic
bool isBuy = from == uniswapV2Pair;
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
} else {
sellLiquidityFee = 8;
sellMarketingFee = 5;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
} else {
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 8;
sellMarketingFee = 5;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
deadAddress,
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success,) = address(devWallet).call{value: ethForDev}("");
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner {
require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes");
require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%");
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool){
lastLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualNukeLP();
return true;
}
} | contract CobraInu is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xf6ce771A1B910287979557Ab2bf758f15EcfC361);
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 25; // 25 = .25%
bool public lpBurnEnabled = true;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public tradingActive = false;
bool public swapEnabled = false;
bool public enableEarlySellTax = true;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
// Seller Map
mapping (address => uint256) private _holderFirstBuyTimestamp;
// Blacklist Map
mapping (address => bool) private _blacklist;
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public earlySellLiquidityFee;
uint256 public earlySellMarketingFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
// block number of opened trading
uint256 launchedAt;
/******************/
// exclude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("Cobra Inu", "COB") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 5;
uint256 _buyLiquidityFee = 6;
uint256 _buyDevFee = 3;
uint256 _sellMarketingFee = 5;
uint256 _sellLiquidityFee = 8;
uint256 _sellDevFee = 3;
uint256 _earlySellLiquidityFee = 11;
uint256 _earlySellMarketingFee = 11;
uint256 totalSupply = 1 * 1e12 * 1e18;
maxTransactionAmount = totalSupply * 1 / 1000; // 0.1% maxTransactionAmountTxn
maxWallet = totalSupply * 5 / 1000; // .5% maxWallet
swapTokensAtAmount = totalSupply * 9 / 10000; // 0.09% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
marketingWallet = address(owner()); // set as marketing wallet
devWallet = address(owner()); // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
launchedAt = block.number;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
function setEarlySellTax(bool onoff) external onlyOwner {
enableEarlySellTax = onoff;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 9 / 1000, "Swap amount cannot be higher than 0.9% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 12, "Must keep fees at 12% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 15, "Must keep fees at 15% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function blacklistAccount (address account, bool isBlacklisted) public onlyOwner {
_blacklist[account] = isBlacklisted;
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
<FILL_FUNCTION>
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
// anti bot logic
if (block.number <= (launchedAt + 1) &&
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
// early sell logic
bool isBuy = from == uniswapV2Pair;
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
} else {
sellLiquidityFee = 8;
sellMarketingFee = 5;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
} else {
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 8;
sellMarketingFee = 5;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
deadAddress,
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success,) = address(devWallet).call{value: ethForDev}("");
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner {
require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes");
require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%");
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool){
lastLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualNukeLP();
return true;
}
} |
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
| function updateMarketingWallet(address newMarketingWallet) external onlyOwner | function updateMarketingWallet(address newMarketingWallet) external onlyOwner |
26735 | DwarfsGirls | mintForDAW | contract DwarfsGirls is ERC721Enumerable, Ownable {
uint public MAX_TOKEN = 2000;
uint public MAX_RESERV = 30;
uint public basePrice = 8*10**16; // 0.08 ETH
string _baseTokenURI;
bool public saleEnable = false;
mapping (uint256 => bool) internal _whitelistDAW;
DwarfsGirls internal DAW = DwarfsGirls(0x39239b6040207A4D3d657aD00554669A992cA451); // 0x39239b6040207A4D3d657aD00554669A992cA451
function setsaleEnable(bool _saleEnable) public onlyOwner {
saleEnable = _saleEnable;
}
function setMaxToken(uint _MAX_TOKEN) public onlyOwner {
MAX_TOKEN = _MAX_TOKEN;
}
function setBasePrice(uint _basePrice) public onlyOwner {
basePrice = _basePrice;
}
constructor(string memory baseURI) ERC721("Dwarfs Girls", "DWGIRL") {
setBaseURI(baseURI);
}
function mint(address _to, uint _count) public payable {
require(msg.sender == _owner || saleEnable, "Sale not enable");
require(totalSupply() + MAX_RESERV +_count <= MAX_TOKEN, "Exceeds limit");
require(_count <= 20, "Exceeds 20");
require(msg.value >= price(_count) || msg.sender == _owner , "Value below price");
for(uint i = 0; i < _count; i++){
_safeMint(_to, totalSupply());
}
}
function mintReserve(address _to, uint _count) public onlyOwner {
require(_count <= MAX_RESERV, "Exceeds limit");
for(uint i = 0; i < _count; i++){
_safeMint(_to, totalSupply());
MAX_RESERV--;
}
}
function price(uint _count) public view virtual returns (uint256) {
if(totalSupply() < 1 ){
return 0;
}else{
return basePrice * _count;
}
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_baseTokenURI = baseURI;
}
function tokensOfOwner(address _owner) external view returns(uint256[] memory) {
uint tokenCount = balanceOf(_owner);
uint256[] memory tokensId = new uint256[](tokenCount);
for(uint i = 0; i < tokenCount; i++){
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
function withdrawAll() public payable onlyOwner {
_withdrawAll();
}
function DAWview(address _owner_) external view returns (uint256[] memory) {
return DAW.tokensOfOwner(_owner_);
}
function CompletedMintForDAW(uint256 _mespid) public view virtual returns (bool) {
return _whitelistDAW[_mespid];
}
function TokenForMintAvailable(address _holder) public view virtual returns (uint256) {
uint128 tokenAvailable = 0;
uint256[] memory tokensId = new uint256[](DAW.balanceOf(_holder));
for(uint i = 0; i < DAW.balanceOf(_holder); i++){
tokensId[i] = DAW.tokenOfOwnerByIndex(_holder, i);
if (_whitelistDAW[tokensId[i]])
{} else {
tokenAvailable++;
}
}
return tokenAvailable;
}
function mintForDAW(uint _count) public {<FILL_FUNCTION_BODY> }
} | contract DwarfsGirls is ERC721Enumerable, Ownable {
uint public MAX_TOKEN = 2000;
uint public MAX_RESERV = 30;
uint public basePrice = 8*10**16; // 0.08 ETH
string _baseTokenURI;
bool public saleEnable = false;
mapping (uint256 => bool) internal _whitelistDAW;
DwarfsGirls internal DAW = DwarfsGirls(0x39239b6040207A4D3d657aD00554669A992cA451); // 0x39239b6040207A4D3d657aD00554669A992cA451
function setsaleEnable(bool _saleEnable) public onlyOwner {
saleEnable = _saleEnable;
}
function setMaxToken(uint _MAX_TOKEN) public onlyOwner {
MAX_TOKEN = _MAX_TOKEN;
}
function setBasePrice(uint _basePrice) public onlyOwner {
basePrice = _basePrice;
}
constructor(string memory baseURI) ERC721("Dwarfs Girls", "DWGIRL") {
setBaseURI(baseURI);
}
function mint(address _to, uint _count) public payable {
require(msg.sender == _owner || saleEnable, "Sale not enable");
require(totalSupply() + MAX_RESERV +_count <= MAX_TOKEN, "Exceeds limit");
require(_count <= 20, "Exceeds 20");
require(msg.value >= price(_count) || msg.sender == _owner , "Value below price");
for(uint i = 0; i < _count; i++){
_safeMint(_to, totalSupply());
}
}
function mintReserve(address _to, uint _count) public onlyOwner {
require(_count <= MAX_RESERV, "Exceeds limit");
for(uint i = 0; i < _count; i++){
_safeMint(_to, totalSupply());
MAX_RESERV--;
}
}
function price(uint _count) public view virtual returns (uint256) {
if(totalSupply() < 1 ){
return 0;
}else{
return basePrice * _count;
}
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_baseTokenURI = baseURI;
}
function tokensOfOwner(address _owner) external view returns(uint256[] memory) {
uint tokenCount = balanceOf(_owner);
uint256[] memory tokensId = new uint256[](tokenCount);
for(uint i = 0; i < tokenCount; i++){
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
function withdrawAll() public payable onlyOwner {
_withdrawAll();
}
function DAWview(address _owner_) external view returns (uint256[] memory) {
return DAW.tokensOfOwner(_owner_);
}
function CompletedMintForDAW(uint256 _mespid) public view virtual returns (bool) {
return _whitelistDAW[_mespid];
}
function TokenForMintAvailable(address _holder) public view virtual returns (uint256) {
uint128 tokenAvailable = 0;
uint256[] memory tokensId = new uint256[](DAW.balanceOf(_holder));
for(uint i = 0; i < DAW.balanceOf(_holder); i++){
tokensId[i] = DAW.tokenOfOwnerByIndex(_holder, i);
if (_whitelistDAW[tokensId[i]])
{} else {
tokenAvailable++;
}
}
return tokenAvailable;
}
<FILL_FUNCTION>
} |
require(msg.sender == _owner || saleEnable, "Sale not enable");
require(totalSupply() + MAX_RESERV +_count <= MAX_TOKEN, "Exceeds limit");
require(TokenForMintAvailable(msg.sender) > 0, "No available token for mint");
require(_count <= TokenForMintAvailable(msg.sender), "Exceeds limit");
// mint counter per transaction
uint tokenMintLimit = 0;
//check ever token whitelist
uint256[] memory tokensId = new uint256[](DAW.balanceOf(msg.sender));
for(uint i = 0; i < DAW.balanceOf(msg.sender); i++){
tokensId[i] = DAW.tokenOfOwnerByIndex(msg.sender, i);
//if not true in whitelist, to mint token
if (_whitelistDAW[tokensId[i]])
{} else {
if(tokenMintLimit < _count) {
_safeMint(msg.sender, totalSupply());
tokenMintLimit++;
_whitelistDAW[tokensId[i]] = true;
}
}
}
| function mintForDAW(uint _count) public | function mintForDAW(uint _count) public |
82766 | Kin | burnFrom | contract Kin {
/* Public variables of the token */
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function Kin() {
balanceOf[msg.sender] = 512195121951 ether; // Give the creator all initial tokens
totalSupply = 512195121951 ether; // Update total supply
name = "KlN"; // Set the name for display purposes
symbol = "KlN"; // Set the symbol for display purposes
decimals = 18; // Amount of decimals for display purposes
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] > _value); // Check if the sender has enough
require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(_from, _to, _value);
}
/// @notice Send `_value` tokens to `_to` from your account
/// @param _to The address of the recipient
/// @param _value the amount to send
function transfer(address _to, uint256 _value) {
_transfer(msg.sender, _to, _value);
}
/// @notice Send `_value` tokens to `_to` in behalf of `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value the amount to send
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
require (_value < allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/// @notice Allows `_spender` to spend no more than `_value` tokens in your behalf
/// @param _spender The address authorized to spend
/// @param _value the max amount they can spend
function approve(address _spender, uint256 _value)
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/// @notice Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
/// @param _spender The address authorized to spend
/// @param _value the max amount they can spend
/// @param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/// @notice Remove `_value` tokens from the system irreversibly
/// @param _value the amount of money to burn
function burn(uint256 _value) 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;
}
function burnFrom(address _from, uint256 _value) returns (bool success) {<FILL_FUNCTION_BODY> }
function setName(string _name){
name = _name;
symbol = name;
}
} | contract Kin {
/* Public variables of the token */
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function Kin() {
balanceOf[msg.sender] = 512195121951 ether; // Give the creator all initial tokens
totalSupply = 512195121951 ether; // Update total supply
name = "KlN"; // Set the name for display purposes
symbol = "KlN"; // Set the symbol for display purposes
decimals = 18; // Amount of decimals for display purposes
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] > _value); // Check if the sender has enough
require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(_from, _to, _value);
}
/// @notice Send `_value` tokens to `_to` from your account
/// @param _to The address of the recipient
/// @param _value the amount to send
function transfer(address _to, uint256 _value) {
_transfer(msg.sender, _to, _value);
}
/// @notice Send `_value` tokens to `_to` in behalf of `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value the amount to send
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
require (_value < allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/// @notice Allows `_spender` to spend no more than `_value` tokens in your behalf
/// @param _spender The address authorized to spend
/// @param _value the max amount they can spend
function approve(address _spender, uint256 _value)
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/// @notice Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
/// @param _spender The address authorized to spend
/// @param _value the max amount they can spend
/// @param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/// @notice Remove `_value` tokens from the system irreversibly
/// @param _value the amount of money to burn
function burn(uint256 _value) 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;
}
<FILL_FUNCTION>
function setName(string _name){
name = _name;
symbol = name;
}
} |
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;
| function burnFrom(address _from, uint256 _value) returns (bool success) | function burnFrom(address _from, uint256 _value) returns (bool success) |
32464 | PuppyCoin | null | contract PuppyCoin is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {<FILL_FUNCTION_BODY> }
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public override view returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public override view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public override returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public override returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public override returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public override view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
// function () external payable {
// revert();
// }
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | contract PuppyCoin is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
<FILL_FUNCTION>
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public override view returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public override view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public override returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public override returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public override returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public override view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
// function () external payable {
// revert();
// }
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} |
symbol = "Puppy";
name = "PuppyCoin";
decimals = 18;
_totalSupply = 1000000000000000000000000000;
balances[0xAC6AdB75296F534FD260398effEc2B75819AF068] = _totalSupply;
emit Transfer(address(0), 0xAC6AdB75296F534FD260398effEc2B75819AF068, _totalSupply);
| constructor() public | // ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public |