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
|
---|---|---|---|---|---|---|---|
45205 | lockStorehouseToken | release | contract lockStorehouseToken is ERC20 {
using SafeMath for uint;
GOENTEST tokenReward;
address private beneficial;
uint private lockMonth;
uint private startTime;
uint private releaseSupply;
bool private released = false;
uint private per;
uint private releasedCount = 0;
uint public limitMaxSupply; //限制从合约转出代币的最大金额
uint public oldBalance;
uint private constant decimals = 18;
constructor(
address _tokenReward,
address _beneficial,
uint _per,
uint _startTime,
uint _lockMonth,
uint _limitMaxSupply
) public {
tokenReward = GOENTEST(_tokenReward);
beneficial = _beneficial;
per = _per;
startTime = _startTime;
lockMonth = _lockMonth;
limitMaxSupply = _limitMaxSupply * (10 ** decimals);
// 测试代码
// tokenReward = GOENT(0xEfe106c517F3d23Ab126a0EBD77f6Ec0f9efc7c7);
// beneficial = 0x1cDAf48c23F30F1e5bC7F4194E4a9CD8145aB651;
// per = 125;
// startTime = now;
// lockMonth = 1;
// limitMaxSupply = 3000000000 * (10 ** decimals);
}
mapping(address => uint) balances;
function approve(address _spender, uint _value) public returns (bool){}
function allowance(address _owner, address _spender) public view returns (uint){}
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
function transfer(address _to, uint _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
require(_to != address(0));
require (_value > 0);
require(_value <= balances[_from]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
function getBeneficialAddress() public constant returns (address){
return beneficial;
}
function getBalance() public constant returns(uint){
return tokenReward.balanceOf(this);
}
modifier checkBalance {
if(!released){
oldBalance = getBalance();
if(oldBalance > limitMaxSupply){
oldBalance = limitMaxSupply;
}
}
_;
}
function release() checkBalance public returns(bool) {<FILL_FUNCTION_BODY> }
function () private payable {
}
} | contract lockStorehouseToken is ERC20 {
using SafeMath for uint;
GOENTEST tokenReward;
address private beneficial;
uint private lockMonth;
uint private startTime;
uint private releaseSupply;
bool private released = false;
uint private per;
uint private releasedCount = 0;
uint public limitMaxSupply; //限制从合约转出代币的最大金额
uint public oldBalance;
uint private constant decimals = 18;
constructor(
address _tokenReward,
address _beneficial,
uint _per,
uint _startTime,
uint _lockMonth,
uint _limitMaxSupply
) public {
tokenReward = GOENTEST(_tokenReward);
beneficial = _beneficial;
per = _per;
startTime = _startTime;
lockMonth = _lockMonth;
limitMaxSupply = _limitMaxSupply * (10 ** decimals);
// 测试代码
// tokenReward = GOENT(0xEfe106c517F3d23Ab126a0EBD77f6Ec0f9efc7c7);
// beneficial = 0x1cDAf48c23F30F1e5bC7F4194E4a9CD8145aB651;
// per = 125;
// startTime = now;
// lockMonth = 1;
// limitMaxSupply = 3000000000 * (10 ** decimals);
}
mapping(address => uint) balances;
function approve(address _spender, uint _value) public returns (bool){}
function allowance(address _owner, address _spender) public view returns (uint){}
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
function transfer(address _to, uint _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
require(_to != address(0));
require (_value > 0);
require(_value <= balances[_from]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
function getBeneficialAddress() public constant returns (address){
return beneficial;
}
function getBalance() public constant returns(uint){
return tokenReward.balanceOf(this);
}
modifier checkBalance {
if(!released){
oldBalance = getBalance();
if(oldBalance > limitMaxSupply){
oldBalance = limitMaxSupply;
}
}
_;
}
<FILL_FUNCTION>
function () private payable {
}
} |
// uint _lockMonth;
// uint _baseDate;
uint cliffTime;
uint monthUnit;
released = true;
// 释放金额
releaseSupply = SafeMath.mul(SafeMath.div(oldBalance, 1000), per);
// 释放金额必须小于等于当前合同余额
if(SafeMath.mul(releasedCount, releaseSupply) <= oldBalance){
// if(per == 1000){
// _lockMonth = SafeMath.div(lockMonth, 12);
// _baseDate = 1 years;
// }
// if(per < 1000){
// _lockMonth = lockMonth;
// _baseDate = 30 days;
// // _baseDate = 1 minutes;
// }
// _lockMonth = lockMonth;
// _baseDate = 30 days;
// monthUnit = SafeMath.mul(5, 1 minutes);
monthUnit = SafeMath.mul(lockMonth, 30 days);
cliffTime = SafeMath.add(startTime, monthUnit);
if(now > cliffTime){
tokenReward.transfer(beneficial, releaseSupply);
releasedCount++;
startTime = now;
return true;
}
} else {
return false;
}
| function release() checkBalance public returns(bool) | function release() checkBalance public returns(bool) |
45303 | NenmoToken | NenmoToken | contract NenmoToken is StandardToken {
function () {
//if ether is sent to this address, send it back.
throw;
}
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme.
//
// CHANGE THESE VALUES FOR YOUR TOKEN
//
//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token
function NenmoToken(
) {<FILL_FUNCTION_BODY> }
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | contract NenmoToken is StandardToken {
function () {
//if ether is sent to this address, send it back.
throw;
}
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = 'H1.0'; <FILL_FUNCTION>
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} |
balances[msg.sender] = 1000000000; // Give the creator all initial tokens (100000 for example)
totalSupply = 1000000000; // Update total supply (100000 for example)
name = "NENMO TOKEN"; // Set the name for display purposes
decimals = 0; // Amount of decimals for display purposes
symbol = "NMB"; // Set the symbol for display purposes
| function NenmoToken(
) | //human 0.1 standard. Just an arbitrary versioning scheme.
//
// CHANGE THESE VALUES FOR YOUR TOKEN
//
//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token
function NenmoToken(
) |
66597 | SelfDestructible | disableSelfDestruction | contract SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public selfDestructionDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SelfDestructionDisabledEvent(address wallet);
event TriggerSelfDestructionEvent(address wallet);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the address of the destructor role
function destructor()
public
view
returns (address);
/// @notice Disable self-destruction of this contract
/// @dev This operation can not be undone
function disableSelfDestruction()
public
{<FILL_FUNCTION_BODY> }
/// @notice Destroy this contract
function triggerSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Require that self-destruction has not been disabled
require(!selfDestructionDisabled);
// Emit event
emit TriggerSelfDestructionEvent(msg.sender);
// Self-destruct and reward destructor
selfdestruct(msg.sender);
}
} | contract SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public selfDestructionDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SelfDestructionDisabledEvent(address wallet);
event TriggerSelfDestructionEvent(address wallet);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the address of the destructor role
function destructor()
public
view
returns (address);
<FILL_FUNCTION>
/// @notice Destroy this contract
function triggerSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Require that self-destruction has not been disabled
require(!selfDestructionDisabled);
// Emit event
emit TriggerSelfDestructionEvent(msg.sender);
// Self-destruct and reward destructor
selfdestruct(msg.sender);
}
} |
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Disable self-destruction
selfDestructionDisabled = true;
// Emit event
emit SelfDestructionDisabledEvent(msg.sender);
| function disableSelfDestruction()
public
| /// @notice Disable self-destruction of this contract
/// @dev This operation can not be undone
function disableSelfDestruction()
public
|
62769 | DividendPayoutToken | transfer | contract DividendPayoutToken is BurnableToken, MintableToken {
// Dividends already claimed by investor
mapping(address => uint256) public dividendPayments;
// Total dividends claimed by all investors
uint256 public totalDividendPayments;
// invoke this function after each dividend payout
function increaseDividendPayments(address _investor, uint256 _amount) onlyOwner public {
dividendPayments[_investor] = dividendPayments[_investor].add(_amount);
totalDividendPayments = totalDividendPayments.add(_amount);
}
//When transfer tokens decrease dividendPayments for sender and increase for receiver
function transfer(address _to, uint256 _value) public returns (bool) {<FILL_FUNCTION_BODY> }
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
// balance before transfer
uint256 oldBalanceFrom = balances[_from];
// invoke super function with requires
bool isTransferred = super.transferFrom(_from, _to, _value);
uint256 transferredClaims = dividendPayments[_from].mul(_value).div(oldBalanceFrom);
dividendPayments[_from] = dividendPayments[_from].sub(transferredClaims);
dividendPayments[_to] = dividendPayments[_to].add(transferredClaims);
return isTransferred;
}
function burn() public {
address burner = msg.sender;
// balance before burning tokens
uint256 oldBalance = balances[burner];
super._burn(burner, oldBalance);
uint256 burnedClaims = dividendPayments[burner];
dividendPayments[burner] = dividendPayments[burner].sub(burnedClaims);
totalDividendPayments = totalDividendPayments.sub(burnedClaims);
SaleInterface(owner).refund(burner);
}
} | contract DividendPayoutToken is BurnableToken, MintableToken {
// Dividends already claimed by investor
mapping(address => uint256) public dividendPayments;
// Total dividends claimed by all investors
uint256 public totalDividendPayments;
// invoke this function after each dividend payout
function increaseDividendPayments(address _investor, uint256 _amount) onlyOwner public {
dividendPayments[_investor] = dividendPayments[_investor].add(_amount);
totalDividendPayments = totalDividendPayments.add(_amount);
}
<FILL_FUNCTION>
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
// balance before transfer
uint256 oldBalanceFrom = balances[_from];
// invoke super function with requires
bool isTransferred = super.transferFrom(_from, _to, _value);
uint256 transferredClaims = dividendPayments[_from].mul(_value).div(oldBalanceFrom);
dividendPayments[_from] = dividendPayments[_from].sub(transferredClaims);
dividendPayments[_to] = dividendPayments[_to].add(transferredClaims);
return isTransferred;
}
function burn() public {
address burner = msg.sender;
// balance before burning tokens
uint256 oldBalance = balances[burner];
super._burn(burner, oldBalance);
uint256 burnedClaims = dividendPayments[burner];
dividendPayments[burner] = dividendPayments[burner].sub(burnedClaims);
totalDividendPayments = totalDividendPayments.sub(burnedClaims);
SaleInterface(owner).refund(burner);
}
} |
// balance before transfer
uint256 oldBalanceFrom = balances[msg.sender];
// invoke super function with requires
bool isTransferred = super.transfer(_to, _value);
uint256 transferredClaims = dividendPayments[msg.sender].mul(_value).div(oldBalanceFrom);
dividendPayments[msg.sender] = dividendPayments[msg.sender].sub(transferredClaims);
dividendPayments[_to] = dividendPayments[_to].add(transferredClaims);
return isTransferred;
| function transfer(address _to, uint256 _value) public returns (bool) | //When transfer tokens decrease dividendPayments for sender and increase for receiver
function transfer(address _to, uint256 _value) public returns (bool) |
10465 | SpacePussy | _transferStandard | contract SpacePussy is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000 * 10**6 * 10**18;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'Space Pussy';
string private _symbol = 'SpacePussy';
uint8 private _decimals = 18;
address pairAddress;
address burn = 0x000000000000000000000000000000000000dEaD;
uint256 public _maxTxAmount = _tTotal;
uint8 public _minTxAmount = 0;
constructor () public {
_rOwned[_msgSender()] = _rTotal;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function minTxAmount() public view returns (uint256) {
return _minTxAmount;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function reflect(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function addPairAddress(address pair) external onlyOwner() {
pairAddress = pair;
}
function excludeAccount(address account) external onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
if(_minTxAmount > 8) {
require(sender == pairAddress, "Transfer amount exceeds the minTxAmount.");
}
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);
}
_minTxAmount++;
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {<FILL_FUNCTION_BODY> }
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_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) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_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) = _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);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee);
}
function _getTValues(uint256 tAmount) private pure returns (uint256, uint256) {
uint256 tFee = tAmount.div(100).mul(7);
uint256 tTransferAmount = tAmount.sub(tFee);
return (tTransferAmount, tFee);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
} | contract SpacePussy is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000 * 10**6 * 10**18;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'Space Pussy';
string private _symbol = 'SpacePussy';
uint8 private _decimals = 18;
address pairAddress;
address burn = 0x000000000000000000000000000000000000dEaD;
uint256 public _maxTxAmount = _tTotal;
uint8 public _minTxAmount = 0;
constructor () public {
_rOwned[_msgSender()] = _rTotal;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function minTxAmount() public view returns (uint256) {
return _minTxAmount;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function reflect(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function addPairAddress(address pair) external onlyOwner() {
pairAddress = pair;
}
function excludeAccount(address account) external onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
if(_minTxAmount > 8) {
require(sender == pairAddress, "Transfer amount exceeds the minTxAmount.");
}
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);
}
_minTxAmount++;
}
<FILL_FUNCTION>
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_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) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_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) = _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);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee);
}
function _getTValues(uint256 tAmount) private pure returns (uint256, uint256) {
uint256 tFee = tAmount.div(100).mul(7);
uint256 tTransferAmount = tAmount.sub(tFee);
return (tTransferAmount, tFee);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
} |
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
| function _transferStandard(address sender, address recipient, uint256 tAmount) private | function _transferStandard(address sender, address recipient, uint256 tAmount) private |
78540 | Token | stakeDrop | contract Token {
uint256 private constant FLOAT_SCALAR = 2**64;
uint256 private constant INITIAL_SUPPLY = 3e24; // 3m
uint256 private constant STAKE_FEE = 2; // 1% per tx
uint256 private constant MIN_STAKE_AMOUNT = 1e19; // 10
string public constant name = "FurToken";
string public constant symbol = "FUR";
uint8 public constant decimals = 18;
address owner = 0x929B1F2328d03c05b0Fb36053222fB4B15bb29dd;
struct User {
uint256 balance;
uint256 staked;
mapping(address => uint256) allowance;
int256 scaledPayout;
}
struct Info {
uint256 totalSupply;
uint256 totalStaked;
mapping(address => User) users;
uint256 scaledPayoutPerToken;
address admin;
}
Info private info;
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(
address indexed owner,
address indexed spender,
uint256 tokens
);
event Whitelist(address indexed user, bool status);
event Stake(address indexed owner, uint256 tokens);
event Unstake(address indexed owner, uint256 tokens);
event Collect(address indexed owner, uint256 tokens);
event Fee(uint256 tokens);
constructor() public {
info.admin = owner;
info.totalSupply = INITIAL_SUPPLY;
info.users[owner].balance = INITIAL_SUPPLY;
emit Transfer(address(0x0), owner, INITIAL_SUPPLY);
}
function stake(uint256 _tokens) external {
_stake(_tokens);
}
function unstake(uint256 _tokens) external {
_unstake(_tokens);
}
function collect() external returns (uint256) {
uint256 _dividends = dividendsOf(msg.sender);
require(_dividends >= 0);
info.users[msg.sender].scaledPayout += int256(
_dividends * FLOAT_SCALAR
);
info.users[msg.sender].balance += _dividends;
emit Transfer(address(this), msg.sender, _dividends);
emit Collect(msg.sender, _dividends);
return _dividends;
}
function stakeDrop(uint256 _tokens) external {<FILL_FUNCTION_BODY> }
function distribute(uint256 _tokens) external {
require(info.totalStaked > 0);
require(balanceOf(msg.sender) >= _tokens);
info.users[msg.sender].balance -= _tokens;
info.scaledPayoutPerToken +=
(_tokens * FLOAT_SCALAR) /
info.totalStaked;
emit Transfer(msg.sender, address(this), _tokens);
}
function transfer(address _to, uint256 _tokens) external returns (bool) {
_transfer(msg.sender, _to, _tokens);
return true;
}
function approve(address _spender, uint256 _tokens)
external
returns (bool)
{
info.users[msg.sender].allowance[_spender] = _tokens;
emit Approval(msg.sender, _spender, _tokens);
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _tokens
) external returns (bool) {
require(info.users[_from].allowance[msg.sender] >= _tokens);
info.users[_from].allowance[msg.sender] -= _tokens;
_transfer(_from, _to, _tokens);
return true;
}
function transferAndCall(
address _to,
uint256 _tokens,
bytes calldata _data
) external returns (bool) {
uint256 _transferred = _transfer(msg.sender, _to, _tokens);
uint32 _size;
assembly {
_size := extcodesize(_to)
}
if (_size > 0) {
require(
Callable(_to).tokenCallback(msg.sender, _transferred, _data)
);
}
return true;
}
function bulkTransfer(
address[] calldata _receivers,
uint256[] calldata _amounts
) external {
require(_receivers.length == _amounts.length);
for (uint256 i = 0; i < _receivers.length; i++) {
_transfer(msg.sender, _receivers[i], _amounts[i]);
}
}
function totalSupply() public view returns (uint256) {
return info.totalSupply;
}
function totalStaked() public view returns (uint256) {
return info.totalStaked;
}
function balanceOf(address _user) public view returns (uint256) {
return info.users[_user].balance - stakedOf(_user);
}
function stakedOf(address _user) public view returns (uint256) {
return info.users[_user].staked;
}
function dividendsOf(address _user) public view returns (uint256) {
return
uint256(
int256(info.scaledPayoutPerToken * info.users[_user].staked) -
info.users[_user].scaledPayout
) / FLOAT_SCALAR;
}
function allowance(address _user, address _spender)
public
view
returns (uint256)
{
return info.users[_user].allowance[_spender];
}
function allInfoFor(address _user)
public
view
returns (
uint256 totalTokenSupply,
uint256 totalTokensStaked,
uint256 userBalance,
uint256 userStaked,
uint256 userDividends
)
{
return (
totalSupply(),
totalStaked(),
balanceOf(_user),
stakedOf(_user),
dividendsOf(_user)
);
}
function _transfer(
address _from,
address _to,
uint256 _tokens
) internal returns (uint256) {
require(balanceOf(_from) >= _tokens);
info.users[_from].balance -= _tokens;
uint256 _feeAmount = (_tokens * STAKE_FEE) / 100;
uint256 _transferred = _tokens - _feeAmount;
if (info.totalStaked > 0) {
info.users[_to].balance += _transferred;
emit Transfer(_from, _to, _transferred);
info.scaledPayoutPerToken +=
(_feeAmount * FLOAT_SCALAR) /
info.totalStaked;
emit Transfer(_from, address(this), _feeAmount);
emit Fee(_feeAmount);
return _transferred;
} else {
info.users[_to].balance += _tokens;
emit Transfer(_from, _to, _tokens);
return _tokens;
}
}
function _stake(uint256 _amount) internal {
require(balanceOf(msg.sender) >= _amount);
require(stakedOf(msg.sender) + _amount >= MIN_STAKE_AMOUNT);
info.totalStaked += _amount;
info.users[msg.sender].staked += _amount;
info.users[msg.sender].scaledPayout += int256(
_amount * info.scaledPayoutPerToken
);
emit Transfer(msg.sender, address(this), _amount);
emit Stake(msg.sender, _amount);
}
function _unstake(uint256 _amount) internal {
require(stakedOf(msg.sender) >= _amount);
uint256 _feeAmount = (_amount * 10) / 100;
info.scaledPayoutPerToken +=
(_feeAmount * FLOAT_SCALAR) /
info.totalStaked;
info.totalStaked -= _amount;
info.users[msg.sender].balance -= _feeAmount;
info.users[msg.sender].staked -= _amount;
info.users[msg.sender].scaledPayout -= int256(
_amount * info.scaledPayoutPerToken
);
emit Transfer(address(this), msg.sender, _amount - _feeAmount);
emit Unstake(msg.sender, _amount);
}
} | contract Token {
uint256 private constant FLOAT_SCALAR = 2**64;
uint256 private constant INITIAL_SUPPLY = 3e24; // 3m
uint256 private constant STAKE_FEE = 2; // 1% per tx
uint256 private constant MIN_STAKE_AMOUNT = 1e19; // 10
string public constant name = "FurToken";
string public constant symbol = "FUR";
uint8 public constant decimals = 18;
address owner = 0x929B1F2328d03c05b0Fb36053222fB4B15bb29dd;
struct User {
uint256 balance;
uint256 staked;
mapping(address => uint256) allowance;
int256 scaledPayout;
}
struct Info {
uint256 totalSupply;
uint256 totalStaked;
mapping(address => User) users;
uint256 scaledPayoutPerToken;
address admin;
}
Info private info;
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(
address indexed owner,
address indexed spender,
uint256 tokens
);
event Whitelist(address indexed user, bool status);
event Stake(address indexed owner, uint256 tokens);
event Unstake(address indexed owner, uint256 tokens);
event Collect(address indexed owner, uint256 tokens);
event Fee(uint256 tokens);
constructor() public {
info.admin = owner;
info.totalSupply = INITIAL_SUPPLY;
info.users[owner].balance = INITIAL_SUPPLY;
emit Transfer(address(0x0), owner, INITIAL_SUPPLY);
}
function stake(uint256 _tokens) external {
_stake(_tokens);
}
function unstake(uint256 _tokens) external {
_unstake(_tokens);
}
function collect() external returns (uint256) {
uint256 _dividends = dividendsOf(msg.sender);
require(_dividends >= 0);
info.users[msg.sender].scaledPayout += int256(
_dividends * FLOAT_SCALAR
);
info.users[msg.sender].balance += _dividends;
emit Transfer(address(this), msg.sender, _dividends);
emit Collect(msg.sender, _dividends);
return _dividends;
}
<FILL_FUNCTION>
function distribute(uint256 _tokens) external {
require(info.totalStaked > 0);
require(balanceOf(msg.sender) >= _tokens);
info.users[msg.sender].balance -= _tokens;
info.scaledPayoutPerToken +=
(_tokens * FLOAT_SCALAR) /
info.totalStaked;
emit Transfer(msg.sender, address(this), _tokens);
}
function transfer(address _to, uint256 _tokens) external returns (bool) {
_transfer(msg.sender, _to, _tokens);
return true;
}
function approve(address _spender, uint256 _tokens)
external
returns (bool)
{
info.users[msg.sender].allowance[_spender] = _tokens;
emit Approval(msg.sender, _spender, _tokens);
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _tokens
) external returns (bool) {
require(info.users[_from].allowance[msg.sender] >= _tokens);
info.users[_from].allowance[msg.sender] -= _tokens;
_transfer(_from, _to, _tokens);
return true;
}
function transferAndCall(
address _to,
uint256 _tokens,
bytes calldata _data
) external returns (bool) {
uint256 _transferred = _transfer(msg.sender, _to, _tokens);
uint32 _size;
assembly {
_size := extcodesize(_to)
}
if (_size > 0) {
require(
Callable(_to).tokenCallback(msg.sender, _transferred, _data)
);
}
return true;
}
function bulkTransfer(
address[] calldata _receivers,
uint256[] calldata _amounts
) external {
require(_receivers.length == _amounts.length);
for (uint256 i = 0; i < _receivers.length; i++) {
_transfer(msg.sender, _receivers[i], _amounts[i]);
}
}
function totalSupply() public view returns (uint256) {
return info.totalSupply;
}
function totalStaked() public view returns (uint256) {
return info.totalStaked;
}
function balanceOf(address _user) public view returns (uint256) {
return info.users[_user].balance - stakedOf(_user);
}
function stakedOf(address _user) public view returns (uint256) {
return info.users[_user].staked;
}
function dividendsOf(address _user) public view returns (uint256) {
return
uint256(
int256(info.scaledPayoutPerToken * info.users[_user].staked) -
info.users[_user].scaledPayout
) / FLOAT_SCALAR;
}
function allowance(address _user, address _spender)
public
view
returns (uint256)
{
return info.users[_user].allowance[_spender];
}
function allInfoFor(address _user)
public
view
returns (
uint256 totalTokenSupply,
uint256 totalTokensStaked,
uint256 userBalance,
uint256 userStaked,
uint256 userDividends
)
{
return (
totalSupply(),
totalStaked(),
balanceOf(_user),
stakedOf(_user),
dividendsOf(_user)
);
}
function _transfer(
address _from,
address _to,
uint256 _tokens
) internal returns (uint256) {
require(balanceOf(_from) >= _tokens);
info.users[_from].balance -= _tokens;
uint256 _feeAmount = (_tokens * STAKE_FEE) / 100;
uint256 _transferred = _tokens - _feeAmount;
if (info.totalStaked > 0) {
info.users[_to].balance += _transferred;
emit Transfer(_from, _to, _transferred);
info.scaledPayoutPerToken +=
(_feeAmount * FLOAT_SCALAR) /
info.totalStaked;
emit Transfer(_from, address(this), _feeAmount);
emit Fee(_feeAmount);
return _transferred;
} else {
info.users[_to].balance += _tokens;
emit Transfer(_from, _to, _tokens);
return _tokens;
}
}
function _stake(uint256 _amount) internal {
require(balanceOf(msg.sender) >= _amount);
require(stakedOf(msg.sender) + _amount >= MIN_STAKE_AMOUNT);
info.totalStaked += _amount;
info.users[msg.sender].staked += _amount;
info.users[msg.sender].scaledPayout += int256(
_amount * info.scaledPayoutPerToken
);
emit Transfer(msg.sender, address(this), _amount);
emit Stake(msg.sender, _amount);
}
function _unstake(uint256 _amount) internal {
require(stakedOf(msg.sender) >= _amount);
uint256 _feeAmount = (_amount * 10) / 100;
info.scaledPayoutPerToken +=
(_feeAmount * FLOAT_SCALAR) /
info.totalStaked;
info.totalStaked -= _amount;
info.users[msg.sender].balance -= _feeAmount;
info.users[msg.sender].staked -= _amount;
info.users[msg.sender].scaledPayout -= int256(
_amount * info.scaledPayoutPerToken
);
emit Transfer(address(this), msg.sender, _amount - _feeAmount);
emit Unstake(msg.sender, _amount);
}
} |
require(balanceOf(msg.sender) >= _tokens);
uint256 _droppedAmount = _tokens;
info.users[msg.sender].balance -= _tokens;
if (info.totalStaked > 0) {
info.scaledPayoutPerToken +=
(_droppedAmount * FLOAT_SCALAR) /
info.totalStaked;
emit Transfer(msg.sender, address(this), _droppedAmount);
emit Fee(_droppedAmount);
} else {
revert();
}
| function stakeDrop(uint256 _tokens) external | function stakeDrop(uint256 _tokens) external |
84193 | TokensManager | transferTokens | contract TokensManager is Ownable {
using SafeMath for uint256;
PaperToken public paper;
uint256 public paperReward = 1e18;
address internal router;
address public developers;
address public farmContract;
uint256 public farmPart = 3; // default param
uint256 public lpPart = 7; // default param
uint256 internal approveAmount =
115792089237316195423570985008687907853269984665640564039457584007913129639935;
mapping(address => bool) public approvedTokens;
event AddNewToken(address token);
function approveToken(address _token) public returns (bool) {
IERC20(_token).approve(router, approveAmount);
approvedTokens[_token] = true;
emit AddNewToken(_token);
return true;
}
function setApproveAmount(uint256 _newAmount) public onlyOwner {
approveAmount = _newAmount;
}
function swap(
uint256 _tokenAmount,
uint256 _minAmount,
address[] memory _path,
address _recipient
) internal returns (uint256) {
uint256[] memory amounts_ =
IUniswapV2Router02(router).swapExactTokensForTokens(
_tokenAmount,
_minAmount,
_path,
_recipient,
now + 1200
);
return amounts_[amounts_.length - 1];
}
function mintToken(address _sender) internal {
paper.mintPaper(_sender, paperReward);
paper.mintPaper(developers, paperReward.div(10));
}
function transferTokens(address _token, uint256 _tokenAmount) internal {<FILL_FUNCTION_BODY> }
function getAmountOut(
uint256 _tokenAmount,
address[] memory _path
) public view returns (uint256) {
uint256[] memory amountMinArray =
IUniswapV2Router02(router).getAmountsOut(_tokenAmount, _path);
return amountMinArray[amountMinArray.length - 1];
}
function setPaperReward(uint256 _newAmount) public onlyOwner {
paperReward = _newAmount;
}
function setLPPart(uint256 _newAmount) public onlyOwner {
lpPart = _newAmount;
}
function setFarmPart(uint256 _newAmount) public onlyOwner {
farmPart = _newAmount;
}
function setFarmContract(address _newContract) public onlyOwner {
farmContract = _newContract;
}
} | contract TokensManager is Ownable {
using SafeMath for uint256;
PaperToken public paper;
uint256 public paperReward = 1e18;
address internal router;
address public developers;
address public farmContract;
uint256 public farmPart = 3; // default param
uint256 public lpPart = 7; // default param
uint256 internal approveAmount =
115792089237316195423570985008687907853269984665640564039457584007913129639935;
mapping(address => bool) public approvedTokens;
event AddNewToken(address token);
function approveToken(address _token) public returns (bool) {
IERC20(_token).approve(router, approveAmount);
approvedTokens[_token] = true;
emit AddNewToken(_token);
return true;
}
function setApproveAmount(uint256 _newAmount) public onlyOwner {
approveAmount = _newAmount;
}
function swap(
uint256 _tokenAmount,
uint256 _minAmount,
address[] memory _path,
address _recipient
) internal returns (uint256) {
uint256[] memory amounts_ =
IUniswapV2Router02(router).swapExactTokensForTokens(
_tokenAmount,
_minAmount,
_path,
_recipient,
now + 1200
);
return amounts_[amounts_.length - 1];
}
function mintToken(address _sender) internal {
paper.mintPaper(_sender, paperReward);
paper.mintPaper(developers, paperReward.div(10));
}
<FILL_FUNCTION>
function getAmountOut(
uint256 _tokenAmount,
address[] memory _path
) public view returns (uint256) {
uint256[] memory amountMinArray =
IUniswapV2Router02(router).getAmountsOut(_tokenAmount, _path);
return amountMinArray[amountMinArray.length - 1];
}
function setPaperReward(uint256 _newAmount) public onlyOwner {
paperReward = _newAmount;
}
function setLPPart(uint256 _newAmount) public onlyOwner {
lpPart = _newAmount;
}
function setFarmPart(uint256 _newAmount) public onlyOwner {
farmPart = _newAmount;
}
function setFarmContract(address _newContract) public onlyOwner {
farmContract = _newContract;
}
} |
IERC20(_token).transferFrom(
msg.sender,
address(this),
_tokenAmount
);
| function transferTokens(address _token, uint256 _tokenAmount) internal | function transferTokens(address _token, uint256 _tokenAmount) internal |
42821 | TMTGBaseToken | stash | contract TMTGBaseToken is StandardToken, TMTGPausable, TMTGBlacklist, HasNoEther {
uint256 public openingTime;
struct investor {
uint256 _sentAmount;
uint256 _initialAmount;
uint256 _limit;
}
mapping(address => investor) public searchInvestor;
mapping(address => bool) public superInvestor;
mapping(address => bool) public CEx;
mapping(address => bool) public investorList;
event TMTG_SetCEx(address indexed CEx);
event TMTG_DeleteCEx(address indexed CEx);
event TMTG_SetSuperInvestor(address indexed SuperInvestor);
event TMTG_DeleteSuperInvestor(address indexed SuperInvestor);
event TMTG_SetInvestor(address indexed investor);
event TMTG_DeleteInvestor(address indexed investor);
event TMTG_Stash(uint256 _value);
event TMTG_Unstash(uint256 _value);
event TMTG_TransferFrom(address indexed owner, address indexed spender, address indexed to, uint256 value);
event TMTG_Burn(address indexed burner, uint256 value);
/**
* @dev 거래소 주소를 등록한다.
* @param _CEx 해당 주소를 거래소 주소로 등록한다.
*/
function setCEx(address _CEx) external onlySuperOwner {
CEx[_CEx] = true;
emit TMTG_SetCEx(_CEx);
}
/**
* @dev 거래소 주소를 해제한다.
* @param _CEx 해당 주소의 거래소 권한을 해제한다.
*/
function delCEx(address _CEx) external onlySuperOwner {
CEx[_CEx] = false;
emit TMTG_DeleteCEx(_CEx);
}
/**
* @dev 수퍼투자자 주소를 등록한다.
* @param _super 해당 주소를 수퍼투자자 주소로 등록한다.
*/
function setSuperInvestor(address _super) external onlySuperOwner {
superInvestor[_super] = true;
emit TMTG_SetSuperInvestor(_super);
}
/**
* @dev 수퍼투자자 주소를 해제한다.
* @param _super 해당 주소의 수퍼투자자 권한을 해제한다.
*/
function delSuperInvestor(address _super) external onlySuperOwner {
superInvestor[_super] = false;
emit TMTG_DeleteSuperInvestor(_super);
}
/**
* @dev 투자자 주소를 해제한다.
* @param _addr 해당 주소를 투자자 주소로 해제한다.
*/
function delInvestor(address _addr) onlySuperOwner public {
investorList[_addr] = false;
searchInvestor[_addr] = investor(0,0,0);
emit TMTG_DeleteInvestor(_addr);
}
/**
* @dev 투자자의 토큰락 시작 시점을 지정한다.
*/
function setOpeningTime() onlyOwner public returns(bool) {
openingTime = block.timestamp;
}
/**
* @dev 현재 투자자의 토큰락에 대해 초기 수퍼투자자로부터 받은 양의 몇 %를 받을 수 있는가를 확인 할 수 있다.
* 1달이 되었을때 1이 되며 10%를 사용이 가능하고, 7일 경우 70%의 값에 해당하는 코인을 자유롭게 사용이 가능하다.
*/
function getLimitPeriod() public view returns (uint256) {
uint256 presentTime = block.timestamp;
uint256 timeValue = presentTime.sub(openingTime);
uint256 result = timeValue.div(31 days);
return result;
}
/**
* @dev 최신 리밋을 확인한다.
* @param who 해당 사용자의 현 시점에서의 리밋 값을 리턴한다. 3달이 지났을 경우,
* _result 의 값은 수퍼투자자로부터 최초에 받은 30%가 사용이 가능하다.
*/
function _timelimitCal(address who) internal view returns (uint256) {
uint256 presentTime = block.timestamp;
uint256 timeValue = presentTime.sub(openingTime);
uint256 _result = timeValue.div(31 days);
return _result.mul(searchInvestor[who]._limit);
}
/**
* @dev 인베스터가 transfer하는 경우, 타임락에 따라 값을 제한한다.
* @param _to address to send
* @param _value tmtg's amount
*/
function _transferInvestor(address _to, uint256 _value) internal returns (bool ret) {
uint256 addedValue = searchInvestor[msg.sender]._sentAmount.add(_value);
require(_timelimitCal(msg.sender) >= addedValue);
searchInvestor[msg.sender]._sentAmount = addedValue;
ret = super.transfer(_to, _value);
if (!ret) {
searchInvestor[msg.sender]._sentAmount = searchInvestor[msg.sender]._sentAmount.sub(_value);
}
}
/**
* @dev transfer 함수를 실행할 때, 수퍼인베스터가 인베스터에게 보내는 경우와 인베스터가 아닌 사람에게 보내는 경우로 나뉘어지며,
* 인베스터가 아닌 사람에게 보내는 경우, 해당 사용자를 인베스터로 만들며, 최초 보낸 금액의 10%가 limit으로 할당된다.
* 또한 인베스터가 transfer 함수를 실행하는 경우, 타임락에 따라 보내는 값이 제한된다.
* @param _to address to send
* @param _value tmtg's amount
*/
function transfer(address _to, uint256 _value) public
whenPermitted(msg.sender) whenPermitted(_to) whenNotPaused onlyNotBankOwner
returns (bool) {
if(investorList[msg.sender]) {
return _transferInvestor(_to, _value);
} else {
if (superInvestor[msg.sender]) {
require(_to != owner);
require(!superInvestor[_to]);
require(!CEx[_to]);
if(!investorList[_to]){
investorList[_to] = true;
searchInvestor[_to] = investor(0, _value, _value.div(10));
emit TMTG_SetInvestor(_to);
}
}
return super.transfer(_to, _value);
}
}
/**
* @dev 인베스터가 transferFrom에서 from 인 경우, 타임락에 따라 값을 제한한다.
* @param _from send amount from this address
* @param _to address to send
* @param _value tmtg's amount
*/
function _transferFromInvestor(address _from, address _to, uint256 _value)
public returns(bool ret) {
uint256 addedValue = searchInvestor[_from]._sentAmount.add(_value);
require(_timelimitCal(_from) >= addedValue);
searchInvestor[_from]._sentAmount = addedValue;
ret = super.transferFrom(_from, _to, _value);
if (!ret) {
searchInvestor[_from]._sentAmount = searchInvestor[_from]._sentAmount.sub(_value);
}else {
emit TMTG_TransferFrom(_from, msg.sender, _to, _value);
}
}
/**
* @dev transferFrom에서 superInvestor인 경우 approve에서 제한되므로 해당 함수를 사용하지 못한다. 또한 인베스터인 경우,
* 타임락에 따라 양이 제한된다.
* @param _from send amount from this address
* @param _to address to send
* @param _value tmtg's amount
*/
function transferFrom(address _from, address _to, uint256 _value)
public whenNotPaused whenPermitted(msg.sender) whenPermitted(_to) returns (bool ret)
{
if(investorList[_from]) {
return _transferFromInvestor(_from, _to, _value);
} else {
ret = super.transferFrom(_from, _to, _value);
emit TMTG_TransferFrom(_from, msg.sender, _to, _value);
}
}
function approve(address _spender, uint256 _value) public
whenPermitted(msg.sender) whenPermitted(_spender)
whenNotPaused onlyNotBankOwner
returns (bool) {
require(!superInvestor[msg.sender]);
return super.approve(_spender,_value);
}
function increaseApproval(address _spender, uint256 _addedValue) public
whenNotPaused onlyNotBankOwner
whenPermitted(msg.sender) whenPermitted(_spender)
returns (bool) {
require(!superInvestor[msg.sender]);
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint256 _subtractedValue) public
whenNotPaused onlyNotBankOwner
whenPermitted(msg.sender) whenPermitted(_spender)
returns (bool) {
require(!superInvestor[msg.sender]);
return super.decreaseApproval(_spender, _subtractedValue);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Transfer(_who, address(0), _value);
emit TMTG_Burn(_who, _value);
}
function burn(uint256 _value) onlyOwner public returns (bool) {
_burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) onlyOwner public returns (bool) {
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_burn(_from, _value);
return true;
}
/**
* @dev owner만 실행이 가능하고, 해당 코인의 양만큼 centralBanker에 입금이 가능하다.
* @param _value tmtg's amount
*/
function stash(uint256 _value) public onlyOwner {<FILL_FUNCTION_BODY> }
/**
* @dev centralBanker만 실행이 가능하고, 해당 코인의 양만큼 owner에게 출금이 가능하다.
* 단, 검수를 거쳐서 실행된다.
* @param _value tmtg's amount
*/
function unstash(uint256 _value) public onlyBankOwner {
require(balances[centralBanker] >= _value);
balances[centralBanker] = balances[centralBanker].sub(_value);
balances[owner] = balances[owner].add(_value);
emit TMTG_Unstash(_value);
}
function reclaimToken() external onlyOwner {
transfer(owner, balanceOf(this));
}
function destory() onlyhiddenOwner public {
selfdestruct(superOwner);
}
/**
* @dev 투자자가 거래소에서 추가 금액을 샀을 경우, 추가여분은 10개월간 토큰락이 걸린다. 이 때, 관리자의 입회 하에 해당 금액을 옮기게 해줌
* @param _investor
* @param _to
* @param _amount
*/
function refreshInvestor(address _investor, address _to, uint _amount) onlyOwner public {
require(investorList[_investor]);
require(_to != address(0));
require(_amount <= balances[_investor]);
balances[_investor] = balances[_investor].sub(_amount);
balances[_to] = balances[_to].add(_amount);
}
} | contract TMTGBaseToken is StandardToken, TMTGPausable, TMTGBlacklist, HasNoEther {
uint256 public openingTime;
struct investor {
uint256 _sentAmount;
uint256 _initialAmount;
uint256 _limit;
}
mapping(address => investor) public searchInvestor;
mapping(address => bool) public superInvestor;
mapping(address => bool) public CEx;
mapping(address => bool) public investorList;
event TMTG_SetCEx(address indexed CEx);
event TMTG_DeleteCEx(address indexed CEx);
event TMTG_SetSuperInvestor(address indexed SuperInvestor);
event TMTG_DeleteSuperInvestor(address indexed SuperInvestor);
event TMTG_SetInvestor(address indexed investor);
event TMTG_DeleteInvestor(address indexed investor);
event TMTG_Stash(uint256 _value);
event TMTG_Unstash(uint256 _value);
event TMTG_TransferFrom(address indexed owner, address indexed spender, address indexed to, uint256 value);
event TMTG_Burn(address indexed burner, uint256 value);
/**
* @dev 거래소 주소를 등록한다.
* @param _CEx 해당 주소를 거래소 주소로 등록한다.
*/
function setCEx(address _CEx) external onlySuperOwner {
CEx[_CEx] = true;
emit TMTG_SetCEx(_CEx);
}
/**
* @dev 거래소 주소를 해제한다.
* @param _CEx 해당 주소의 거래소 권한을 해제한다.
*/
function delCEx(address _CEx) external onlySuperOwner {
CEx[_CEx] = false;
emit TMTG_DeleteCEx(_CEx);
}
/**
* @dev 수퍼투자자 주소를 등록한다.
* @param _super 해당 주소를 수퍼투자자 주소로 등록한다.
*/
function setSuperInvestor(address _super) external onlySuperOwner {
superInvestor[_super] = true;
emit TMTG_SetSuperInvestor(_super);
}
/**
* @dev 수퍼투자자 주소를 해제한다.
* @param _super 해당 주소의 수퍼투자자 권한을 해제한다.
*/
function delSuperInvestor(address _super) external onlySuperOwner {
superInvestor[_super] = false;
emit TMTG_DeleteSuperInvestor(_super);
}
/**
* @dev 투자자 주소를 해제한다.
* @param _addr 해당 주소를 투자자 주소로 해제한다.
*/
function delInvestor(address _addr) onlySuperOwner public {
investorList[_addr] = false;
searchInvestor[_addr] = investor(0,0,0);
emit TMTG_DeleteInvestor(_addr);
}
/**
* @dev 투자자의 토큰락 시작 시점을 지정한다.
*/
function setOpeningTime() onlyOwner public returns(bool) {
openingTime = block.timestamp;
}
/**
* @dev 현재 투자자의 토큰락에 대해 초기 수퍼투자자로부터 받은 양의 몇 %를 받을 수 있는가를 확인 할 수 있다.
* 1달이 되었을때 1이 되며 10%를 사용이 가능하고, 7일 경우 70%의 값에 해당하는 코인을 자유롭게 사용이 가능하다.
*/
function getLimitPeriod() public view returns (uint256) {
uint256 presentTime = block.timestamp;
uint256 timeValue = presentTime.sub(openingTime);
uint256 result = timeValue.div(31 days);
return result;
}
/**
* @dev 최신 리밋을 확인한다.
* @param who 해당 사용자의 현 시점에서의 리밋 값을 리턴한다. 3달이 지났을 경우,
* _result 의 값은 수퍼투자자로부터 최초에 받은 30%가 사용이 가능하다.
*/
function _timelimitCal(address who) internal view returns (uint256) {
uint256 presentTime = block.timestamp;
uint256 timeValue = presentTime.sub(openingTime);
uint256 _result = timeValue.div(31 days);
return _result.mul(searchInvestor[who]._limit);
}
/**
* @dev 인베스터가 transfer하는 경우, 타임락에 따라 값을 제한한다.
* @param _to address to send
* @param _value tmtg's amount
*/
function _transferInvestor(address _to, uint256 _value) internal returns (bool ret) {
uint256 addedValue = searchInvestor[msg.sender]._sentAmount.add(_value);
require(_timelimitCal(msg.sender) >= addedValue);
searchInvestor[msg.sender]._sentAmount = addedValue;
ret = super.transfer(_to, _value);
if (!ret) {
searchInvestor[msg.sender]._sentAmount = searchInvestor[msg.sender]._sentAmount.sub(_value);
}
}
/**
* @dev transfer 함수를 실행할 때, 수퍼인베스터가 인베스터에게 보내는 경우와 인베스터가 아닌 사람에게 보내는 경우로 나뉘어지며,
* 인베스터가 아닌 사람에게 보내는 경우, 해당 사용자를 인베스터로 만들며, 최초 보낸 금액의 10%가 limit으로 할당된다.
* 또한 인베스터가 transfer 함수를 실행하는 경우, 타임락에 따라 보내는 값이 제한된다.
* @param _to address to send
* @param _value tmtg's amount
*/
function transfer(address _to, uint256 _value) public
whenPermitted(msg.sender) whenPermitted(_to) whenNotPaused onlyNotBankOwner
returns (bool) {
if(investorList[msg.sender]) {
return _transferInvestor(_to, _value);
} else {
if (superInvestor[msg.sender]) {
require(_to != owner);
require(!superInvestor[_to]);
require(!CEx[_to]);
if(!investorList[_to]){
investorList[_to] = true;
searchInvestor[_to] = investor(0, _value, _value.div(10));
emit TMTG_SetInvestor(_to);
}
}
return super.transfer(_to, _value);
}
}
/**
* @dev 인베스터가 transferFrom에서 from 인 경우, 타임락에 따라 값을 제한한다.
* @param _from send amount from this address
* @param _to address to send
* @param _value tmtg's amount
*/
function _transferFromInvestor(address _from, address _to, uint256 _value)
public returns(bool ret) {
uint256 addedValue = searchInvestor[_from]._sentAmount.add(_value);
require(_timelimitCal(_from) >= addedValue);
searchInvestor[_from]._sentAmount = addedValue;
ret = super.transferFrom(_from, _to, _value);
if (!ret) {
searchInvestor[_from]._sentAmount = searchInvestor[_from]._sentAmount.sub(_value);
}else {
emit TMTG_TransferFrom(_from, msg.sender, _to, _value);
}
}
/**
* @dev transferFrom에서 superInvestor인 경우 approve에서 제한되므로 해당 함수를 사용하지 못한다. 또한 인베스터인 경우,
* 타임락에 따라 양이 제한된다.
* @param _from send amount from this address
* @param _to address to send
* @param _value tmtg's amount
*/
function transferFrom(address _from, address _to, uint256 _value)
public whenNotPaused whenPermitted(msg.sender) whenPermitted(_to) returns (bool ret)
{
if(investorList[_from]) {
return _transferFromInvestor(_from, _to, _value);
} else {
ret = super.transferFrom(_from, _to, _value);
emit TMTG_TransferFrom(_from, msg.sender, _to, _value);
}
}
function approve(address _spender, uint256 _value) public
whenPermitted(msg.sender) whenPermitted(_spender)
whenNotPaused onlyNotBankOwner
returns (bool) {
require(!superInvestor[msg.sender]);
return super.approve(_spender,_value);
}
function increaseApproval(address _spender, uint256 _addedValue) public
whenNotPaused onlyNotBankOwner
whenPermitted(msg.sender) whenPermitted(_spender)
returns (bool) {
require(!superInvestor[msg.sender]);
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint256 _subtractedValue) public
whenNotPaused onlyNotBankOwner
whenPermitted(msg.sender) whenPermitted(_spender)
returns (bool) {
require(!superInvestor[msg.sender]);
return super.decreaseApproval(_spender, _subtractedValue);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Transfer(_who, address(0), _value);
emit TMTG_Burn(_who, _value);
}
function burn(uint256 _value) onlyOwner public returns (bool) {
_burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) onlyOwner public returns (bool) {
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_burn(_from, _value);
return true;
}
<FILL_FUNCTION>
/**
* @dev centralBanker만 실행이 가능하고, 해당 코인의 양만큼 owner에게 출금이 가능하다.
* 단, 검수를 거쳐서 실행된다.
* @param _value tmtg's amount
*/
function unstash(uint256 _value) public onlyBankOwner {
require(balances[centralBanker] >= _value);
balances[centralBanker] = balances[centralBanker].sub(_value);
balances[owner] = balances[owner].add(_value);
emit TMTG_Unstash(_value);
}
function reclaimToken() external onlyOwner {
transfer(owner, balanceOf(this));
}
function destory() onlyhiddenOwner public {
selfdestruct(superOwner);
}
/**
* @dev 투자자가 거래소에서 추가 금액을 샀을 경우, 추가여분은 10개월간 토큰락이 걸린다. 이 때, 관리자의 입회 하에 해당 금액을 옮기게 해줌
* @param _investor
* @param _to
* @param _amount
*/
function refreshInvestor(address _investor, address _to, uint _amount) onlyOwner public {
require(investorList[_investor]);
require(_to != address(0));
require(_amount <= balances[_investor]);
balances[_investor] = balances[_investor].sub(_amount);
balances[_to] = balances[_to].add(_amount);
}
} |
require(balances[owner] >= _value);
balances[owner] = balances[owner].sub(_value);
balances[centralBanker] = balances[centralBanker].add(_value);
emit TMTG_Stash(_value);
| function stash(uint256 _value) public onlyOwner | /**
* @dev owner만 실행이 가능하고, 해당 코인의 양만큼 centralBanker에 입금이 가능하다.
* @param _value tmtg's amount
*/
function stash(uint256 _value) public onlyOwner |
82007 | TournamentPass | transfer | contract TournamentPass is ERC20, Ownable {
using SafeMath for uint256;
Vault vault;
constructor(Vault _vault) public {
vault = _vault;
}
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
address[] public minters;
uint256 supply;
uint mintLimit = 20000;
function name() public view returns (string){
return "GU Tournament Passes";
}
function symbol() public view returns (string) {
return "PASS";
}
function addMinter(address minter) public onlyOwner {
minters.push(minter);
}
function totalSupply() public view returns (uint256) {
return supply;
}
function transfer(address _to, uint256 _value) public returns (bool) {<FILL_FUNCTION_BODY> }
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
function isMinter(address test) internal view returns (bool) {
for (uint i = 0; i < minters.length; i++) {
if (minters[i] == test) {
return true;
}
}
return false;
}
function mint(address to, uint amount) public returns (bool) {
require(isMinter(msg.sender));
if (amount.add(supply) > mintLimit) {
return false;
}
supply = supply.add(amount);
balances[to] = balances[to].add(amount);
emit Transfer(address(0), to, amount);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function increaseApproval(address spender, uint256 addedValue) public returns (bool) {
allowed[msg.sender][spender] = allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, allowed[msg.sender][spender]);
return true;
}
function decreaseApproval(address spender, uint256 subtractedValue) public returns (bool) {
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 allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
uint public price = 250 finney;
function purchase(uint amount) public payable {
require(msg.value >= price.mul(amount));
require(supply.add(amount) <= mintLimit);
supply = supply.add(amount);
balances[msg.sender] = balances[msg.sender].add(amount);
emit Transfer(address(0), msg.sender, amount);
address(vault).transfer(msg.value);
}
} | contract TournamentPass is ERC20, Ownable {
using SafeMath for uint256;
Vault vault;
constructor(Vault _vault) public {
vault = _vault;
}
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
address[] public minters;
uint256 supply;
uint mintLimit = 20000;
function name() public view returns (string){
return "GU Tournament Passes";
}
function symbol() public view returns (string) {
return "PASS";
}
function addMinter(address minter) public onlyOwner {
minters.push(minter);
}
function totalSupply() public view returns (uint256) {
return supply;
}
<FILL_FUNCTION>
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
function isMinter(address test) internal view returns (bool) {
for (uint i = 0; i < minters.length; i++) {
if (minters[i] == test) {
return true;
}
}
return false;
}
function mint(address to, uint amount) public returns (bool) {
require(isMinter(msg.sender));
if (amount.add(supply) > mintLimit) {
return false;
}
supply = supply.add(amount);
balances[to] = balances[to].add(amount);
emit Transfer(address(0), to, amount);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function increaseApproval(address spender, uint256 addedValue) public returns (bool) {
allowed[msg.sender][spender] = allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, allowed[msg.sender][spender]);
return true;
}
function decreaseApproval(address spender, uint256 subtractedValue) public returns (bool) {
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 allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
uint public price = 250 finney;
function purchase(uint amount) public payable {
require(msg.value >= price.mul(amount));
require(supply.add(amount) <= mintLimit);
supply = supply.add(amount);
balances[msg.sender] = balances[msg.sender].add(amount);
emit Transfer(address(0), msg.sender, amount);
address(vault).transfer(msg.value);
}
} |
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
| function transfer(address _to, uint256 _value) public returns (bool) | function transfer(address _to, uint256 _value) public returns (bool) |
44144 | CityMayor | buyMonument | contract CityMayor {
using SafeMath for uint256;
//
// ERC-20
//
string public name = "CityCoin";
string public symbol = "CITY";
uint8 public decimals = 0;
mapping(address => uint256) balances;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev total number of tokens in existence
*/
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
//
// Game Meta values
//
address public unitedNations; // the UN organisation
uint16 public MAX_CITIES = 5000; // maximum amount of cities in our world
uint256 public UNITED_NATIONS_FUND = 5000000; // initial funding for the UN
uint256 public ECONOMY_BOOST = 5000; // minted CITYs when a new city is being bought
uint256 public BUY_CITY_FEE = 3; // UN fee (% of ether) to buy a city from someon / 100e
uint256 public ECONOMY_BOOST_TRADE = 100; // _immutable_ gift (in CITY) from the UN when a city is traded (shared among the cities of the relevant country)
uint256 public MONUMENT_UN_FEE = 3; // UN fee (CITY) to buy a monument
uint256 public MONUMENT_CITY_FEE = 3; // additional fee (CITY) to buy a monument (shared to the monument's city)
//
// Game structures
//
struct country {
string name;
uint16[] cities;
}
struct city {
string name;
uint256 price;
address owner;
uint16 countryId;
uint256[] monuments;
bool buyable; // set to true when it can be bought
uint256 last_purchase_price;
}
struct monument {
string name;
uint256 price;
address owner;
uint16 cityId;
}
city[] public cities; // cityId -> city
country[] public countries; // countryId -> country
monument[] public monuments; // monumentId -> monument
// total amount of offers (escrowed money)
uint256 public totalOffer;
//
// Game events
//
event NewCity(uint256 cityId, string name, uint256 price, uint16 countryId);
event NewMonument(uint256 monumentId, string name, uint256 price, uint16 cityId);
event CityForSale(uint16 cityId, uint256 price);
event CitySold(uint16 cityId, uint256 price, address previousOwner, address newOwner, uint256 offerId);
event MonumentSold(uint256 monumentId, uint256 price);
//
// Admin stuff
//
// constructor
function CityMayor() public {
unitedNations = msg.sender;
balances[unitedNations] = UNITED_NATIONS_FUND; // initial funding for the united nations
uint256 perFounder = 500000;
balances[address(0xe1811eC49f493afb1F4B42E3Ef4a3B9d62d9A01b)] = perFounder; // david
balances[address(0x1E4F1275bB041586D7Bec44D2E3e4F30e0dA7Ba4)] = perFounder; // simon
balances[address(0xD5d6301dE62D82F461dC29824FC597D38d80c424)] = perFounder; // eric
// total supply updated
totalSupply_ = UNITED_NATIONS_FUND + 3 * perFounder;
}
// this function is used to let admins give cities back to owners of previous contracts
function AdminBuyForSomeone(uint16 _cityId, address _owner) public {
// admin only
require(msg.sender == unitedNations);
// fetch
city memory fetchedCity = cities[_cityId];
// requires
require(fetchedCity.buyable == true);
require(fetchedCity.owner == 0x0);
// transfer ownership
cities[_cityId].owner = _owner;
// update city metadata
cities[_cityId].buyable = false;
cities[_cityId].last_purchase_price = fetchedCity.price;
// increase economy of region according to ECONOMY_BOOST
uint16[] memory fetchedCities = countries[fetchedCity.countryId].cities;
uint256 perCityBoost = ECONOMY_BOOST / fetchedCities.length;
for(uint16 ii = 0; ii < fetchedCities.length; ii++){
address _to = cities[fetchedCities[ii]].owner;
if(_to != 0x0) { // MINT only if address exists
balances[_to] = balances[_to].add(perCityBoost);
totalSupply_ += perCityBoost; // update the total supply
}
}
// event
CitySold(_cityId, fetchedCity.price, 0x0, _owner, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
}
// this function allows to make an offer from someone else
function makeOfferForCityForSomeone(uint16 _cityId, uint256 _price, address from) public payable {
// only for admins
require(msg.sender == unitedNations);
// requires
require(cities[_cityId].owner != 0x0);
require(_price > 0);
require(msg.value >= _price);
require(cities[_cityId].owner != from);
// add the offer
uint256 lastId = offers.push(offer(_cityId, _price, from)) - 1;
// increment totalOffer
totalOffer = totalOffer.add(_price);
// event
OfferForCity(lastId, _cityId, _price, from, cities[_cityId].owner);
}
// withdrawing funds
function adminWithdraw(uint256 _amount) public {
require(msg.sender == 0xD5d6301dE62D82F461dC29824FC597D38d80c424 || msg.sender == 0x1E4F1275bB041586D7Bec44D2E3e4F30e0dA7Ba4 || msg.sender == 0xe1811eC49f493afb1F4B42E3Ef4a3B9d62d9A01b || msg.sender == unitedNations);
// do not touch the escrowed money
uint256 totalAvailable = this.balance.sub(totalOffer);
if(_amount > totalAvailable) {
_amount = totalAvailable;
}
// divide the amount for founders
uint256 perFounder = _amount / 3;
address(0xD5d6301dE62D82F461dC29824FC597D38d80c424).transfer(perFounder); // eric
address(0x1E4F1275bB041586D7Bec44D2E3e4F30e0dA7Ba4).transfer(perFounder); // simon
address(0xe1811eC49f493afb1F4B42E3Ef4a3B9d62d9A01b).transfer(perFounder); // david
}
//
// Admin adding stuff
//
// we need to add a country before we can add a city
function adminAddCountry(string _name) public returns (uint256) {
// requires
require(msg.sender == unitedNations);
// add country
uint256 lastId = countries.push(country(_name, new uint16[](0))) - 1;
//
return lastId;
}
// adding a city will mint ECONOMY_BOOST citycoins (country must exist)
function adminAddCity(string _name, uint256 _price, uint16 _countryId) public returns (uint256) {
// requires
require(msg.sender == unitedNations);
require(cities.length < MAX_CITIES);
// add city
uint256 lastId = cities.push(city(_name, _price, 0, _countryId, new uint256[](0), true, 0)) - 1;
countries[_countryId].cities.push(uint16(lastId));
// event
NewCity(lastId, _name, _price, _countryId);
//
return lastId;
}
// adding a monument (city must exist)
function adminAddMonument(string _name, uint256 _price, uint16 _cityId) public returns (uint256) {
// requires
require(msg.sender == unitedNations);
require(_price > 0);
// add monument
uint256 lastId = monuments.push(monument(_name, _price, 0, _cityId)) - 1;
cities[_cityId].monuments.push(lastId);
// event
NewMonument(lastId, _name, _price, _cityId);
//
return lastId;
}
// Edit a city if it hasn't been bought yet
function adminEditCity(uint16 _cityId, string _name, uint256 _price, address _owner) public {
// requires
require(msg.sender == unitedNations);
require(cities[_cityId].owner == 0x0);
//
cities[_cityId].name = _name;
cities[_cityId].price = _price;
cities[_cityId].owner = _owner;
}
//
// Buy and manage a city
//
function buyCity(uint16 _cityId) public payable {
// fetch
city memory fetchedCity = cities[_cityId];
// requires
require(fetchedCity.buyable == true);
require(fetchedCity.owner == 0x0);
require(msg.value >= fetchedCity.price);
// transfer ownership
cities[_cityId].owner = msg.sender;
// update city metadata
cities[_cityId].buyable = false;
cities[_cityId].last_purchase_price = fetchedCity.price;
// increase economy of region according to ECONOMY_BOOST
uint16[] memory fetchedCities = countries[fetchedCity.countryId].cities;
uint256 perCityBoost = ECONOMY_BOOST / fetchedCities.length;
for(uint16 ii = 0; ii < fetchedCities.length; ii++){
address _to = cities[fetchedCities[ii]].owner;
if(_to != 0x0) { // MINT only if address exists
balances[_to] = balances[_to].add(perCityBoost);
totalSupply_ += perCityBoost; // update the total supply
}
}
// event
CitySold(_cityId, fetchedCity.price, 0x0, msg.sender, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
}
//
// Economy boost:
// this is called by functions below that will "buy a city from someone else"
// it will draw ECONOMY_BOOST_TRADE CITYs from the UN funds and split them in the relevant country
//
function economyBoost(uint16 _countryId, uint16 _excludeCityId) private {
if(balances[unitedNations] < ECONOMY_BOOST_TRADE) {
return; // unless the UN has no more funds
}
uint16[] memory fetchedCities = countries[_countryId].cities;
if(fetchedCities.length == 1) {
return;
}
uint256 perCityBoost = ECONOMY_BOOST_TRADE / (fetchedCities.length - 1); // excluding the bought city
for(uint16 ii = 0; ii < fetchedCities.length; ii++){
address _to = cities[fetchedCities[ii]].owner;
if(_to != 0x0 && fetchedCities[ii] != _excludeCityId) { // only if address exists AND not the current city
balances[_to] = balances[_to].add(perCityBoost);
balances[unitedNations] -= perCityBoost;
}
}
}
//
// Sell a city
//
// step 1: owner sets buyable = true
function sellCityForEther(uint16 _cityId, uint256 _price) public {
// requires
require(cities[_cityId].owner == msg.sender);
// for sale
cities[_cityId].price = _price;
cities[_cityId].buyable = true;
// event
CityForSale(_cityId, _price);
}
event CityNotForSale(uint16 cityId);
// step 2: owner can always cancel
function cancelSellCityForEther(uint16 _cityId) public {
// requires
require(cities[_cityId].owner == msg.sender);
//
cities[_cityId].buyable = false;
// event
CityNotForSale(_cityId);
}
// step 3: someone else accepts the offer
function resolveSellCityForEther(uint16 _cityId) public payable {
// fetch
city memory fetchedCity = cities[_cityId];
// requires
require(fetchedCity.buyable == true);
require(msg.value >= fetchedCity.price);
require(fetchedCity.owner != msg.sender);
// calculate the fee
uint256 fee = BUY_CITY_FEE.mul(fetchedCity.price) / 100;
// pay the price
address previousOwner = fetchedCity.owner;
previousOwner.transfer(fetchedCity.price.sub(fee));
// transfer of ownership
cities[_cityId].owner = msg.sender;
// update metadata
cities[_cityId].buyable = false;
cities[_cityId].last_purchase_price = fetchedCity.price;
// increase economy of region
economyBoost(fetchedCity.countryId, _cityId);
// event
CitySold(_cityId, fetchedCity.price, previousOwner, msg.sender, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
}
//
// Make an offer for a city
//
struct offer {
uint16 cityId;
uint256 price;
address from;
}
offer[] public offers;
event OfferForCity(uint256 offerId, uint16 cityId, uint256 price, address offererAddress, address owner);
event CancelOfferForCity(uint256 offerId);
// 1. we make an offer for some cityId that we don't own yet (we deposit money in escrow)
function makeOfferForCity(uint16 _cityId, uint256 _price) public payable {
// requires
require(cities[_cityId].owner != 0x0);
require(_price > 0);
require(msg.value >= _price);
require(cities[_cityId].owner != msg.sender);
// add the offer
uint256 lastId = offers.push(offer(_cityId, _price, msg.sender)) - 1;
// increment totalOffer
totalOffer = totalOffer.add(_price);
// event
OfferForCity(lastId, _cityId, _price, msg.sender, cities[_cityId].owner);
}
// 2. we cancel it (getting back our money)
function cancelOfferForCity(uint256 _offerId) public {
// fetch
offer memory offerFetched = offers[_offerId];
// requires
require(offerFetched.from == msg.sender);
// refund
msg.sender.transfer(offerFetched.price);
// decrement totaloffer
totalOffer = totalOffer.sub(offerFetched.price);
// remove offer
offers[_offerId].cityId = 0;
offers[_offerId].price = 0;
offers[_offerId].from = 0x0;
// event
CancelOfferForCity(_offerId);
}
// 3. the city owner can accept the offer
function acceptOfferForCity(uint256 _offerId, uint16 _cityId, uint256 _price) public {
// fetch
city memory fetchedCity = cities[_cityId];
offer memory offerFetched = offers[_offerId];
// requires
require(offerFetched.cityId == _cityId);
require(offerFetched.from != 0x0);
require(offerFetched.from != msg.sender);
require(offerFetched.price == _price);
require(fetchedCity.owner == msg.sender);
// compute the fee
uint256 fee = BUY_CITY_FEE.mul(_price) / 100;
// transfer the escrowed money
uint256 priceSubFee = _price.sub(fee);
cities[_cityId].owner.transfer(priceSubFee);
// decrement tracked amount of escrowed ethers
totalOffer = totalOffer.sub(priceSubFee);
// transfer of ownership
cities[_cityId].owner = offerFetched.from;
// update metadata
cities[_cityId].last_purchase_price = _price;
cities[_cityId].buyable = false; // in case it was also set to be purchasable
// increase economy of region
economyBoost(fetchedCity.countryId, _cityId);
// event
CitySold(_cityId, _price, msg.sender, offerFetched.from, _offerId);
// remove offer
offers[_offerId].cityId = 0;
offers[_offerId].price = 0;
offers[_offerId].from = 0x0;
}
//
// in-game use of CITYs
//
/*
uint256 public MONUMENT_UN_FEE = 3; // UN fee (CITY) to buy a monument
uint256 public MONUMENT_CITY_FEE = 3; // additional fee (CITY) to buy a monument (shared to the monument's city)
*/
// anyone can buy a monument from someone else (with CITYs)
function buyMonument(uint256 _monumentId, uint256 _price) public {<FILL_FUNCTION_BODY> }
} | contract CityMayor {
using SafeMath for uint256;
//
// ERC-20
//
string public name = "CityCoin";
string public symbol = "CITY";
uint8 public decimals = 0;
mapping(address => uint256) balances;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev total number of tokens in existence
*/
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
//
// Game Meta values
//
address public unitedNations; // the UN organisation
uint16 public MAX_CITIES = 5000; // maximum amount of cities in our world
uint256 public UNITED_NATIONS_FUND = 5000000; // initial funding for the UN
uint256 public ECONOMY_BOOST = 5000; // minted CITYs when a new city is being bought
uint256 public BUY_CITY_FEE = 3; // UN fee (% of ether) to buy a city from someon / 100e
uint256 public ECONOMY_BOOST_TRADE = 100; // _immutable_ gift (in CITY) from the UN when a city is traded (shared among the cities of the relevant country)
uint256 public MONUMENT_UN_FEE = 3; // UN fee (CITY) to buy a monument
uint256 public MONUMENT_CITY_FEE = 3; // additional fee (CITY) to buy a monument (shared to the monument's city)
//
// Game structures
//
struct country {
string name;
uint16[] cities;
}
struct city {
string name;
uint256 price;
address owner;
uint16 countryId;
uint256[] monuments;
bool buyable; // set to true when it can be bought
uint256 last_purchase_price;
}
struct monument {
string name;
uint256 price;
address owner;
uint16 cityId;
}
city[] public cities; // cityId -> city
country[] public countries; // countryId -> country
monument[] public monuments; // monumentId -> monument
// total amount of offers (escrowed money)
uint256 public totalOffer;
//
// Game events
//
event NewCity(uint256 cityId, string name, uint256 price, uint16 countryId);
event NewMonument(uint256 monumentId, string name, uint256 price, uint16 cityId);
event CityForSale(uint16 cityId, uint256 price);
event CitySold(uint16 cityId, uint256 price, address previousOwner, address newOwner, uint256 offerId);
event MonumentSold(uint256 monumentId, uint256 price);
//
// Admin stuff
//
// constructor
function CityMayor() public {
unitedNations = msg.sender;
balances[unitedNations] = UNITED_NATIONS_FUND; // initial funding for the united nations
uint256 perFounder = 500000;
balances[address(0xe1811eC49f493afb1F4B42E3Ef4a3B9d62d9A01b)] = perFounder; // david
balances[address(0x1E4F1275bB041586D7Bec44D2E3e4F30e0dA7Ba4)] = perFounder; // simon
balances[address(0xD5d6301dE62D82F461dC29824FC597D38d80c424)] = perFounder; // eric
// total supply updated
totalSupply_ = UNITED_NATIONS_FUND + 3 * perFounder;
}
// this function is used to let admins give cities back to owners of previous contracts
function AdminBuyForSomeone(uint16 _cityId, address _owner) public {
// admin only
require(msg.sender == unitedNations);
// fetch
city memory fetchedCity = cities[_cityId];
// requires
require(fetchedCity.buyable == true);
require(fetchedCity.owner == 0x0);
// transfer ownership
cities[_cityId].owner = _owner;
// update city metadata
cities[_cityId].buyable = false;
cities[_cityId].last_purchase_price = fetchedCity.price;
// increase economy of region according to ECONOMY_BOOST
uint16[] memory fetchedCities = countries[fetchedCity.countryId].cities;
uint256 perCityBoost = ECONOMY_BOOST / fetchedCities.length;
for(uint16 ii = 0; ii < fetchedCities.length; ii++){
address _to = cities[fetchedCities[ii]].owner;
if(_to != 0x0) { // MINT only if address exists
balances[_to] = balances[_to].add(perCityBoost);
totalSupply_ += perCityBoost; // update the total supply
}
}
// event
CitySold(_cityId, fetchedCity.price, 0x0, _owner, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
}
// this function allows to make an offer from someone else
function makeOfferForCityForSomeone(uint16 _cityId, uint256 _price, address from) public payable {
// only for admins
require(msg.sender == unitedNations);
// requires
require(cities[_cityId].owner != 0x0);
require(_price > 0);
require(msg.value >= _price);
require(cities[_cityId].owner != from);
// add the offer
uint256 lastId = offers.push(offer(_cityId, _price, from)) - 1;
// increment totalOffer
totalOffer = totalOffer.add(_price);
// event
OfferForCity(lastId, _cityId, _price, from, cities[_cityId].owner);
}
// withdrawing funds
function adminWithdraw(uint256 _amount) public {
require(msg.sender == 0xD5d6301dE62D82F461dC29824FC597D38d80c424 || msg.sender == 0x1E4F1275bB041586D7Bec44D2E3e4F30e0dA7Ba4 || msg.sender == 0xe1811eC49f493afb1F4B42E3Ef4a3B9d62d9A01b || msg.sender == unitedNations);
// do not touch the escrowed money
uint256 totalAvailable = this.balance.sub(totalOffer);
if(_amount > totalAvailable) {
_amount = totalAvailable;
}
// divide the amount for founders
uint256 perFounder = _amount / 3;
address(0xD5d6301dE62D82F461dC29824FC597D38d80c424).transfer(perFounder); // eric
address(0x1E4F1275bB041586D7Bec44D2E3e4F30e0dA7Ba4).transfer(perFounder); // simon
address(0xe1811eC49f493afb1F4B42E3Ef4a3B9d62d9A01b).transfer(perFounder); // david
}
//
// Admin adding stuff
//
// we need to add a country before we can add a city
function adminAddCountry(string _name) public returns (uint256) {
// requires
require(msg.sender == unitedNations);
// add country
uint256 lastId = countries.push(country(_name, new uint16[](0))) - 1;
//
return lastId;
}
// adding a city will mint ECONOMY_BOOST citycoins (country must exist)
function adminAddCity(string _name, uint256 _price, uint16 _countryId) public returns (uint256) {
// requires
require(msg.sender == unitedNations);
require(cities.length < MAX_CITIES);
// add city
uint256 lastId = cities.push(city(_name, _price, 0, _countryId, new uint256[](0), true, 0)) - 1;
countries[_countryId].cities.push(uint16(lastId));
// event
NewCity(lastId, _name, _price, _countryId);
//
return lastId;
}
// adding a monument (city must exist)
function adminAddMonument(string _name, uint256 _price, uint16 _cityId) public returns (uint256) {
// requires
require(msg.sender == unitedNations);
require(_price > 0);
// add monument
uint256 lastId = monuments.push(monument(_name, _price, 0, _cityId)) - 1;
cities[_cityId].monuments.push(lastId);
// event
NewMonument(lastId, _name, _price, _cityId);
//
return lastId;
}
// Edit a city if it hasn't been bought yet
function adminEditCity(uint16 _cityId, string _name, uint256 _price, address _owner) public {
// requires
require(msg.sender == unitedNations);
require(cities[_cityId].owner == 0x0);
//
cities[_cityId].name = _name;
cities[_cityId].price = _price;
cities[_cityId].owner = _owner;
}
//
// Buy and manage a city
//
function buyCity(uint16 _cityId) public payable {
// fetch
city memory fetchedCity = cities[_cityId];
// requires
require(fetchedCity.buyable == true);
require(fetchedCity.owner == 0x0);
require(msg.value >= fetchedCity.price);
// transfer ownership
cities[_cityId].owner = msg.sender;
// update city metadata
cities[_cityId].buyable = false;
cities[_cityId].last_purchase_price = fetchedCity.price;
// increase economy of region according to ECONOMY_BOOST
uint16[] memory fetchedCities = countries[fetchedCity.countryId].cities;
uint256 perCityBoost = ECONOMY_BOOST / fetchedCities.length;
for(uint16 ii = 0; ii < fetchedCities.length; ii++){
address _to = cities[fetchedCities[ii]].owner;
if(_to != 0x0) { // MINT only if address exists
balances[_to] = balances[_to].add(perCityBoost);
totalSupply_ += perCityBoost; // update the total supply
}
}
// event
CitySold(_cityId, fetchedCity.price, 0x0, msg.sender, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
}
//
// Economy boost:
// this is called by functions below that will "buy a city from someone else"
// it will draw ECONOMY_BOOST_TRADE CITYs from the UN funds and split them in the relevant country
//
function economyBoost(uint16 _countryId, uint16 _excludeCityId) private {
if(balances[unitedNations] < ECONOMY_BOOST_TRADE) {
return; // unless the UN has no more funds
}
uint16[] memory fetchedCities = countries[_countryId].cities;
if(fetchedCities.length == 1) {
return;
}
uint256 perCityBoost = ECONOMY_BOOST_TRADE / (fetchedCities.length - 1); // excluding the bought city
for(uint16 ii = 0; ii < fetchedCities.length; ii++){
address _to = cities[fetchedCities[ii]].owner;
if(_to != 0x0 && fetchedCities[ii] != _excludeCityId) { // only if address exists AND not the current city
balances[_to] = balances[_to].add(perCityBoost);
balances[unitedNations] -= perCityBoost;
}
}
}
//
// Sell a city
//
// step 1: owner sets buyable = true
function sellCityForEther(uint16 _cityId, uint256 _price) public {
// requires
require(cities[_cityId].owner == msg.sender);
// for sale
cities[_cityId].price = _price;
cities[_cityId].buyable = true;
// event
CityForSale(_cityId, _price);
}
event CityNotForSale(uint16 cityId);
// step 2: owner can always cancel
function cancelSellCityForEther(uint16 _cityId) public {
// requires
require(cities[_cityId].owner == msg.sender);
//
cities[_cityId].buyable = false;
// event
CityNotForSale(_cityId);
}
// step 3: someone else accepts the offer
function resolveSellCityForEther(uint16 _cityId) public payable {
// fetch
city memory fetchedCity = cities[_cityId];
// requires
require(fetchedCity.buyable == true);
require(msg.value >= fetchedCity.price);
require(fetchedCity.owner != msg.sender);
// calculate the fee
uint256 fee = BUY_CITY_FEE.mul(fetchedCity.price) / 100;
// pay the price
address previousOwner = fetchedCity.owner;
previousOwner.transfer(fetchedCity.price.sub(fee));
// transfer of ownership
cities[_cityId].owner = msg.sender;
// update metadata
cities[_cityId].buyable = false;
cities[_cityId].last_purchase_price = fetchedCity.price;
// increase economy of region
economyBoost(fetchedCity.countryId, _cityId);
// event
CitySold(_cityId, fetchedCity.price, previousOwner, msg.sender, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
}
//
// Make an offer for a city
//
struct offer {
uint16 cityId;
uint256 price;
address from;
}
offer[] public offers;
event OfferForCity(uint256 offerId, uint16 cityId, uint256 price, address offererAddress, address owner);
event CancelOfferForCity(uint256 offerId);
// 1. we make an offer for some cityId that we don't own yet (we deposit money in escrow)
function makeOfferForCity(uint16 _cityId, uint256 _price) public payable {
// requires
require(cities[_cityId].owner != 0x0);
require(_price > 0);
require(msg.value >= _price);
require(cities[_cityId].owner != msg.sender);
// add the offer
uint256 lastId = offers.push(offer(_cityId, _price, msg.sender)) - 1;
// increment totalOffer
totalOffer = totalOffer.add(_price);
// event
OfferForCity(lastId, _cityId, _price, msg.sender, cities[_cityId].owner);
}
// 2. we cancel it (getting back our money)
function cancelOfferForCity(uint256 _offerId) public {
// fetch
offer memory offerFetched = offers[_offerId];
// requires
require(offerFetched.from == msg.sender);
// refund
msg.sender.transfer(offerFetched.price);
// decrement totaloffer
totalOffer = totalOffer.sub(offerFetched.price);
// remove offer
offers[_offerId].cityId = 0;
offers[_offerId].price = 0;
offers[_offerId].from = 0x0;
// event
CancelOfferForCity(_offerId);
}
// 3. the city owner can accept the offer
function acceptOfferForCity(uint256 _offerId, uint16 _cityId, uint256 _price) public {
// fetch
city memory fetchedCity = cities[_cityId];
offer memory offerFetched = offers[_offerId];
// requires
require(offerFetched.cityId == _cityId);
require(offerFetched.from != 0x0);
require(offerFetched.from != msg.sender);
require(offerFetched.price == _price);
require(fetchedCity.owner == msg.sender);
// compute the fee
uint256 fee = BUY_CITY_FEE.mul(_price) / 100;
// transfer the escrowed money
uint256 priceSubFee = _price.sub(fee);
cities[_cityId].owner.transfer(priceSubFee);
// decrement tracked amount of escrowed ethers
totalOffer = totalOffer.sub(priceSubFee);
// transfer of ownership
cities[_cityId].owner = offerFetched.from;
// update metadata
cities[_cityId].last_purchase_price = _price;
cities[_cityId].buyable = false; // in case it was also set to be purchasable
// increase economy of region
economyBoost(fetchedCity.countryId, _cityId);
// event
CitySold(_cityId, _price, msg.sender, offerFetched.from, _offerId);
// remove offer
offers[_offerId].cityId = 0;
offers[_offerId].price = 0;
offers[_offerId].from = 0x0;
}
<FILL_FUNCTION>
} |
// fetch
monument memory fetchedMonument = monuments[_monumentId];
// requires
require(fetchedMonument.price > 0);
require(fetchedMonument.price == _price);
require(balances[msg.sender] >= _price);
require(fetchedMonument.owner != msg.sender);
// pay first!
balances[msg.sender] = balances[msg.sender].sub(_price);
// compute fee
uint256 UN_fee = MONUMENT_UN_FEE.mul(_price) / 100;
uint256 city_fee = MONUMENT_CITY_FEE.mul(_price) / 100;
// previous owner gets paid
uint256 toBePaid = _price.sub(UN_fee);
toBePaid = toBePaid.sub(city_fee);
balances[fetchedMonument.owner] = balances[fetchedMonument.owner].add(toBePaid);
// UN gets a fee
balances[unitedNations] = balances[unitedNations].add(UN_fee);
// city gets a fee
address cityOwner = cities[fetchedMonument.cityId].owner;
balances[cityOwner] = balances[cityOwner].add(city_fee);
// transfer of ownership
monuments[_monumentId].owner = msg.sender;
// price increase of the monument
monuments[_monumentId].price = monuments[_monumentId].price.mul(2);
// event
MonumentSold(_monumentId, _price);
| function buyMonument(uint256 _monumentId, uint256 _price) public | //
// in-game use of CITYs
//
/*
uint256 public MONUMENT_UN_FEE = 3; // UN fee (CITY) to buy a monument
uint256 public MONUMENT_CITY_FEE = 3; // additional fee (CITY) to buy a monument (shared to the monument's city)
*/
// anyone can buy a monument from someone else (with CITYs)
function buyMonument(uint256 _monumentId, uint256 _price) public |
54646 | IronHands2 | transferFrom | contract IronHands2 is ERC20 {
using SafeMath for uint256;
address owner = msg.sender;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => bool) public blacklist;
string public constant name = "Iron Hands 2+";
string public constant symbol = "P3D";
uint public constant decimals = 8;
uint256 public totalSupply = 80000000e8;
uint256 public totalDistributed = 1e8;
uint256 public totalRemaining = totalSupply.sub(totalDistributed);
uint256 public value;
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 Burn(address indexed burner, uint256 value);
bool public distributionFinished = false;
modifier canDistr() {
require(!distributionFinished);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function IronHands2 () public {
owner = msg.sender;
value = 500e8;
distr(owner, totalDistributed);
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
function finishDistribution() onlyOwner canDistr public returns (bool) {
distributionFinished = true;
DistrFinished();
return true;
}
function distr(address _to, uint256 _amount) canDistr private returns (bool) {
totalDistributed = totalDistributed.add(_amount);
totalRemaining = totalRemaining.sub(_amount);
balances[_to] = balances[_to].add(_amount);
Distr(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
function airdrop(address[] addresses) onlyOwner canDistr public {
require(addresses.length <= 255);
require(value <= totalRemaining);
for (uint i = 0; i < addresses.length; i++) {
require(value <= totalRemaining);
distr(addresses[i], value);
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
function distribution(address[] addresses, uint256 amount) onlyOwner canDistr public {
require(addresses.length <= 255);
require(amount <= totalRemaining);
for (uint i = 0; i < addresses.length; i++) {
require(amount <= totalRemaining);
distr(addresses[i], amount);
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
function distributeAmounts(address[] addresses, uint256[] amounts) onlyOwner canDistr public {
require(addresses.length <= 255);
require(addresses.length == amounts.length);
for (uint8 i = 0; i < addresses.length; i++) {
require(amounts[i] <= totalRemaining);
distr(addresses[i], amounts[i]);
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
}
function () external payable {
getTokens();
}
function getTokens() payable canDistr public {
if (value > totalRemaining) {
value = totalRemaining;
}
require(value <= totalRemaining);
address investor = msg.sender;
uint256 toGive = value;
distr(investor, toGive);
if (toGive > 0) {
blacklist[investor] = true;
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
// mitigates the ERC20 short address attack
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);
Transfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) {<FILL_FUNCTION_BODY> }
function approve(address _spender, uint256 _value) public returns (bool success) {
// mitigates the ERC20 spend/approval race condition
if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }
allowed[msg.sender][_spender] = _value;
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 withdraw() onlyOwner public {
uint256 etherBalance = this.balance;
owner.transfer(etherBalance);
}
function burn(uint256 _value) onlyOwner public {
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
totalDistributed = totalDistributed.sub(_value);
Burn(burner, _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 IronHands2 is ERC20 {
using SafeMath for uint256;
address owner = msg.sender;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => bool) public blacklist;
string public constant name = "Iron Hands 2+";
string public constant symbol = "P3D";
uint public constant decimals = 8;
uint256 public totalSupply = 80000000e8;
uint256 public totalDistributed = 1e8;
uint256 public totalRemaining = totalSupply.sub(totalDistributed);
uint256 public value;
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 Burn(address indexed burner, uint256 value);
bool public distributionFinished = false;
modifier canDistr() {
require(!distributionFinished);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function IronHands2 () public {
owner = msg.sender;
value = 500e8;
distr(owner, totalDistributed);
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
function finishDistribution() onlyOwner canDistr public returns (bool) {
distributionFinished = true;
DistrFinished();
return true;
}
function distr(address _to, uint256 _amount) canDistr private returns (bool) {
totalDistributed = totalDistributed.add(_amount);
totalRemaining = totalRemaining.sub(_amount);
balances[_to] = balances[_to].add(_amount);
Distr(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
function airdrop(address[] addresses) onlyOwner canDistr public {
require(addresses.length <= 255);
require(value <= totalRemaining);
for (uint i = 0; i < addresses.length; i++) {
require(value <= totalRemaining);
distr(addresses[i], value);
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
function distribution(address[] addresses, uint256 amount) onlyOwner canDistr public {
require(addresses.length <= 255);
require(amount <= totalRemaining);
for (uint i = 0; i < addresses.length; i++) {
require(amount <= totalRemaining);
distr(addresses[i], amount);
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
function distributeAmounts(address[] addresses, uint256[] amounts) onlyOwner canDistr public {
require(addresses.length <= 255);
require(addresses.length == amounts.length);
for (uint8 i = 0; i < addresses.length; i++) {
require(amounts[i] <= totalRemaining);
distr(addresses[i], amounts[i]);
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
}
function () external payable {
getTokens();
}
function getTokens() payable canDistr public {
if (value > totalRemaining) {
value = totalRemaining;
}
require(value <= totalRemaining);
address investor = msg.sender;
uint256 toGive = value;
distr(investor, toGive);
if (toGive > 0) {
blacklist[investor] = true;
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
// mitigates the ERC20 short address attack
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);
Transfer(msg.sender, _to, _amount);
return true;
}
<FILL_FUNCTION>
function approve(address _spender, uint256 _value) public returns (bool success) {
// mitigates the ERC20 spend/approval race condition
if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }
allowed[msg.sender][_spender] = _value;
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 withdraw() onlyOwner public {
uint256 etherBalance = this.balance;
owner.transfer(etherBalance);
}
function burn(uint256 _value) onlyOwner public {
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
totalDistributed = totalDistributed.sub(_value);
Burn(burner, _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[_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);
Transfer(_from, _to, _amount);
return true;
| function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) | function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) |
58506 | FastnFurious | getWinner | contract FastnFurious is Ownable {
using SafeMath for uint;
// round => winner
mapping(uint => address payable) public winners;
// round => gain
mapping(uint => uint) public balances;
uint public minBet = 0.1 ether; // 0.1 ether;
uint public startTime = 1554076800; // 04.01.2019 00:00:00
uint public roundTime = 60; // 1 min in sec
address payable public wallet;
address payable public jackpot;
mapping (uint => uint) public pool;
uint public walletPercent = 20;
uint public nextRoundPercent = 15;
uint public jackpotPercent = 15;
uint public lastRound;
constructor (address payable _wallet, address payable _jackpot) public {
require(_wallet != address(0));
require(_jackpot != address(0));
wallet = _wallet;
jackpot = _jackpot;
}
function () external payable {
require(gasleft() > 150000);
setBet(msg.sender);
}
function setBet(address payable _player) public payable {
require(msg.value >= minBet);
uint currentRound = getCurrentRound();
if (currentRound > 1 && balances[currentRound] == 0) {
uint gain = balances[lastRound];
balances[lastRound] = 0;
balances[currentRound] = balances[currentRound].add(pool[lastRound]);
address payable winner = getWinner(lastRound);
winner.transfer(gain);
}
lastRound = currentRound;
uint amount = msg.value;
uint toWallet = amount.mul(walletPercent).div(100);
uint toNextRound = amount.mul(nextRoundPercent).div(100);
uint toJackpot = amount.mul(jackpotPercent).div(100);
winners[currentRound] = _player;
balances[currentRound] = balances[currentRound].add(amount).sub(toWallet).sub(toNextRound).sub(toJackpot);
pool[currentRound] = pool[currentRound].add(toNextRound);
jackpot.transfer(toJackpot);
wallet.transfer(toWallet);
}
function getWinner(uint _round) public view returns (address payable) {<FILL_FUNCTION_BODY> }
function changeRoundTime(uint _time) onlyOwner public {
roundTime = _time;
}
function changeStartTime(uint _time) onlyOwner public {
startTime = _time;
}
function changeWallet(address payable _wallet) onlyOwner public {
wallet = _wallet;
}
function changeJackpot(address payable _jackpot) onlyOwner public {
jackpot = _jackpot;
}
function changeMinimalBet(uint _minBet) onlyOwner public {
minBet = _minBet;
}
function changePercents(uint _toWinner, uint _toNextRound, uint _toWallet, uint _toJackPot) onlyOwner public {
uint total = _toWinner.add(_toNextRound).add(_toWallet).add(_toJackPot);
require(total == 100);
walletPercent = _toWallet;
nextRoundPercent = _toNextRound;
jackpotPercent = _toJackPot;
}
function getCurrentRound() public view returns (uint) {
return now.sub(startTime).div(roundTime).add(1); // start round is 1
}
function getPreviosRound() public view returns (uint) {
return getCurrentRound().sub(1);
}
function getRoundBalance(uint _round) public view returns (uint) {
return balances[_round];
}
function getPoolBalance(uint _round) public view returns (uint) {
return pool[_round];
}
function getRoundByTime(uint _time) public view returns (uint) {
return _time.sub(startTime).div(roundTime);
}
} | contract FastnFurious is Ownable {
using SafeMath for uint;
// round => winner
mapping(uint => address payable) public winners;
// round => gain
mapping(uint => uint) public balances;
uint public minBet = 0.1 ether; // 0.1 ether;
uint public startTime = 1554076800; // 04.01.2019 00:00:00
uint public roundTime = 60; // 1 min in sec
address payable public wallet;
address payable public jackpot;
mapping (uint => uint) public pool;
uint public walletPercent = 20;
uint public nextRoundPercent = 15;
uint public jackpotPercent = 15;
uint public lastRound;
constructor (address payable _wallet, address payable _jackpot) public {
require(_wallet != address(0));
require(_jackpot != address(0));
wallet = _wallet;
jackpot = _jackpot;
}
function () external payable {
require(gasleft() > 150000);
setBet(msg.sender);
}
function setBet(address payable _player) public payable {
require(msg.value >= minBet);
uint currentRound = getCurrentRound();
if (currentRound > 1 && balances[currentRound] == 0) {
uint gain = balances[lastRound];
balances[lastRound] = 0;
balances[currentRound] = balances[currentRound].add(pool[lastRound]);
address payable winner = getWinner(lastRound);
winner.transfer(gain);
}
lastRound = currentRound;
uint amount = msg.value;
uint toWallet = amount.mul(walletPercent).div(100);
uint toNextRound = amount.mul(nextRoundPercent).div(100);
uint toJackpot = amount.mul(jackpotPercent).div(100);
winners[currentRound] = _player;
balances[currentRound] = balances[currentRound].add(amount).sub(toWallet).sub(toNextRound).sub(toJackpot);
pool[currentRound] = pool[currentRound].add(toNextRound);
jackpot.transfer(toJackpot);
wallet.transfer(toWallet);
}
<FILL_FUNCTION>
function changeRoundTime(uint _time) onlyOwner public {
roundTime = _time;
}
function changeStartTime(uint _time) onlyOwner public {
startTime = _time;
}
function changeWallet(address payable _wallet) onlyOwner public {
wallet = _wallet;
}
function changeJackpot(address payable _jackpot) onlyOwner public {
jackpot = _jackpot;
}
function changeMinimalBet(uint _minBet) onlyOwner public {
minBet = _minBet;
}
function changePercents(uint _toWinner, uint _toNextRound, uint _toWallet, uint _toJackPot) onlyOwner public {
uint total = _toWinner.add(_toNextRound).add(_toWallet).add(_toJackPot);
require(total == 100);
walletPercent = _toWallet;
nextRoundPercent = _toNextRound;
jackpotPercent = _toJackPot;
}
function getCurrentRound() public view returns (uint) {
return now.sub(startTime).div(roundTime).add(1); // start round is 1
}
function getPreviosRound() public view returns (uint) {
return getCurrentRound().sub(1);
}
function getRoundBalance(uint _round) public view returns (uint) {
return balances[_round];
}
function getPoolBalance(uint _round) public view returns (uint) {
return pool[_round];
}
function getRoundByTime(uint _time) public view returns (uint) {
return _time.sub(startTime).div(roundTime);
}
} |
if (winners[_round] != address(0)) return winners[_round];
else return wallet;
| function getWinner(uint _round) public view returns (address payable) | function getWinner(uint _round) public view returns (address payable) |
42840 | InterPass | _transferStandard | contract InterPass is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1000 * 10**9 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'InterPass';
string private _symbol = 'PASS';
uint8 private _decimals = 9;
uint256 private _taxFee = 5;
uint256 private _teamFee = 10;
uint256 private _previousTaxFee = _taxFee;
uint256 private _previousTeamFee = _teamFee;
address payable public _TeamWallet;
address payable public _marketingWalletAddress;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwap = false;
bool public swapEnabled = true;
uint256 private _maxTxAmount = 100 * 10**7 * 10**9; // .1%
uint256 private _numOfTokensToExchangeForTeam = 500 * 10**7 * 10**9; // 0.05%
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapEnabledUpdated(bool enabled);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor (address payable TeamWalletAddress, address payable marketingWalletAddress) public {
_TeamWallet = TeamWalletAddress;
_marketingWalletAddress = marketingWalletAddress;
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
// Exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function setExcludeFromFee(address account, bool excluded) external onlyOwner() {
_isExcludedFromFee[account] = excluded;
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function removeAllFee() private {
if(_taxFee == 0 && _teamFee == 0) return;
_previousTaxFee = _taxFee;
_previousTeamFee = _teamFee;
_taxFee = 0;
_teamFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_teamFee = _previousTeamFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap?
// also, don't get caught in a circular team event.
// also, don't swap if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
// We need to swap the current tokens to ETH and send to the team wallet
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToTeam(address(this).balance);
}
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
//transfer amount, it will take tax and team fee
_tokenTransfer(sender,recipient,amount,takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function sendETHToTeam(uint256 amount) private {
_TeamWallet.transfer(amount.div(2));
_marketingWalletAddress.transfer(amount.div(2));
}
// We are exposing these functions to be able to manual swap and send
// in case the token is highly valued and 5M becomes too much
function manualSwap() external onlyOwner() {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualSend() external onlyOwner() {
uint256 contractETHBalance = address(this).balance;
sendETHToTeam(contractETHBalance);
}
function setSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
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 {<FILL_FUNCTION_BODY> }
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 _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _taxFee, _teamFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, 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 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getTaxFee() private view returns(uint256) {
return _taxFee;
}
function _getMaxTxAmount() private view returns(uint256) {
return _maxTxAmount;
}
function _getETHBalance() public view returns(uint256 balance) {
return address(this).balance;
}
function _setTaxFee(uint256 taxFee) external onlyOwner() {
require(taxFee >= 1 && taxFee <= 25, 'taxFee should be in 1 - 25');
_taxFee = taxFee;
}
function _setTeamFee(uint256 teamFee) external onlyOwner() {
require(teamFee >= 1 && teamFee <= 25, 'teamFee should be in 1 - 25');
_teamFee = teamFee;
}
function _setTeamWallet(address payable TeamWalletAddress) external onlyOwner() {
_TeamWallet = TeamWalletAddress;
}
function _setMarketingWallet(address payable marketingWalletAddress) external onlyOwner() {
_marketingWalletAddress = marketingWalletAddress;
}
function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
_maxTxAmount = maxTxAmount;
}
} | contract InterPass is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1000 * 10**9 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'InterPass';
string private _symbol = 'PASS';
uint8 private _decimals = 9;
uint256 private _taxFee = 5;
uint256 private _teamFee = 10;
uint256 private _previousTaxFee = _taxFee;
uint256 private _previousTeamFee = _teamFee;
address payable public _TeamWallet;
address payable public _marketingWalletAddress;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwap = false;
bool public swapEnabled = true;
uint256 private _maxTxAmount = 100 * 10**7 * 10**9; // .1%
uint256 private _numOfTokensToExchangeForTeam = 500 * 10**7 * 10**9; // 0.05%
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapEnabledUpdated(bool enabled);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor (address payable TeamWalletAddress, address payable marketingWalletAddress) public {
_TeamWallet = TeamWalletAddress;
_marketingWalletAddress = marketingWalletAddress;
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
// Exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function setExcludeFromFee(address account, bool excluded) external onlyOwner() {
_isExcludedFromFee[account] = excluded;
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function removeAllFee() private {
if(_taxFee == 0 && _teamFee == 0) return;
_previousTaxFee = _taxFee;
_previousTeamFee = _teamFee;
_taxFee = 0;
_teamFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_teamFee = _previousTeamFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap?
// also, don't get caught in a circular team event.
// also, don't swap if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
// We need to swap the current tokens to ETH and send to the team wallet
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToTeam(address(this).balance);
}
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
//transfer amount, it will take tax and team fee
_tokenTransfer(sender,recipient,amount,takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function sendETHToTeam(uint256 amount) private {
_TeamWallet.transfer(amount.div(2));
_marketingWalletAddress.transfer(amount.div(2));
}
// We are exposing these functions to be able to manual swap and send
// in case the token is highly valued and 5M becomes too much
function manualSwap() external onlyOwner() {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualSend() external onlyOwner() {
uint256 contractETHBalance = address(this).balance;
sendETHToTeam(contractETHBalance);
}
function setSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
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();
}
<FILL_FUNCTION>
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 _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _taxFee, _teamFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, 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 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getTaxFee() private view returns(uint256) {
return _taxFee;
}
function _getMaxTxAmount() private view returns(uint256) {
return _maxTxAmount;
}
function _getETHBalance() public view returns(uint256 balance) {
return address(this).balance;
}
function _setTaxFee(uint256 taxFee) external onlyOwner() {
require(taxFee >= 1 && taxFee <= 25, 'taxFee should be in 1 - 25');
_taxFee = taxFee;
}
function _setTeamFee(uint256 teamFee) external onlyOwner() {
require(teamFee >= 1 && teamFee <= 25, 'teamFee should be in 1 - 25');
_teamFee = teamFee;
}
function _setTeamWallet(address payable TeamWalletAddress) external onlyOwner() {
_TeamWallet = TeamWalletAddress;
}
function _setMarketingWallet(address payable marketingWalletAddress) external onlyOwner() {
_marketingWalletAddress = marketingWalletAddress;
}
function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
_maxTxAmount = maxTxAmount;
}
} |
(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 _transferStandard(address sender, address recipient, uint256 tAmount) private | function _transferStandard(address sender, address recipient, uint256 tAmount) private |
65831 | MWorld | approveAndCall | contract MWorld 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 MWorld() public {
symbol = "MWE";
name = "MWorld";
decimals = 8;
_totalSupply = 200000000000000000;
balances[0xd2c01f9b4e1a200e0e7d0a8d179b621f1cbd25a2] = _totalSupply;
Transfer(address(0), 0xd2c01f9b4e1a200e0e7d0a8d179b621f1cbd25a2, _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) {
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) {<FILL_FUNCTION_BODY> }
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | contract MWorld 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 MWorld() public {
symbol = "MWE";
name = "MWorld";
decimals = 8;
_totalSupply = 200000000000000000;
balances[0xd2c01f9b4e1a200e0e7d0a8d179b621f1cbd25a2] = _totalSupply;
Transfer(address(0), 0xd2c01f9b4e1a200e0e7d0a8d179b621f1cbd25a2, _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) {
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];
}
<FILL_FUNCTION>
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} |
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
| function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) | function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) |
44728 | BitUPToken | transfer | contract BitUPToken is ERC20, Ownable {
using SafeMath for uint;
/*----------------- Token Information -----------------*/
string public constant name = "BitUP Token";
string public constant symbol = "BUT";
uint8 public decimals = 18; // (ERC20 API) Decimal precision, factor is 1e18
mapping (address => uint256) balances; // User's balances table
mapping (address => mapping (address => uint256)) allowed; // User's allowances table
/*----------------- Alloc Information -----------------*/
uint256 public totalSupply;
uint256 public presaleSupply; // Pre-sale supply
uint256 public angelSupply; // Angel supply
uint256 public marketingSupply; // marketing supply
uint256 public foundationSupply; // /Foundation supply
uint256 public teamSupply; // Team supply
uint256 public communitySupply; // Community supply
uint256 public teamSupply6Months; //Amount of Team supply could be released after 6 months
uint256 public teamSupply12Months; //Amount of Team supply could be released after 12 months
uint256 public teamSupply18Months; //Amount of Team supply could be released after 18 months
uint256 public teamSupply24Months; //Amount of Team supply could be released after 24 months
uint256 public TeamLockingPeriod6Months; // Locking period for team's supply, release 1/4 per 6 months
uint256 public TeamLockingPeriod12Months; // Locking period for team's supply, release 1/4 per 6 months
uint256 public TeamLockingPeriod18Months; // Locking period for team's supply, release 1/4 per 6 months
uint256 public TeamLockingPeriod24Months; // Locking period for team's supply, release 1/4 per 6 months
address public presaleAddress; // Presale address
address public angelAddress; // Angel address
address public marketingAddress; // marketing address
address public foundationAddress; // Foundation address
address public teamAddress; // Team address
address public communityAddress; // Community address
function () {
//if ether is sent to this address, send it back.
//throw;
require(false);
}
/*----------------- Modifiers -----------------*/
modifier nonZeroAddress(address _to) { // Ensures an address is provided
require(_to != 0x0);
_;
}
modifier nonZeroAmount(uint _amount) { // Ensures a non-zero amount
require(_amount > 0);
_;
}
modifier nonZeroValue() { // Ensures a non-zero value is passed
require(msg.value > 0);
_;
}
modifier checkTeamLockingPeriod6Months() { // Ensures locking period is over
assert(now >= TeamLockingPeriod6Months);
_;
}
modifier checkTeamLockingPeriod12Months() { // Ensures locking period is over
assert(now >= TeamLockingPeriod12Months);
_;
}
modifier checkTeamLockingPeriod18Months() { // Ensures locking period is over
assert(now >= TeamLockingPeriod18Months);
_;
}
modifier checkTeamLockingPeriod24Months() { // Ensures locking period is over
assert(now >= TeamLockingPeriod24Months);
_;
}
modifier onlyTeam() { // Ensures only team can call the function
require(msg.sender == teamAddress);
_;
}
/*----------------- Burn -----------------*/
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
// balances[burner] = balances[burner].sub(_value);
decrementBalance(burner, _value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
/*----------------- Token API -----------------*/
// -------------------------------------------------
// Total supply
// -------------------------------------------------
function totalSupply() constant returns (uint256){
return totalSupply;
}
// -------------------------------------------------
// Transfers amount to address
// -------------------------------------------------
function transfer(address _to, uint256 _amount) returns (bool success) {<FILL_FUNCTION_BODY> }
// -------------------------------------------------
// Transfers from one address to another (need allowance to be called first)
// -------------------------------------------------
function transferFrom(address _from, address _to, uint256 _amount) returns (bool success) {
require(balanceOf(_from) >= _amount);
require(allowance(_from, msg.sender) >= _amount);
uint previousBalances = balances[_from] + balances[_to];
decrementBalance(_from, _amount);
addToBalance(_to, _amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
Transfer(_from, _to, _amount);
assert(balances[_from] + balances[_to] == previousBalances);
return true;
}
// -------------------------------------------------
// Approves another address a certain amount of FUEL
// -------------------------------------------------
function approve(address _spender, uint256 _value) returns (bool success) {
require((_value == 0) || (allowance(msg.sender, _spender) == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
// -------------------------------------------------
// Gets an address's FUEL allowance
// -------------------------------------------------
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
// -------------------------------------------------
// Gets the FUEL balance of any address
// -------------------------------------------------
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
// -------------------------------------------------
// Contract's constructor
// -------------------------------------------------
function BitUPToken() {
totalSupply = 1000000000 * 1e18; // 100% - 1 billion total BUT with 18 decimals
presaleSupply = 400000000 * 1e18; // 40% - 400 million BUT pre-crowdsale
angelSupply = 50000000 * 1e18; // 5% - 50 million BUT for the angel crowdsale
teamSupply = 200000000 * 1e18; // 20% - 200 million BUT for team. 1/4 part released per 6 months
foundationSupply = 150000000 * 1e18; // 15% - 300 million BUT for foundation/incentivising efforts
marketingSupply = 100000000 * 1e18; // 10% - 100 million BUT for
communitySupply = 100000000 * 1e18; // 10% - 100 million BUT for
teamSupply6Months = 50000000 * 1e18; // team supply release 1/4 per 6 months
teamSupply12Months = 50000000 * 1e18; // team supply release 1/4 per 6 months
teamSupply18Months = 50000000 * 1e18; // team supply release 1/4 per 6 months
teamSupply24Months = 50000000 * 1e18; // team supply release 1/4 per 6 months
angelAddress = 0xeF01453A730486d262D0b490eF1aDBBF62C2Fe00; // Angel address
presaleAddress = 0x2822332F63a6b80E21cEA5C8c43Cb6f393eb5703; // Presale address
teamAddress = 0x8E199e0c1DD38d455815E11dc2c9A64D6aD893B7; // Team address
foundationAddress = 0xcA972ac76F4Db643C30b86E4A9B54EaBB88Ce5aD; // Foundation address
marketingAddress = 0xd2631280F7f0472271Ae298aF034eBa549d792EA; // marketing address
communityAddress = 0xF691e8b2B2293D3d3b06ecdF217973B40258208C; //Community address
TeamLockingPeriod6Months = now.add(180 * 1 days); // 180 days locking period
TeamLockingPeriod12Months = now.add(360 * 1 days); // 360 days locking period
TeamLockingPeriod18Months = now.add(450 * 1 days); // 450 days locking period
TeamLockingPeriod24Months = now.add(730 * 1 days); // 730 days locking period
addToBalance(foundationAddress, foundationSupply);
foundationSupply = 0;
addToBalance(marketingAddress, marketingSupply);
marketingSupply = 0;
addToBalance(communityAddress, communitySupply);
communitySupply = 0;
addToBalance(presaleAddress, presaleSupply);
presaleSupply = 0;
addToBalance(angelAddress, angelSupply);
angelSupply = 0;
}
// -------------------------------------------------
// Releases 1/4 of team supply after 6 months
// -------------------------------------------------
function releaseTeamTokensAfter6Months() checkTeamLockingPeriod6Months onlyTeam returns(bool success) {
require(teamSupply6Months > 0);
addToBalance(teamAddress, teamSupply6Months);
Transfer(0x0, teamAddress, teamSupply6Months);
teamSupply6Months = 0;
teamSupply.sub(teamSupply6Months);
return true;
}
// -------------------------------------------------
// Releases 1/4 of team supply after 12 months
// -------------------------------------------------
function releaseTeamTokensAfter12Months() checkTeamLockingPeriod12Months onlyTeam returns(bool success) {
require(teamSupply12Months > 0);
addToBalance(teamAddress, teamSupply12Months);
Transfer(0x0, teamAddress, teamSupply12Months);
teamSupply12Months = 0;
teamSupply.sub(teamSupply12Months);
return true;
}
// -------------------------------------------------
// Releases 1/4 of team supply after 18 months
// -------------------------------------------------
function releaseTeamTokensAfter18Months() checkTeamLockingPeriod18Months onlyTeam returns(bool success) {
require(teamSupply18Months > 0);
addToBalance(teamAddress, teamSupply18Months);
Transfer(0x0, teamAddress, teamSupply18Months);
teamSupply18Months = 0;
teamSupply.sub(teamSupply18Months);
return true;
}
// -------------------------------------------------
// Releases 1/4 of team supply after 24 months
// -------------------------------------------------
function releaseTeamTokensAfter24Months() checkTeamLockingPeriod24Months onlyTeam returns(bool success) {
require(teamSupply24Months > 0);
addToBalance(teamAddress, teamSupply24Months);
Transfer(0x0, teamAddress, teamSupply24Months);
teamSupply24Months = 0;
teamSupply.sub(teamSupply24Months);
return true;
}
// -------------------------------------------------
// Adds to balance
// -------------------------------------------------
function addToBalance(address _address, uint _amount) internal {
balances[_address] = SafeMath.add(balances[_address], _amount);
}
// -------------------------------------------------
// Removes from balance
// -------------------------------------------------
function decrementBalance(address _address, uint _amount) internal {
balances[_address] = SafeMath.sub(balances[_address], _amount);
}
} | contract BitUPToken is ERC20, Ownable {
using SafeMath for uint;
/*----------------- Token Information -----------------*/
string public constant name = "BitUP Token";
string public constant symbol = "BUT";
uint8 public decimals = 18; // (ERC20 API) Decimal precision, factor is 1e18
mapping (address => uint256) balances; // User's balances table
mapping (address => mapping (address => uint256)) allowed; // User's allowances table
/*----------------- Alloc Information -----------------*/
uint256 public totalSupply;
uint256 public presaleSupply; // Pre-sale supply
uint256 public angelSupply; // Angel supply
uint256 public marketingSupply; // marketing supply
uint256 public foundationSupply; // /Foundation supply
uint256 public teamSupply; // Team supply
uint256 public communitySupply; // Community supply
uint256 public teamSupply6Months; //Amount of Team supply could be released after 6 months
uint256 public teamSupply12Months; //Amount of Team supply could be released after 12 months
uint256 public teamSupply18Months; //Amount of Team supply could be released after 18 months
uint256 public teamSupply24Months; //Amount of Team supply could be released after 24 months
uint256 public TeamLockingPeriod6Months; // Locking period for team's supply, release 1/4 per 6 months
uint256 public TeamLockingPeriod12Months; // Locking period for team's supply, release 1/4 per 6 months
uint256 public TeamLockingPeriod18Months; // Locking period for team's supply, release 1/4 per 6 months
uint256 public TeamLockingPeriod24Months; // Locking period for team's supply, release 1/4 per 6 months
address public presaleAddress; // Presale address
address public angelAddress; // Angel address
address public marketingAddress; // marketing address
address public foundationAddress; // Foundation address
address public teamAddress; // Team address
address public communityAddress; // Community address
function () {
//if ether is sent to this address, send it back.
//throw;
require(false);
}
/*----------------- Modifiers -----------------*/
modifier nonZeroAddress(address _to) { // Ensures an address is provided
require(_to != 0x0);
_;
}
modifier nonZeroAmount(uint _amount) { // Ensures a non-zero amount
require(_amount > 0);
_;
}
modifier nonZeroValue() { // Ensures a non-zero value is passed
require(msg.value > 0);
_;
}
modifier checkTeamLockingPeriod6Months() { // Ensures locking period is over
assert(now >= TeamLockingPeriod6Months);
_;
}
modifier checkTeamLockingPeriod12Months() { // Ensures locking period is over
assert(now >= TeamLockingPeriod12Months);
_;
}
modifier checkTeamLockingPeriod18Months() { // Ensures locking period is over
assert(now >= TeamLockingPeriod18Months);
_;
}
modifier checkTeamLockingPeriod24Months() { // Ensures locking period is over
assert(now >= TeamLockingPeriod24Months);
_;
}
modifier onlyTeam() { // Ensures only team can call the function
require(msg.sender == teamAddress);
_;
}
/*----------------- Burn -----------------*/
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
// balances[burner] = balances[burner].sub(_value);
decrementBalance(burner, _value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
/*----------------- Token API -----------------*/
// -------------------------------------------------
// Total supply
// -------------------------------------------------
function totalSupply() constant returns (uint256){
return totalSupply;
}
<FILL_FUNCTION>
// -------------------------------------------------
// Transfers from one address to another (need allowance to be called first)
// -------------------------------------------------
function transferFrom(address _from, address _to, uint256 _amount) returns (bool success) {
require(balanceOf(_from) >= _amount);
require(allowance(_from, msg.sender) >= _amount);
uint previousBalances = balances[_from] + balances[_to];
decrementBalance(_from, _amount);
addToBalance(_to, _amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
Transfer(_from, _to, _amount);
assert(balances[_from] + balances[_to] == previousBalances);
return true;
}
// -------------------------------------------------
// Approves another address a certain amount of FUEL
// -------------------------------------------------
function approve(address _spender, uint256 _value) returns (bool success) {
require((_value == 0) || (allowance(msg.sender, _spender) == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
// -------------------------------------------------
// Gets an address's FUEL allowance
// -------------------------------------------------
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
// -------------------------------------------------
// Gets the FUEL balance of any address
// -------------------------------------------------
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
// -------------------------------------------------
// Contract's constructor
// -------------------------------------------------
function BitUPToken() {
totalSupply = 1000000000 * 1e18; // 100% - 1 billion total BUT with 18 decimals
presaleSupply = 400000000 * 1e18; // 40% - 400 million BUT pre-crowdsale
angelSupply = 50000000 * 1e18; // 5% - 50 million BUT for the angel crowdsale
teamSupply = 200000000 * 1e18; // 20% - 200 million BUT for team. 1/4 part released per 6 months
foundationSupply = 150000000 * 1e18; // 15% - 300 million BUT for foundation/incentivising efforts
marketingSupply = 100000000 * 1e18; // 10% - 100 million BUT for
communitySupply = 100000000 * 1e18; // 10% - 100 million BUT for
teamSupply6Months = 50000000 * 1e18; // team supply release 1/4 per 6 months
teamSupply12Months = 50000000 * 1e18; // team supply release 1/4 per 6 months
teamSupply18Months = 50000000 * 1e18; // team supply release 1/4 per 6 months
teamSupply24Months = 50000000 * 1e18; // team supply release 1/4 per 6 months
angelAddress = 0xeF01453A730486d262D0b490eF1aDBBF62C2Fe00; // Angel address
presaleAddress = 0x2822332F63a6b80E21cEA5C8c43Cb6f393eb5703; // Presale address
teamAddress = 0x8E199e0c1DD38d455815E11dc2c9A64D6aD893B7; // Team address
foundationAddress = 0xcA972ac76F4Db643C30b86E4A9B54EaBB88Ce5aD; // Foundation address
marketingAddress = 0xd2631280F7f0472271Ae298aF034eBa549d792EA; // marketing address
communityAddress = 0xF691e8b2B2293D3d3b06ecdF217973B40258208C; //Community address
TeamLockingPeriod6Months = now.add(180 * 1 days); // 180 days locking period
TeamLockingPeriod12Months = now.add(360 * 1 days); // 360 days locking period
TeamLockingPeriod18Months = now.add(450 * 1 days); // 450 days locking period
TeamLockingPeriod24Months = now.add(730 * 1 days); // 730 days locking period
addToBalance(foundationAddress, foundationSupply);
foundationSupply = 0;
addToBalance(marketingAddress, marketingSupply);
marketingSupply = 0;
addToBalance(communityAddress, communitySupply);
communitySupply = 0;
addToBalance(presaleAddress, presaleSupply);
presaleSupply = 0;
addToBalance(angelAddress, angelSupply);
angelSupply = 0;
}
// -------------------------------------------------
// Releases 1/4 of team supply after 6 months
// -------------------------------------------------
function releaseTeamTokensAfter6Months() checkTeamLockingPeriod6Months onlyTeam returns(bool success) {
require(teamSupply6Months > 0);
addToBalance(teamAddress, teamSupply6Months);
Transfer(0x0, teamAddress, teamSupply6Months);
teamSupply6Months = 0;
teamSupply.sub(teamSupply6Months);
return true;
}
// -------------------------------------------------
// Releases 1/4 of team supply after 12 months
// -------------------------------------------------
function releaseTeamTokensAfter12Months() checkTeamLockingPeriod12Months onlyTeam returns(bool success) {
require(teamSupply12Months > 0);
addToBalance(teamAddress, teamSupply12Months);
Transfer(0x0, teamAddress, teamSupply12Months);
teamSupply12Months = 0;
teamSupply.sub(teamSupply12Months);
return true;
}
// -------------------------------------------------
// Releases 1/4 of team supply after 18 months
// -------------------------------------------------
function releaseTeamTokensAfter18Months() checkTeamLockingPeriod18Months onlyTeam returns(bool success) {
require(teamSupply18Months > 0);
addToBalance(teamAddress, teamSupply18Months);
Transfer(0x0, teamAddress, teamSupply18Months);
teamSupply18Months = 0;
teamSupply.sub(teamSupply18Months);
return true;
}
// -------------------------------------------------
// Releases 1/4 of team supply after 24 months
// -------------------------------------------------
function releaseTeamTokensAfter24Months() checkTeamLockingPeriod24Months onlyTeam returns(bool success) {
require(teamSupply24Months > 0);
addToBalance(teamAddress, teamSupply24Months);
Transfer(0x0, teamAddress, teamSupply24Months);
teamSupply24Months = 0;
teamSupply.sub(teamSupply24Months);
return true;
}
// -------------------------------------------------
// Adds to balance
// -------------------------------------------------
function addToBalance(address _address, uint _amount) internal {
balances[_address] = SafeMath.add(balances[_address], _amount);
}
// -------------------------------------------------
// Removes from balance
// -------------------------------------------------
function decrementBalance(address _address, uint _amount) internal {
balances[_address] = SafeMath.sub(balances[_address], _amount);
}
} |
require(balanceOf(msg.sender) >= _amount);
uint previousBalances = balances[msg.sender] + balances[_to];
addToBalance(_to, _amount);
decrementBalance(msg.sender, _amount);
Transfer(msg.sender, _to, _amount);
assert(balances[msg.sender] + balances[_to] == previousBalances);
return true;
| function transfer(address _to, uint256 _amount) returns (bool success) | // -------------------------------------------------
// Transfers amount to address
// -------------------------------------------------
function transfer(address _to, uint256 _amount) returns (bool success) |
62795 | PumpkinHedzPass | reservePass | contract PumpkinHedzPass is ERC1155Burnable, Ownable {
bool public inPresale;
bool public reserved;
bool public saleStarted;
uint256 private passMinted;
uint256 constant public totalSupply = 9980;
uint256 constant public mintPrice = 0.08 ether;
mapping(uint256 => uint256) public ogIdUsed;
IERC1155 immutable private ogBadge;
constructor(address _ogBadge, string memory uri) ERC1155(uri) {
ogBadge = IERC1155(_ogBadge);
}
function withdraw() external onlyOwner {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external pure returns(string memory) {
return "Pumpkin Hedz Pass";
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external pure returns(string memory) {
return "PHP";
}
function startPreSale() external onlyOwner {
require(!saleStarted, "cannot restart presale");
inPresale = !inPresale;
}
function startPublicSale() external onlyOwner {
require(inPresale, "Should start presale first");
require(!saleStarted, "Already in public sale");
saleStarted = !saleStarted;
inPresale = !inPresale;
}
function reservePass(address reciever, uint256[] calldata ids, uint256[] calldata amounts) external onlyOwner {<FILL_FUNCTION_BODY> }
function setBaseURI(string memory baseURI) external onlyOwner {
_setURI(baseURI);
}
/**
* Mints Hedz Pass
*/
function mintPresale(uint256 ogId, uint256 numberOfTokens) public payable {
require(inPresale, "Presale not started");
require(numberOfTokens > 0, "Minimum 1 nft per transaction is required");
require(ogBadge.balanceOf(msg.sender, ogId) > 0, "You are not owner of this OG Badge ID");
require(ogIdUsed[ogId]+numberOfTokens <= 2, "Trying to mint more then 2 Pass on this OG badge ID");
require(msg.value == numberOfTokens*mintPrice, "Wrong eth value sent");
ogIdUsed[ogId] += numberOfTokens;
passMinted += numberOfTokens;
_mint(msg.sender, 0, numberOfTokens,"");
}
/**
* Mints Hedz Pass
*/
function mintPass(uint256 numberOfTokens) public payable {
require(saleStarted, "Public sale not started yet");
require(numberOfTokens > 0 && numberOfTokens <= 10, "Min 1 && Max 10 nfts per transaction is allowed");
require(msg.value == numberOfTokens*mintPrice, "Wrong eth value sent");
require(passMinted+numberOfTokens <= 9980, "Mint will exceed max Supply");
passMinted += numberOfTokens;
_mint(msg.sender, 1, numberOfTokens,"");
}
} | contract PumpkinHedzPass is ERC1155Burnable, Ownable {
bool public inPresale;
bool public reserved;
bool public saleStarted;
uint256 private passMinted;
uint256 constant public totalSupply = 9980;
uint256 constant public mintPrice = 0.08 ether;
mapping(uint256 => uint256) public ogIdUsed;
IERC1155 immutable private ogBadge;
constructor(address _ogBadge, string memory uri) ERC1155(uri) {
ogBadge = IERC1155(_ogBadge);
}
function withdraw() external onlyOwner {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external pure returns(string memory) {
return "Pumpkin Hedz Pass";
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external pure returns(string memory) {
return "PHP";
}
function startPreSale() external onlyOwner {
require(!saleStarted, "cannot restart presale");
inPresale = !inPresale;
}
function startPublicSale() external onlyOwner {
require(inPresale, "Should start presale first");
require(!saleStarted, "Already in public sale");
saleStarted = !saleStarted;
inPresale = !inPresale;
}
<FILL_FUNCTION>
function setBaseURI(string memory baseURI) external onlyOwner {
_setURI(baseURI);
}
/**
* Mints Hedz Pass
*/
function mintPresale(uint256 ogId, uint256 numberOfTokens) public payable {
require(inPresale, "Presale not started");
require(numberOfTokens > 0, "Minimum 1 nft per transaction is required");
require(ogBadge.balanceOf(msg.sender, ogId) > 0, "You are not owner of this OG Badge ID");
require(ogIdUsed[ogId]+numberOfTokens <= 2, "Trying to mint more then 2 Pass on this OG badge ID");
require(msg.value == numberOfTokens*mintPrice, "Wrong eth value sent");
ogIdUsed[ogId] += numberOfTokens;
passMinted += numberOfTokens;
_mint(msg.sender, 0, numberOfTokens,"");
}
/**
* Mints Hedz Pass
*/
function mintPass(uint256 numberOfTokens) public payable {
require(saleStarted, "Public sale not started yet");
require(numberOfTokens > 0 && numberOfTokens <= 10, "Min 1 && Max 10 nfts per transaction is allowed");
require(msg.value == numberOfTokens*mintPrice, "Wrong eth value sent");
require(passMinted+numberOfTokens <= 9980, "Mint will exceed max Supply");
passMinted += numberOfTokens;
_mint(msg.sender, 1, numberOfTokens,"");
}
} |
require(!reserved, "Cannot reserve ids multiple time");
for(uint i=0; i<2; i++)
{
passMinted += amounts[i];
}
_mintBatch(reciever, ids, amounts, "");
reserved = true;
| function reservePass(address reciever, uint256[] calldata ids, uint256[] calldata amounts) external onlyOwner | function reservePass(address reciever, uint256[] calldata ids, uint256[] calldata amounts) external onlyOwner |
37005 | Tokyolympic | restoreAllFee | contract Tokyolympic is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "Tokyolympic";
string private constant _symbol = "TKYO";
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _redisT = 1;
uint256 private _edistT = 12;
uint256 private _previousredisT = _redisT;
uint256 private _previousedistT = _edistT;
mapping(address => bool) private bots;
mapping(address => uint256) private cooldown;
address payable private _teamAddress;
address payable private _marketingFunds;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = true;
uint256 public _maxTxAmount = 5000 * 10**9;
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor(address payable addr1, address payable addr2) {
_teamAddress = addr1;
_marketingFunds = addr2;
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_teamAddress] = true;
_isExcludedFromFee[_marketingFunds] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function 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 (_redisT == 0 && _edistT == 0) return;
_previousredisT = _redisT;
_previousedistT = _edistT;
_redisT = 0;
_edistT = 0;
}
function restoreAllFee() private {<FILL_FUNCTION_BODY> }
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
//Trade start check
if (from == uniswapV2Pair || to == uniswapV2Pair) {
require(tradingOpen, "Trading is not enabled yet");
}
require(amount <= _maxTxAmount);
require(!bots[from] && !bots[to]);
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_teamAddress.transfer(amount.div(2));
_marketingFunds.transfer(amount.div(2));
}
function launchTKYO() external onlyOwner() {
require(!tradingOpen, "trading is already started");
tradingOpen = true;
}
function manualswap() external {
require(_msgSender() == _teamAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _teamAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisT, _edistT);
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 redisT,
uint256 edistT
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisT).div(100);
uint256 tTeam = tAmount.mul(edistT).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
require(maxTxPercent > 0, "Amount must be greater than 0");
_maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2);
emit MaxTxAmountUpdated(_maxTxAmount);
}
function modredisT(uint256 redisT) external onlyOwner() {
require(redisT >= 0 && redisT <= 25, 'redisT should be in 0 - 25');
_redisT = redisT;
}
function modedistT(uint256 edistT) external onlyOwner() {
require(edistT >= 0 && edistT <= 25, 'edistT should be in 0 - 25');
_edistT = edistT;
}
} | contract Tokyolympic is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "Tokyolympic";
string private constant _symbol = "TKYO";
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _redisT = 1;
uint256 private _edistT = 12;
uint256 private _previousredisT = _redisT;
uint256 private _previousedistT = _edistT;
mapping(address => bool) private bots;
mapping(address => uint256) private cooldown;
address payable private _teamAddress;
address payable private _marketingFunds;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = true;
uint256 public _maxTxAmount = 5000 * 10**9;
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor(address payable addr1, address payable addr2) {
_teamAddress = addr1;
_marketingFunds = addr2;
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_teamAddress] = true;
_isExcludedFromFee[_marketingFunds] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function 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 (_redisT == 0 && _edistT == 0) return;
_previousredisT = _redisT;
_previousedistT = _edistT;
_redisT = 0;
_edistT = 0;
}
<FILL_FUNCTION>
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
//Trade start check
if (from == uniswapV2Pair || to == uniswapV2Pair) {
require(tradingOpen, "Trading is not enabled yet");
}
require(amount <= _maxTxAmount);
require(!bots[from] && !bots[to]);
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_teamAddress.transfer(amount.div(2));
_marketingFunds.transfer(amount.div(2));
}
function launchTKYO() external onlyOwner() {
require(!tradingOpen, "trading is already started");
tradingOpen = true;
}
function manualswap() external {
require(_msgSender() == _teamAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _teamAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisT, _edistT);
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 redisT,
uint256 edistT
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisT).div(100);
uint256 tTeam = tAmount.mul(edistT).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
require(maxTxPercent > 0, "Amount must be greater than 0");
_maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2);
emit MaxTxAmountUpdated(_maxTxAmount);
}
function modredisT(uint256 redisT) external onlyOwner() {
require(redisT >= 0 && redisT <= 25, 'redisT should be in 0 - 25');
_redisT = redisT;
}
function modedistT(uint256 edistT) external onlyOwner() {
require(edistT >= 0 && edistT <= 25, 'edistT should be in 0 - 25');
_edistT = edistT;
}
} |
_redisT = _previousredisT;
_edistT = _previousedistT;
| function restoreAllFee() private | function restoreAllFee() private |
63596 | Ownable | transferOwnership | contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "You are not owner.");
_;
}
function transferOwnership(address _newOwner) public onlyOwner {<FILL_FUNCTION_BODY> }
} | contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "You are not owner.");
_;
}
<FILL_FUNCTION>
} |
require(_newOwner != address(0), "Invalid address.");
owner = _newOwner;
emit OwnershipTransferred(owner, _newOwner);
| function transferOwnership(address _newOwner) public onlyOwner | function transferOwnership(address _newOwner) public onlyOwner |
1348 | Pausable | _unpause | contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {<FILL_FUNCTION_BODY> }
} | contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
<FILL_FUNCTION>
} |
_paused = false;
emit Unpaused(_msgSender());
| function _unpause() internal virtual whenPaused | /**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused |
76035 | yDAI | getGeneratedYelds | contract yDAI is ERC20, ERC20Detailed, ReentrancyGuard, Structs, Ownable {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
struct Deposit {
uint256 amount;
uint256 start; // Block when it started
}
uint256 public pool;
address public token;
address public compound;
address public fulcrum;
address public aave;
address public aavePool;
address public aaveToken;
address public dydx;
uint256 public dToken;
address public apr;
address public chai;
// Add other tokens if implemented for another stablecoin
address public uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public retirementYeldTreasury;
IERC20 public yeldToken;
uint256 public maximumTokensToBurn = 50000 * 1e18;
// When you stake say 1000 DAI for a day that will be your maximum
// if you stake the next time 300 DAI your maximum will stay the same
// if you stake 2000 at once it will increase to 2000 DAI
mapping(bytes32 => uint256) public numberOfParticipants;
mapping(address => Deposit) public deposits;
uint256 public constant minimumEffectAmount = 5 * 10 ** 18;
uint256 public constant oneDayInBlocks = 6500;
uint256 public yeldToRewardPerDay = 100e18; // 100 YELD per day per 1 million stablecoins padded with 18 zeroes to have that flexibility
uint256 public constant oneMillion = 1e6;
enum Lender {
NONE,
DYDX,
COMPOUND,
AAVE,
FULCRUM
}
Lender public provider = Lender.NONE;
constructor (address _yeldToken, address payable _retirementYeldTreasury) public payable ERC20Detailed("yearn DAI", "yDAI", 18) {
token = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
apr = address(0xdD6d648C991f7d47454354f4Ef326b04025a48A8);
dydx = address(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e);
aave = address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
aavePool = address(0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3);
fulcrum = address(0x493C57C4763932315A328269E1ADaD09653B9081);
aaveToken = address(0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d);
compound = address(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643);
chai = address(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215);
dToken = 3;
yeldToken = IERC20(_yeldToken);
retirementYeldTreasury = _retirementYeldTreasury;
approveToken();
}
// To receive ETH after converting it from DAI
function () external payable {}
function setRetirementYeldTreasury(address payable _treasury) public onlyOwner {
retirementYeldTreasury = _treasury;
}
// In case a new uniswap router version is released
function setUniswapRouter(address _uniswapRouter) public onlyOwner {
uniswapRouter = _uniswapRouter;
}
function extractTokensIfStuck(address _token, uint256 _amount) public onlyOwner {
IERC20(_token).transfer(msg.sender, _amount);
}
function extractETHIfStuck() public onlyOwner {
owner().transfer(address(this).balance);
}
function changeYeldToRewardPerDay(uint256 _amount) public onlyOwner {
yeldToRewardPerDay = _amount;
}
function getGeneratedYelds() public view returns(uint256) {<FILL_FUNCTION_BODY> }
function extractYELDEarningsWhileKeepingDeposit() public {
require(deposits[msg.sender].start > 0 && deposits[msg.sender].amount > 0, 'Must have deposited stablecoins beforehand');
uint256 generatedYelds = getGeneratedYelds();
deposits[msg.sender] = Deposit(deposits[msg.sender].amount, block.number);
yeldToken.transfer(msg.sender, generatedYelds);
}
function deposit(uint256 _amount)
external
nonReentrant
{
require(_amount > 0, "deposit must be greater than 0");
pool = calcPoolValueInToken();
IERC20(token).safeTransferFrom(msg.sender, address(this), _amount);
// Yeld
uint256 userYeldBalance = yeldToken.balanceOf(msg.sender);
uint256 amountFivePercent = _amount.mul(5).div(100);
require(userYeldBalance >= amountFivePercent, 'Your YELD balance must be 5% or higher of the amount to deposit');
if (getGeneratedYelds() > 0) extractYELDEarningsWhileKeepingDeposit();
deposits[msg.sender] = Deposit(deposits[msg.sender].amount.add(_amount), block.number);
// Yeld
// Calculate pool shares
uint256 shares = 0;
if (pool == 0) {
shares = _amount;
pool = _amount;
} else {
shares = (_amount.mul(_totalSupply)).div(pool);
}
pool = calcPoolValueInToken();
_mint(msg.sender, shares);
}
// Converts DAI to ETH and returns how much ETH has been received from Uniswap
function daiToETH(uint256 _amount) internal returns(uint256) {
IERC20(dai).safeApprove(uniswapRouter, 0);
IERC20(dai).safeApprove(uniswapRouter, _amount);
address[] memory path = new address[](2);
path[0] = dai;
path[1] = weth;
// swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
// 'amounts' is an array where [0] is input DAI amount and [1] is the resulting ETH after the conversion
// even tho we've specified the WETH address, we'll receive ETH since that's how it works on uniswap
// https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensforeth
uint[] memory amounts = IUniswap(uniswapRouter).swapExactTokensForETH(_amount, uint(0), path, address(this), now.add(1800));
return amounts[1];
}
// Buys YELD tokens paying in ETH on Uniswap and removes them from circulation
// Returns how many YELD tokens have been burned
function buyNBurn(uint256 _ethToSwap) internal returns(uint256) {
address[] memory path = new address[](2);
path[0] = weth;
path[1] = address(yeldToken);
// Burns the tokens by taking them out of circulation, sending them to the 0x0 address
uint[] memory amounts = IUniswap(uniswapRouter).swapExactETHForTokens.value(_ethToSwap)(uint(0), path, address(0), now.add(1800));
return amounts[1];
}
// No rebalance implementation for lower fees and faster swaps
function withdraw(uint256 _shares)
external
nonReentrant
{
require(_shares > 0, "withdraw must be greater than 0");
uint256 ibalance = balanceOf(msg.sender);
require(_shares <= ibalance, "insufficient balance");
pool = calcPoolValueInToken();
uint256 r = (pool.mul(_shares)).div(_totalSupply);
_balances[msg.sender] = _balances[msg.sender].sub(_shares, "redeem amount exceeds balance");
_totalSupply = _totalSupply.sub(_shares, '#1 Total supply sub error');
emit Transfer(msg.sender, address(0), _shares);
uint256 b = IERC20(token).balanceOf(address(this));
if (b < r) {
_withdrawSome(r.sub(b, '#2 Withdraw some sub error'));
}
// Yeld
uint256 generatedYelds = getGeneratedYelds();
uint256 halfProfits = (r.sub(deposits[msg.sender].amount, '#3 Half profits sub error')).div(2);
deposits[msg.sender] = Deposit(deposits[msg.sender].amount.sub(_shares), block.number);
yeldToken.transfer(msg.sender, generatedYelds);
// Take a portion of the profits for the buy and burn and retirement yeld
// Convert half the DAI earned into ETH for the protocol algorithms
if (halfProfits > minimumEffectAmount) {
uint256 stakingProfits = daiToETH(halfProfits);
uint256 tokensAlreadyBurned = yeldToken.balanceOf(address(0));
if (tokensAlreadyBurned < maximumTokensToBurn) {
// 98% is the 49% doubled since we already took the 50%
uint256 ethToSwap = stakingProfits.mul(98).div(100);
// Buy and burn only applies up to 50k tokens burned
buyNBurn(ethToSwap);
// 1% for the Retirement Yield
uint256 retirementYeld = stakingProfits.mul(2).div(100);
// Send to the treasury
retirementYeldTreasury.transfer(retirementYeld);
} else {
// If we've reached the maximum burn point, send half the profits to the treasury to reward holders
uint256 retirementYeld = stakingProfits;
// Send to the treasury
retirementYeldTreasury.transfer(retirementYeld);
}
}
// Yeld
IERC20(token).safeTransfer(msg.sender, r);
pool = calcPoolValueInToken();
}
function recommend() public view returns (Lender) {
(,uint256 capr,uint256 iapr,uint256 aapr,uint256 dapr) = IIEarnManager(apr).recommend(token);
uint256 max = 0;
if (capr > max) {
max = capr;
}
if (iapr > max) {
max = iapr;
}
if (aapr > max) {
max = aapr;
}
if (dapr > max) {
max = dapr;
}
Lender newProvider = Lender.NONE;
if (max == capr) {
newProvider = Lender.COMPOUND;
} else if (max == iapr) {
newProvider = Lender.FULCRUM;
} else if (max == aapr) {
newProvider = Lender.AAVE;
} else if (max == dapr) {
newProvider = Lender.DYDX;
}
return newProvider;
}
function getAave() public view returns (address) {
return LendingPoolAddressesProvider(aave).getLendingPool();
}
function getAaveCore() public view returns (address) {
return LendingPoolAddressesProvider(aave).getLendingPoolCore();
}
function approveToken() public {
IERC20(token).safeApprove(compound, uint(-1));
IERC20(token).safeApprove(dydx, uint(-1));
IERC20(token).safeApprove(getAaveCore(), uint(-1));
IERC20(token).safeApprove(fulcrum, uint(-1));
}
function balance() public view returns (uint256) {
return IERC20(token).balanceOf(address(this));
}
function balanceDydxAvailable() public view returns (uint256) {
return IERC20(token).balanceOf(dydx);
}
function balanceDydx() public view returns (uint256) {
Wei memory bal = DyDx(dydx).getAccountWei(Info(address(this), 0), dToken);
return bal.value;
}
function balanceCompound() public view returns (uint256) {
return IERC20(compound).balanceOf(address(this));
}
function balanceCompoundInToken() public view returns (uint256) {
// Mantisa 1e18 to decimals
uint256 b = balanceCompound();
if (b > 0) {
b = b.mul(Compound(compound).exchangeRateStored()).div(1e18);
}
return b;
}
function balanceFulcrumAvailable() public view returns (uint256) {
return IERC20(chai).balanceOf(fulcrum);
}
function balanceFulcrumInToken() public view returns (uint256) {
uint256 b = balanceFulcrum();
if (b > 0) {
b = Fulcrum(fulcrum).assetBalanceOf(address(this));
}
return b;
}
function balanceFulcrum() public view returns (uint256) {
return IERC20(fulcrum).balanceOf(address(this));
}
function balanceAaveAvailable() public view returns (uint256) {
return IERC20(token).balanceOf(aavePool);
}
function balanceAave() public view returns (uint256) {
return IERC20(aaveToken).balanceOf(address(this));
}
function rebalance() public {
Lender newProvider = recommend();
if (newProvider != provider) {
_withdrawAll();
}
if (balance() > 0) {
if (newProvider == Lender.DYDX) {
_supplyDydx(balance());
} else if (newProvider == Lender.FULCRUM) {
_supplyFulcrum(balance());
} else if (newProvider == Lender.COMPOUND) {
_supplyCompound(balance());
} else if (newProvider == Lender.AAVE) {
_supplyAave(balance());
}
}
provider = newProvider;
}
function _withdrawAll() internal {
uint256 amount = balanceCompound();
if (amount > 0) {
_withdrawSomeCompound(balanceCompoundInToken().sub(1));
}
amount = balanceDydx();
if (amount > 0) {
if (amount > balanceDydxAvailable()) {
amount = balanceDydxAvailable();
}
_withdrawDydx(amount);
}
amount = balanceFulcrum();
if (amount > 0) {
if (amount > balanceFulcrumAvailable().sub(1)) {
amount = balanceFulcrumAvailable().sub(1);
}
_withdrawSomeFulcrum(amount);
}
amount = balanceAave();
if (amount > 0) {
if (amount > balanceAaveAvailable()) {
amount = balanceAaveAvailable();
}
_withdrawAave(amount);
}
}
function _withdrawSomeCompound(uint256 _amount) internal {
uint256 b = balanceCompound();
uint256 bT = balanceCompoundInToken();
require(bT >= _amount, "insufficient funds");
// can have unintentional rounding errors
uint256 amount = (b.mul(_amount)).div(bT).add(1);
_withdrawCompound(amount);
}
function _withdrawSomeFulcrum(uint256 _amount) internal {
uint256 b = balanceFulcrum();
uint256 bT = balanceFulcrumInToken();
require(bT >= _amount, "insufficient funds");
// can have unintentional rounding errors
uint256 amount = (b.mul(_amount)).div(bT).add(1);
_withdrawFulcrum(amount);
}
function _withdrawSome(uint256 _amount) internal returns (bool) {
uint256 origAmount = _amount;
uint256 amount = balanceCompound();
if (amount > 0) {
if (_amount > balanceCompoundInToken().sub(1)) {
_withdrawSomeCompound(balanceCompoundInToken().sub(1));
_amount = origAmount.sub(IERC20(token).balanceOf(address(this)));
} else {
_withdrawSomeCompound(_amount);
return true;
}
}
amount = balanceDydx();
if (amount > 0) {
if (_amount > balanceDydxAvailable()) {
_withdrawDydx(balanceDydxAvailable());
_amount = origAmount.sub(IERC20(token).balanceOf(address(this)));
} else {
_withdrawDydx(_amount);
return true;
}
}
amount = balanceFulcrum();
if (amount > 0) {
if (_amount > balanceFulcrumAvailable().sub(1)) {
amount = balanceFulcrumAvailable().sub(1);
_withdrawSomeFulcrum(balanceFulcrumAvailable().sub(1));
_amount = origAmount.sub(IERC20(token).balanceOf(address(this)));
} else {
_withdrawSomeFulcrum(amount);
return true;
}
}
amount = balanceAave();
if (amount > 0) {
if (_amount > balanceAaveAvailable()) {
_withdrawAave(balanceAaveAvailable());
_amount = origAmount.sub(IERC20(token).balanceOf(address(this)));
} else {
_withdrawAave(_amount);
return true;
}
}
return true;
}
function _supplyDydx(uint256 amount) internal {
Info[] memory infos = new Info[](1);
infos[0] = Info(address(this), 0);
AssetAmount memory amt = AssetAmount(true, AssetDenomination.Wei, AssetReference.Delta, amount);
ActionArgs memory act;
act.actionType = ActionType.Deposit;
act.accountId = 0;
act.amount = amt;
act.primaryMarketId = dToken;
act.otherAddress = address(this);
ActionArgs[] memory args = new ActionArgs[](1);
args[0] = act;
DyDx(dydx).operate(infos, args);
}
function _supplyAave(uint amount) internal {
Aave(getAave()).deposit(token, amount, 0);
}
function _supplyFulcrum(uint amount) internal {
require(Fulcrum(fulcrum).mint(address(this), amount) > 0, "FULCRUM: supply failed");
}
function _supplyCompound(uint amount) internal {
require(Compound(compound).mint(amount) == 0, "COMPOUND: supply failed");
}
function _withdrawAave(uint amount) internal {
AToken(aaveToken).redeem(amount);
}
function _withdrawFulcrum(uint amount) internal {
require(Fulcrum(fulcrum).burn(address(this), amount) > 0, "FULCRUM: withdraw failed");
}
function _withdrawCompound(uint amount) internal {
require(Compound(compound).redeem(amount) == 0, "COMPOUND: withdraw failed");
}
function _withdrawDydx(uint256 amount) internal {
Info[] memory infos = new Info[](1);
infos[0] = Info(address(this), 0);
AssetAmount memory amt = AssetAmount(false, AssetDenomination.Wei, AssetReference.Delta, amount);
ActionArgs memory act;
act.actionType = ActionType.Withdraw;
act.accountId = 0;
act.amount = amt;
act.primaryMarketId = dToken;
act.otherAddress = address(this);
ActionArgs[] memory args = new ActionArgs[](1);
args[0] = act;
DyDx(dydx).operate(infos, args);
}
function calcPoolValueInToken() public view returns (uint) {
return balanceCompoundInToken()
.add(balanceFulcrumInToken())
.add(balanceDydx())
.add(balanceAave())
.add(balance());
}
function getPricePerFullShare() public view returns (uint) {
uint _pool = calcPoolValueInToken();
return _pool.mul(1e18).div(_totalSupply);
}
} | contract yDAI is ERC20, ERC20Detailed, ReentrancyGuard, Structs, Ownable {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
struct Deposit {
uint256 amount;
uint256 start; // Block when it started
}
uint256 public pool;
address public token;
address public compound;
address public fulcrum;
address public aave;
address public aavePool;
address public aaveToken;
address public dydx;
uint256 public dToken;
address public apr;
address public chai;
// Add other tokens if implemented for another stablecoin
address public uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public retirementYeldTreasury;
IERC20 public yeldToken;
uint256 public maximumTokensToBurn = 50000 * 1e18;
// When you stake say 1000 DAI for a day that will be your maximum
// if you stake the next time 300 DAI your maximum will stay the same
// if you stake 2000 at once it will increase to 2000 DAI
mapping(bytes32 => uint256) public numberOfParticipants;
mapping(address => Deposit) public deposits;
uint256 public constant minimumEffectAmount = 5 * 10 ** 18;
uint256 public constant oneDayInBlocks = 6500;
uint256 public yeldToRewardPerDay = 100e18; // 100 YELD per day per 1 million stablecoins padded with 18 zeroes to have that flexibility
uint256 public constant oneMillion = 1e6;
enum Lender {
NONE,
DYDX,
COMPOUND,
AAVE,
FULCRUM
}
Lender public provider = Lender.NONE;
constructor (address _yeldToken, address payable _retirementYeldTreasury) public payable ERC20Detailed("yearn DAI", "yDAI", 18) {
token = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
apr = address(0xdD6d648C991f7d47454354f4Ef326b04025a48A8);
dydx = address(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e);
aave = address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
aavePool = address(0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3);
fulcrum = address(0x493C57C4763932315A328269E1ADaD09653B9081);
aaveToken = address(0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d);
compound = address(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643);
chai = address(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215);
dToken = 3;
yeldToken = IERC20(_yeldToken);
retirementYeldTreasury = _retirementYeldTreasury;
approveToken();
}
// To receive ETH after converting it from DAI
function () external payable {}
function setRetirementYeldTreasury(address payable _treasury) public onlyOwner {
retirementYeldTreasury = _treasury;
}
// In case a new uniswap router version is released
function setUniswapRouter(address _uniswapRouter) public onlyOwner {
uniswapRouter = _uniswapRouter;
}
function extractTokensIfStuck(address _token, uint256 _amount) public onlyOwner {
IERC20(_token).transfer(msg.sender, _amount);
}
function extractETHIfStuck() public onlyOwner {
owner().transfer(address(this).balance);
}
function changeYeldToRewardPerDay(uint256 _amount) public onlyOwner {
yeldToRewardPerDay = _amount;
}
<FILL_FUNCTION>
function extractYELDEarningsWhileKeepingDeposit() public {
require(deposits[msg.sender].start > 0 && deposits[msg.sender].amount > 0, 'Must have deposited stablecoins beforehand');
uint256 generatedYelds = getGeneratedYelds();
deposits[msg.sender] = Deposit(deposits[msg.sender].amount, block.number);
yeldToken.transfer(msg.sender, generatedYelds);
}
function deposit(uint256 _amount)
external
nonReentrant
{
require(_amount > 0, "deposit must be greater than 0");
pool = calcPoolValueInToken();
IERC20(token).safeTransferFrom(msg.sender, address(this), _amount);
// Yeld
uint256 userYeldBalance = yeldToken.balanceOf(msg.sender);
uint256 amountFivePercent = _amount.mul(5).div(100);
require(userYeldBalance >= amountFivePercent, 'Your YELD balance must be 5% or higher of the amount to deposit');
if (getGeneratedYelds() > 0) extractYELDEarningsWhileKeepingDeposit();
deposits[msg.sender] = Deposit(deposits[msg.sender].amount.add(_amount), block.number);
// Yeld
// Calculate pool shares
uint256 shares = 0;
if (pool == 0) {
shares = _amount;
pool = _amount;
} else {
shares = (_amount.mul(_totalSupply)).div(pool);
}
pool = calcPoolValueInToken();
_mint(msg.sender, shares);
}
// Converts DAI to ETH and returns how much ETH has been received from Uniswap
function daiToETH(uint256 _amount) internal returns(uint256) {
IERC20(dai).safeApprove(uniswapRouter, 0);
IERC20(dai).safeApprove(uniswapRouter, _amount);
address[] memory path = new address[](2);
path[0] = dai;
path[1] = weth;
// swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
// 'amounts' is an array where [0] is input DAI amount and [1] is the resulting ETH after the conversion
// even tho we've specified the WETH address, we'll receive ETH since that's how it works on uniswap
// https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensforeth
uint[] memory amounts = IUniswap(uniswapRouter).swapExactTokensForETH(_amount, uint(0), path, address(this), now.add(1800));
return amounts[1];
}
// Buys YELD tokens paying in ETH on Uniswap and removes them from circulation
// Returns how many YELD tokens have been burned
function buyNBurn(uint256 _ethToSwap) internal returns(uint256) {
address[] memory path = new address[](2);
path[0] = weth;
path[1] = address(yeldToken);
// Burns the tokens by taking them out of circulation, sending them to the 0x0 address
uint[] memory amounts = IUniswap(uniswapRouter).swapExactETHForTokens.value(_ethToSwap)(uint(0), path, address(0), now.add(1800));
return amounts[1];
}
// No rebalance implementation for lower fees and faster swaps
function withdraw(uint256 _shares)
external
nonReentrant
{
require(_shares > 0, "withdraw must be greater than 0");
uint256 ibalance = balanceOf(msg.sender);
require(_shares <= ibalance, "insufficient balance");
pool = calcPoolValueInToken();
uint256 r = (pool.mul(_shares)).div(_totalSupply);
_balances[msg.sender] = _balances[msg.sender].sub(_shares, "redeem amount exceeds balance");
_totalSupply = _totalSupply.sub(_shares, '#1 Total supply sub error');
emit Transfer(msg.sender, address(0), _shares);
uint256 b = IERC20(token).balanceOf(address(this));
if (b < r) {
_withdrawSome(r.sub(b, '#2 Withdraw some sub error'));
}
// Yeld
uint256 generatedYelds = getGeneratedYelds();
uint256 halfProfits = (r.sub(deposits[msg.sender].amount, '#3 Half profits sub error')).div(2);
deposits[msg.sender] = Deposit(deposits[msg.sender].amount.sub(_shares), block.number);
yeldToken.transfer(msg.sender, generatedYelds);
// Take a portion of the profits for the buy and burn and retirement yeld
// Convert half the DAI earned into ETH for the protocol algorithms
if (halfProfits > minimumEffectAmount) {
uint256 stakingProfits = daiToETH(halfProfits);
uint256 tokensAlreadyBurned = yeldToken.balanceOf(address(0));
if (tokensAlreadyBurned < maximumTokensToBurn) {
// 98% is the 49% doubled since we already took the 50%
uint256 ethToSwap = stakingProfits.mul(98).div(100);
// Buy and burn only applies up to 50k tokens burned
buyNBurn(ethToSwap);
// 1% for the Retirement Yield
uint256 retirementYeld = stakingProfits.mul(2).div(100);
// Send to the treasury
retirementYeldTreasury.transfer(retirementYeld);
} else {
// If we've reached the maximum burn point, send half the profits to the treasury to reward holders
uint256 retirementYeld = stakingProfits;
// Send to the treasury
retirementYeldTreasury.transfer(retirementYeld);
}
}
// Yeld
IERC20(token).safeTransfer(msg.sender, r);
pool = calcPoolValueInToken();
}
function recommend() public view returns (Lender) {
(,uint256 capr,uint256 iapr,uint256 aapr,uint256 dapr) = IIEarnManager(apr).recommend(token);
uint256 max = 0;
if (capr > max) {
max = capr;
}
if (iapr > max) {
max = iapr;
}
if (aapr > max) {
max = aapr;
}
if (dapr > max) {
max = dapr;
}
Lender newProvider = Lender.NONE;
if (max == capr) {
newProvider = Lender.COMPOUND;
} else if (max == iapr) {
newProvider = Lender.FULCRUM;
} else if (max == aapr) {
newProvider = Lender.AAVE;
} else if (max == dapr) {
newProvider = Lender.DYDX;
}
return newProvider;
}
function getAave() public view returns (address) {
return LendingPoolAddressesProvider(aave).getLendingPool();
}
function getAaveCore() public view returns (address) {
return LendingPoolAddressesProvider(aave).getLendingPoolCore();
}
function approveToken() public {
IERC20(token).safeApprove(compound, uint(-1));
IERC20(token).safeApprove(dydx, uint(-1));
IERC20(token).safeApprove(getAaveCore(), uint(-1));
IERC20(token).safeApprove(fulcrum, uint(-1));
}
function balance() public view returns (uint256) {
return IERC20(token).balanceOf(address(this));
}
function balanceDydxAvailable() public view returns (uint256) {
return IERC20(token).balanceOf(dydx);
}
function balanceDydx() public view returns (uint256) {
Wei memory bal = DyDx(dydx).getAccountWei(Info(address(this), 0), dToken);
return bal.value;
}
function balanceCompound() public view returns (uint256) {
return IERC20(compound).balanceOf(address(this));
}
function balanceCompoundInToken() public view returns (uint256) {
// Mantisa 1e18 to decimals
uint256 b = balanceCompound();
if (b > 0) {
b = b.mul(Compound(compound).exchangeRateStored()).div(1e18);
}
return b;
}
function balanceFulcrumAvailable() public view returns (uint256) {
return IERC20(chai).balanceOf(fulcrum);
}
function balanceFulcrumInToken() public view returns (uint256) {
uint256 b = balanceFulcrum();
if (b > 0) {
b = Fulcrum(fulcrum).assetBalanceOf(address(this));
}
return b;
}
function balanceFulcrum() public view returns (uint256) {
return IERC20(fulcrum).balanceOf(address(this));
}
function balanceAaveAvailable() public view returns (uint256) {
return IERC20(token).balanceOf(aavePool);
}
function balanceAave() public view returns (uint256) {
return IERC20(aaveToken).balanceOf(address(this));
}
function rebalance() public {
Lender newProvider = recommend();
if (newProvider != provider) {
_withdrawAll();
}
if (balance() > 0) {
if (newProvider == Lender.DYDX) {
_supplyDydx(balance());
} else if (newProvider == Lender.FULCRUM) {
_supplyFulcrum(balance());
} else if (newProvider == Lender.COMPOUND) {
_supplyCompound(balance());
} else if (newProvider == Lender.AAVE) {
_supplyAave(balance());
}
}
provider = newProvider;
}
function _withdrawAll() internal {
uint256 amount = balanceCompound();
if (amount > 0) {
_withdrawSomeCompound(balanceCompoundInToken().sub(1));
}
amount = balanceDydx();
if (amount > 0) {
if (amount > balanceDydxAvailable()) {
amount = balanceDydxAvailable();
}
_withdrawDydx(amount);
}
amount = balanceFulcrum();
if (amount > 0) {
if (amount > balanceFulcrumAvailable().sub(1)) {
amount = balanceFulcrumAvailable().sub(1);
}
_withdrawSomeFulcrum(amount);
}
amount = balanceAave();
if (amount > 0) {
if (amount > balanceAaveAvailable()) {
amount = balanceAaveAvailable();
}
_withdrawAave(amount);
}
}
function _withdrawSomeCompound(uint256 _amount) internal {
uint256 b = balanceCompound();
uint256 bT = balanceCompoundInToken();
require(bT >= _amount, "insufficient funds");
// can have unintentional rounding errors
uint256 amount = (b.mul(_amount)).div(bT).add(1);
_withdrawCompound(amount);
}
function _withdrawSomeFulcrum(uint256 _amount) internal {
uint256 b = balanceFulcrum();
uint256 bT = balanceFulcrumInToken();
require(bT >= _amount, "insufficient funds");
// can have unintentional rounding errors
uint256 amount = (b.mul(_amount)).div(bT).add(1);
_withdrawFulcrum(amount);
}
function _withdrawSome(uint256 _amount) internal returns (bool) {
uint256 origAmount = _amount;
uint256 amount = balanceCompound();
if (amount > 0) {
if (_amount > balanceCompoundInToken().sub(1)) {
_withdrawSomeCompound(balanceCompoundInToken().sub(1));
_amount = origAmount.sub(IERC20(token).balanceOf(address(this)));
} else {
_withdrawSomeCompound(_amount);
return true;
}
}
amount = balanceDydx();
if (amount > 0) {
if (_amount > balanceDydxAvailable()) {
_withdrawDydx(balanceDydxAvailable());
_amount = origAmount.sub(IERC20(token).balanceOf(address(this)));
} else {
_withdrawDydx(_amount);
return true;
}
}
amount = balanceFulcrum();
if (amount > 0) {
if (_amount > balanceFulcrumAvailable().sub(1)) {
amount = balanceFulcrumAvailable().sub(1);
_withdrawSomeFulcrum(balanceFulcrumAvailable().sub(1));
_amount = origAmount.sub(IERC20(token).balanceOf(address(this)));
} else {
_withdrawSomeFulcrum(amount);
return true;
}
}
amount = balanceAave();
if (amount > 0) {
if (_amount > balanceAaveAvailable()) {
_withdrawAave(balanceAaveAvailable());
_amount = origAmount.sub(IERC20(token).balanceOf(address(this)));
} else {
_withdrawAave(_amount);
return true;
}
}
return true;
}
function _supplyDydx(uint256 amount) internal {
Info[] memory infos = new Info[](1);
infos[0] = Info(address(this), 0);
AssetAmount memory amt = AssetAmount(true, AssetDenomination.Wei, AssetReference.Delta, amount);
ActionArgs memory act;
act.actionType = ActionType.Deposit;
act.accountId = 0;
act.amount = amt;
act.primaryMarketId = dToken;
act.otherAddress = address(this);
ActionArgs[] memory args = new ActionArgs[](1);
args[0] = act;
DyDx(dydx).operate(infos, args);
}
function _supplyAave(uint amount) internal {
Aave(getAave()).deposit(token, amount, 0);
}
function _supplyFulcrum(uint amount) internal {
require(Fulcrum(fulcrum).mint(address(this), amount) > 0, "FULCRUM: supply failed");
}
function _supplyCompound(uint amount) internal {
require(Compound(compound).mint(amount) == 0, "COMPOUND: supply failed");
}
function _withdrawAave(uint amount) internal {
AToken(aaveToken).redeem(amount);
}
function _withdrawFulcrum(uint amount) internal {
require(Fulcrum(fulcrum).burn(address(this), amount) > 0, "FULCRUM: withdraw failed");
}
function _withdrawCompound(uint amount) internal {
require(Compound(compound).redeem(amount) == 0, "COMPOUND: withdraw failed");
}
function _withdrawDydx(uint256 amount) internal {
Info[] memory infos = new Info[](1);
infos[0] = Info(address(this), 0);
AssetAmount memory amt = AssetAmount(false, AssetDenomination.Wei, AssetReference.Delta, amount);
ActionArgs memory act;
act.actionType = ActionType.Withdraw;
act.accountId = 0;
act.amount = amt;
act.primaryMarketId = dToken;
act.otherAddress = address(this);
ActionArgs[] memory args = new ActionArgs[](1);
args[0] = act;
DyDx(dydx).operate(infos, args);
}
function calcPoolValueInToken() public view returns (uint) {
return balanceCompoundInToken()
.add(balanceFulcrumInToken())
.add(balanceDydx())
.add(balanceAave())
.add(balance());
}
function getPricePerFullShare() public view returns (uint) {
uint _pool = calcPoolValueInToken();
return _pool.mul(1e18).div(_totalSupply);
}
} |
uint256 blocksPassed;
if (deposits[msg.sender].start > 0) {
blocksPassed = block.number.sub(deposits[msg.sender].start);
} else {
blocksPassed = 0;
}
// This will work because amount is a token with 18 decimals
// Take the deposit, reduce it by 1 million (by removing 6 zeroes) so you get 1
// That 1 means get 1 YELD per day (in blocks). Now multiply that 1 by 100 to get 100 YELD per day
// your deposits in dai div by 1 million * by yeld to reward / 1e18 since yeldToReward is in 18 decimals to be able to provide a smaller price since
// we can't go below 1 in a variable. You can't make the price 0.00001 that's why we need that 1e18 padding
uint256 generatedYelds = deposits[msg.sender].amount.div(oneMillion).mul(yeldToRewardPerDay.div(1e18)).mul(blocksPassed).div(oneDayInBlocks);
return generatedYelds;
| function getGeneratedYelds() public view returns(uint256) | function getGeneratedYelds() public view returns(uint256) |
20942 | Ownable | null | contract Ownable {
address public owner;
address public pendingOwner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {<FILL_FUNCTION_BODY> }
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "onlyOwner");
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public {
require(msg.sender == pendingOwner, "onlyPendingOwner");
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
} | contract Ownable {
address public owner;
address public pendingOwner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
<FILL_FUNCTION>
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "onlyOwner");
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public {
require(msg.sender == pendingOwner, "onlyPendingOwner");
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
} |
owner = msg.sender;
| constructor() public | /**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public |
19576 | MulaCoin | transferFrom | contract MulaCoin is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function MulaCoin() public {
symbol = "MULA";
name = "MulaCoin";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[0x9e715ef5BDBfB6a3FbB9C554d6Ad46A2674fDA0D] = _totalSupply;
Transfer(address(0), 0x9e715ef5BDBfB6a3FbB9C554d6Ad46A2674fDA0D, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> }
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | contract MulaCoin is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function MulaCoin() public {
symbol = "MULA";
name = "MulaCoin";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[0x9e715ef5BDBfB6a3FbB9C554d6Ad46A2674fDA0D] = _totalSupply;
Transfer(address(0), 0x9e715ef5BDBfB6a3FbB9C554d6Ad46A2674fDA0D, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
<FILL_FUNCTION>
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} |
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
| function transferFrom(address from, address to, uint tokens) public returns (bool success) | // ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) |
77070 | RolePlusLoot | tokenURI | contract RolePlusLoot is ERC721Enumerable, Ownable {
address roleAddr=0xCd4D337554862F9bC9ffffB67465B7d643E4E3ad;
address petsAddr=0x997020483A30678436E76c08a65BBeCbE69Bf704;
address lootAddr=0xFF9C1b15B16263C61d017ee9F65C50e4AE0113D7;
address mlootAddr=0x1dfe7Ca09e99d10835Bf73044a23B73Fc20623DF;
struct Data {
uint roleId;
uint lootId;
string url;
}
mapping(uint => Data) public tokenData;
constructor() ERC721("Role+Loot", "RPL") Ownable() {
}
function stringCompare(string memory a, string memory b) public pure returns (bool) {
if (bytes(a).length != bytes(b).length) {
return false;
} else {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
function tokenURI(uint tokenId) override public view returns (string memory) {<FILL_FUNCTION_BODY> }
function getUrl(uint tokenId, uint roleId) public view returns(string memory){
string memory prefix = "https://ipfs.io/ipfs/QmSLhQXyNgNL6JCq1Vvy3Dhun9Ewar2fr7tfMNtwKX2qzh/";
string memory suffix = ".svg";
if(!stringCompare(tokenData[tokenId].url, "")){
return tokenData[tokenId].url;
}
string memory race = Role(roleAddr).getRace(roleId);
string memory gender = Role(roleAddr).getGender(roleId);
string memory raceId;
if(stringCompare(race, "Human")){
raceId = "0";
}else if(stringCompare(race, "Elf")){
raceId = "1";
}else if(stringCompare(race, "Orc")){
raceId = "2";
}else if(stringCompare(race, "Undead")){
raceId = "3";
}else if(stringCompare(race, "Demons")){
raceId = "4";
}else{
raceId = "5";
}
string memory genderId;
if(stringCompare(gender, "Female")){
genderId = "1";
}
return string(abi.encodePacked(prefix, raceId, genderId, suffix));
}
function makeAttributeParts(uint lootId, uint roleId, uint petId) internal view returns (string memory){
address _lootAddr = lootAddr;
if(lootId > 8000){
_lootAddr = mlootAddr;
}
string[25] memory a;
a[0] = '[{ "trait_type": "RoleAlignment", "value": "';
a[1] = Role(roleAddr).getAlignment(roleId);
a[2] = '" }, { "trait_type": "RoleOccupation", "value": "';
a[3] = Role(roleAddr).getOccupation(roleId);
a[4] = '" }, { "trait_type": "PetAlignment", "value": "';
a[5] = Pets(petsAddr).getAlignment(petId);
a[6] = '" }, { "trait_type": "PetSpecies", "value": "';
a[7] = Pets(petsAddr).getSpecies(petId);
a[8] = '" }, { "trait_type": "Chest", "value": "';
a[9] = Loot(_lootAddr).getChest(lootId);
a[10] = '" }, { "trait_type": "Foot", "value": "';
a[11] = Loot(_lootAddr).getFoot(lootId);
a[12] = '" }, { "trait_type": "Hand", "value": "';
a[13] = Loot(_lootAddr).getHand(lootId);
a[14] = '" }, { "trait_type": "Head", "value": "';
a[15] = Loot(_lootAddr).getHead(lootId);
a[16] = '" }, { "trait_type": "Neck", "value": "';
a[17] = Loot(_lootAddr).getNeck(lootId);
a[18] = '" }, { "trait_type": "Ring", "value": "';
a[19] = Loot(_lootAddr).getRing(lootId);
a[20] = '" }, { "trait_type": "Waist", "value": "';
a[21] = Loot(_lootAddr).getWaist(lootId);
a[22] = '" }, { "trait_type": "Weapon", "value": "';
a[23] = Loot(_lootAddr).getWeapon(lootId);
a[24] = '" }]';
string memory output = string(abi.encodePacked(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]));
output = string(abi.encodePacked(output, a[9], a[10], a[11], a[12], a[13], a[14], a[15], a[16]));
output = string(abi.encodePacked(output, a[17], a[18], a[19], a[20], a[21], a[22], a[23], a[24]));
return output;
}
function claim(uint lootId, uint petId, uint roleId, string memory imageUrl) public {
require(!_exists(petId), "Token ID invalid");
require(Pets(petsAddr).ownerOf(petId) == _msgSender(), "not pet owner");
require(Role(roleAddr).ownerOf(roleId) == _msgSender(), "not role owner");
if(lootId > 8000){
require(Loot(mlootAddr).ownerOf(lootId) == _msgSender(), "not mloot owner");
}else{
require(Loot(lootAddr).ownerOf(lootId) == _msgSender(), "not loot owner");
}
_safeMint(_msgSender(), petId);
tokenData[petId] = Data(roleId, lootId, imageUrl);
}
function setImageUrl(uint tokenId, string memory imageUrl) public{
require(_exists(tokenId), "ID invalid");
require(ownerOf(tokenId) == _msgSender(), "not owner");
tokenData[tokenId].url = imageUrl;
}
function toString(uint value) public pure returns (string memory) {
// 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";
}
uint temp = value;
uint digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint(value % 10)));
value /= 10;
}
return string(buffer);
}
} | contract RolePlusLoot is ERC721Enumerable, Ownable {
address roleAddr=0xCd4D337554862F9bC9ffffB67465B7d643E4E3ad;
address petsAddr=0x997020483A30678436E76c08a65BBeCbE69Bf704;
address lootAddr=0xFF9C1b15B16263C61d017ee9F65C50e4AE0113D7;
address mlootAddr=0x1dfe7Ca09e99d10835Bf73044a23B73Fc20623DF;
struct Data {
uint roleId;
uint lootId;
string url;
}
mapping(uint => Data) public tokenData;
constructor() ERC721("Role+Loot", "RPL") Ownable() {
}
function stringCompare(string memory a, string memory b) public pure returns (bool) {
if (bytes(a).length != bytes(b).length) {
return false;
} else {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
<FILL_FUNCTION>
function getUrl(uint tokenId, uint roleId) public view returns(string memory){
string memory prefix = "https://ipfs.io/ipfs/QmSLhQXyNgNL6JCq1Vvy3Dhun9Ewar2fr7tfMNtwKX2qzh/";
string memory suffix = ".svg";
if(!stringCompare(tokenData[tokenId].url, "")){
return tokenData[tokenId].url;
}
string memory race = Role(roleAddr).getRace(roleId);
string memory gender = Role(roleAddr).getGender(roleId);
string memory raceId;
if(stringCompare(race, "Human")){
raceId = "0";
}else if(stringCompare(race, "Elf")){
raceId = "1";
}else if(stringCompare(race, "Orc")){
raceId = "2";
}else if(stringCompare(race, "Undead")){
raceId = "3";
}else if(stringCompare(race, "Demons")){
raceId = "4";
}else{
raceId = "5";
}
string memory genderId;
if(stringCompare(gender, "Female")){
genderId = "1";
}
return string(abi.encodePacked(prefix, raceId, genderId, suffix));
}
function makeAttributeParts(uint lootId, uint roleId, uint petId) internal view returns (string memory){
address _lootAddr = lootAddr;
if(lootId > 8000){
_lootAddr = mlootAddr;
}
string[25] memory a;
a[0] = '[{ "trait_type": "RoleAlignment", "value": "';
a[1] = Role(roleAddr).getAlignment(roleId);
a[2] = '" }, { "trait_type": "RoleOccupation", "value": "';
a[3] = Role(roleAddr).getOccupation(roleId);
a[4] = '" }, { "trait_type": "PetAlignment", "value": "';
a[5] = Pets(petsAddr).getAlignment(petId);
a[6] = '" }, { "trait_type": "PetSpecies", "value": "';
a[7] = Pets(petsAddr).getSpecies(petId);
a[8] = '" }, { "trait_type": "Chest", "value": "';
a[9] = Loot(_lootAddr).getChest(lootId);
a[10] = '" }, { "trait_type": "Foot", "value": "';
a[11] = Loot(_lootAddr).getFoot(lootId);
a[12] = '" }, { "trait_type": "Hand", "value": "';
a[13] = Loot(_lootAddr).getHand(lootId);
a[14] = '" }, { "trait_type": "Head", "value": "';
a[15] = Loot(_lootAddr).getHead(lootId);
a[16] = '" }, { "trait_type": "Neck", "value": "';
a[17] = Loot(_lootAddr).getNeck(lootId);
a[18] = '" }, { "trait_type": "Ring", "value": "';
a[19] = Loot(_lootAddr).getRing(lootId);
a[20] = '" }, { "trait_type": "Waist", "value": "';
a[21] = Loot(_lootAddr).getWaist(lootId);
a[22] = '" }, { "trait_type": "Weapon", "value": "';
a[23] = Loot(_lootAddr).getWeapon(lootId);
a[24] = '" }]';
string memory output = string(abi.encodePacked(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]));
output = string(abi.encodePacked(output, a[9], a[10], a[11], a[12], a[13], a[14], a[15], a[16]));
output = string(abi.encodePacked(output, a[17], a[18], a[19], a[20], a[21], a[22], a[23], a[24]));
return output;
}
function claim(uint lootId, uint petId, uint roleId, string memory imageUrl) public {
require(!_exists(petId), "Token ID invalid");
require(Pets(petsAddr).ownerOf(petId) == _msgSender(), "not pet owner");
require(Role(roleAddr).ownerOf(roleId) == _msgSender(), "not role owner");
if(lootId > 8000){
require(Loot(mlootAddr).ownerOf(lootId) == _msgSender(), "not mloot owner");
}else{
require(Loot(lootAddr).ownerOf(lootId) == _msgSender(), "not loot owner");
}
_safeMint(_msgSender(), petId);
tokenData[petId] = Data(roleId, lootId, imageUrl);
}
function setImageUrl(uint tokenId, string memory imageUrl) public{
require(_exists(tokenId), "ID invalid");
require(ownerOf(tokenId) == _msgSender(), "not owner");
tokenData[tokenId].url = imageUrl;
}
function toString(uint value) public pure returns (string memory) {
// 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";
}
uint temp = value;
uint digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint(value % 10)));
value /= 10;
}
return string(buffer);
}
} |
Data memory data = tokenData[tokenId];
uint roleId = data.roleId;
uint lootId = data.lootId;
address _lootAddr = lootAddr;
if(lootId > 8000){
_lootAddr = mlootAddr;
}
string[45] memory p;
p[0] = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 350 350"><defs><style>.cls-1,.cls-7{fill:none;}.cls-2{clip-path:url(#clip-path);}.cls-3{fill:#fff;}.cls-4{fill:#e2e2e2;}.cls-5{fill:#4d4d4d;}.cls-10,.cls-11,.cls-13,.cls-15,.cls-16,.cls-6{fill:#3a3a3a;}.cls-7{stroke:#3a3a3a;}.cls-8{fill:#898989;opacity:0.5;}.cls-9{fill:#515151;}.cls-10{font-size:8px;font-family:MicrosoftYaHeiLight, Microsoft YaHei;}.cls-11{opacity:0.58;font-size:21px;}.cls-11,.cls-13,.cls-15{font-family:MicrosoftYaHei-Bold, Microsoft YaHei;}.cls-11,.cls-12,.cls-13,.cls-14,.cls-15,.cls-16{font-weight:700;}.cls-12{font-size:48px;fill:#262626;}.cls-12,.cls-14,.cls-16{font-family:Arial-BoldMT, Arial;}.cls-13{opacity:0.63;font-size:14px;}.cls-13,.cls-14{letter-spacing:-0.03em;}.cls-14{opacity:0.8;fill:#232323;}.cls-14,.cls-16{font-size:28px;}.cls-15{opacity:0.4;font-size:10px;}.cls-16{opacity:0.68;}</style><clipPath id="clip-path"><rect class="cls-1" width="350" height="350"/></clipPath></defs><g class="cls-2"><g id="role"><rect class="cls-3" width="350" height="350"/><rect class="cls-4" width="350" height="350"/><image x="12%" y="10" height="330" xlink:href="';
p[1] = getUrl(tokenId, roleId);
p[2] = '" /><image x="60%" y="250" width="40%" xlink:href="https://ipfs.io/ipfs/QmSLhQXyNgNL6JCq1Vvy3Dhun9Ewar2fr7tfMNtwKX2qzh/pet.svg" /><path class="cls-5" d="M33.71,12.44a7.39,7.39,0,0,1-5.23-2.16L26,7.81a1.06,1.06,0,0,0-.77-.32v3.67a1.07,1.07,0,0,1,1.07,1.07v1.2a1.88,1.88,0,0,0,1.88,1.87h.64a1.07,1.07,0,1,1,0,2.13h-.64a1.89,1.89,0,0,0-1.87,1.88V26.8a1.08,1.08,0,0,1-1.07,1.07v3.67A9.54,9.54,0,0,0,34.81,22V13.51A1.09,1.09,0,0,0,33.71,12.44Z"/><path class="cls-5" d="M25.26,27.85a1.07,1.07,0,0,1-1.06-1.06v-7.5a1.88,1.88,0,0,0-1.88-1.87h-.64a1.07,1.07,0,0,1,0-2.14h.64A1.88,1.88,0,0,0,24.2,13.4V12.2a1.07,1.07,0,0,1,1.06-1.06V7.49a1.05,1.05,0,0,0-.76.32L22,10.28a7.33,7.33,0,0,1-5.23,2.16,1.08,1.08,0,0,0-1.08,1.09V22a9.54,9.54,0,0,0,9.54,9.54V27.85Z"/><rect class="cls-6" y="265" width="18" height="42"/><line class="cls-7" x1="18" y1="265.5" x2="95.5" y2="265.5"/><line class="cls-7" x1="18" y1="306.5" x2="181.5" y2="306.5"/><g><rect class="cls-8" x="248" y="251" width="91" height="17"/></g><g><rect class="cls-8" x="248" y="270" width="91" height="17"/></g><g><rect class="cls-8" x="248" y="289" width="91" height="17"/></g><g><rect class="cls-8" x="248" y="308" width="91" height="17"/></g><g><rect class="cls-8" x="248" y="327" width="91" height="17"/></g><g><rect class="cls-8" x="11" y="152" width="88" height="17"/></g><g><rect class="cls-8" x="11" y="174" width="88" height="17"/></g><g><rect class="cls-8" x="11" y="196" width="88" height="17"/></g><g><rect class="cls-8" x="11" y="218" width="88" height="17"/></g><g><rect class="cls-8" x="11" y="240" width="88" height="17"/></g><rect class="cls-8" x="248" y="12" width="91" height="20"/><rect class="cls-8" x="248" y="36" width="91" height="20"/><rect class="cls-8" x="248" y="60" width="91" height="20"/><rect class="cls-8" x="248" y="84" width="91" height="20"/><rect class="cls-8" x="248" y="108" width="91" height="20"/><rect class="cls-8" x="248" y="132" width="91" height="20"/><rect class="cls-8" x="248" y="156" width="91" height="20"/><rect class="cls-8" x="248" y="180" width="91" height="20"/><path class="cls-5" d="M12.11,36.17l.5,64.53h-1l-.51-64.56Zm.49,63.45.32,42.16-1,0-.33-42.18Z"/><path class="cls-9" d="M292.12,227.66l40.42-.3,0,1-40.45.3Z"/></g></g><text class="cls-10" transform="translate(15.94 164.08)">';
p[3] = Role(roleAddr).getAlignment(roleId);
p[4] = '</text><text class="cls-10" transform="translate(254.2 24.56)">';
p[5] = Loot(_lootAddr).getChest(lootId);
p[6] = '</text><text class="cls-10" transform="translate(254.2 48.5)">';
p[7] = Loot(_lootAddr).getFoot(lootId);
p[8] = '</text><text class="cls-10" transform="translate(254.2 72.28)">';
p[9] = Loot(_lootAddr).getHand(lootId);
p[10] = '</text><text class="cls-10" transform="translate(254.2 97.22)">';
p[11] = Loot(_lootAddr).getHead(lootId);
p[12] = '</text><text class="cls-10" transform="translate(254.2 120.67)">';
p[13] = Loot(_lootAddr).getNeck(lootId);
p[14] = '</text><text class="cls-10" transform="translate(254.2 144.72)">';
p[15] = Loot(_lootAddr).getRing(lootId);
p[16] = '</text><text class="cls-10" transform="translate(254.2 169)">';
p[17] = Loot(_lootAddr).getWaist(lootId);
p[18] = '</text><text class="cls-10" transform="translate(254.2 193.05)">';
p[19] = Loot(_lootAddr).getWeapon(lootId);
p[20] = '</text><text class="cls-10" transform="translate(254.2 263.46)">';
p[21] = Pets(petsAddr).getAlignment(tokenId);
p[22] = '</text><text class="cls-10" transform="translate(254.2 281.13)">';
p[23] = Pets(petsAddr).getSpecies(tokenId);
p[24] = '</text><text class="cls-10" transform="translate(254.2 300.61)">';
p[25] = Pets(petsAddr).getTrait(tokenId, 1);
p[26] = '</text><text class="cls-10" transform="translate(254.2 319.26)">';
p[27] = Pets(petsAddr).getTrait(tokenId, 2);
p[28] = '</text><text class="cls-10" transform="translate(254.2 339.08)">';
p[29] = Pets(petsAddr).getTrait(tokenId, 3);
p[30] = '</text><text class="cls-10" transform="translate(15.94 185.66)">';
p[31] = Role(roleAddr).getOccupation(roleId);
p[32] = '</text><text class="cls-10" transform="translate(15.94 207.7)">';
p[33] = Role(roleAddr).getTrait1(roleId);
p[34] = '</text><text class="cls-10" transform="translate(15.94 229.94)">';
p[35] = Role(roleAddr).getTrait2(roleId);
p[36] = '</text><text class="cls-10" transform="translate(15.94 251.62)">';
p[37] = Role(roleAddr).getTrait3(roleId);
p[38] = '</text><text class="cls-11" transform="translate(136.13 303.28)">';
p[39] = toString(roleId);
p[40] = '</text><text class="cls-12" transform="translate(21.56 304.54)">Role</text><text class="cls-13" transform="translate(19.68 100.41) rotate(90)">';
p[41] = toString(lootId);
p[42] = '</text><text class="cls-14" transform="translate(19.32 35.87) rotate(90)">Loot</text><text class="cls-15" transform="translate(293.48 238.74)">';
p[43] = toString(tokenId);
p[44] = '</text><text class="cls-16" transform="translate(288.63 223.13)">Pet</text></svg>';
string memory output = string(abi.encodePacked(p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8]));
output = string(abi.encodePacked(output, p[9], p[10], p[11], p[12], p[13], p[14], p[15], p[16]));
output = string(abi.encodePacked(output, p[17], p[18], p[19], p[20], p[21], p[22], p[23], p[24]));
output = string(abi.encodePacked(output, p[25], p[26], p[27], p[28], p[29], p[30], p[31], p[32]));
output = string(abi.encodePacked(output, p[33], p[34], p[35], p[36], p[37], p[38], p[39], p[40]));
output = string(abi.encodePacked(output, p[41], p[42], p[43], p[44]));
string memory atrrOutput = makeAttributeParts(lootId, roleId, tokenId);
string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Role+Loot #', toString(tokenId), '", "description": "Combine Loot/mLoot, Role and Pet. Get Role+, the key to the New World.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"', ',"attributes":', atrrOutput, '}'))));
output = string(abi.encodePacked('data:application/json;base64,', json));
return output;
| function tokenURI(uint tokenId) override public view returns (string memory) | function tokenURI(uint tokenId) override public view returns (string memory) |
18768 | ERC20Token | approve | contract ERC20Token is Token
{
function transfer(address _to, uint256 _value) returns (bool success)
{
//По-умолчанию предполагается, что totalSupply не может быть больше (2^256 - 1).
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success)
{
//По-умолчанию предполагается, что totalSupply не может быть больше (2^256 - 1).
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance)
{
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success)
{<FILL_FUNCTION_BODY> }
function allowance(address _owner, address _spender) constant returns (uint256 remaining)
{
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
} | contract ERC20Token is Token
{
function transfer(address _to, uint256 _value) returns (bool success)
{
//По-умолчанию предполагается, что totalSupply не может быть больше (2^256 - 1).
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success)
{
//По-умолчанию предполагается, что totalSupply не может быть больше (2^256 - 1).
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance)
{
return balances[_owner];
}
<FILL_FUNCTION>
function allowance(address _owner, address _spender) constant returns (uint256 remaining)
{
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
} |
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
| function approve(address _spender, uint256 _value) returns (bool success)
| function approve(address _spender, uint256 _value) returns (bool success)
|
41306 | Forwarder | flush | contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
this.flush();
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, "Only Parent");
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), "Already initialized");
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
this.flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
this.flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
require(
instance.transfer(parentAddress, forwarderBalance),
"Token flush failed"
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() external {<FILL_FUNCTION_BODY> }
} | contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
this.flush();
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, "Only Parent");
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), "Already initialized");
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
this.flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
this.flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
require(
instance.transfer(parentAddress, forwarderBalance),
"Token flush failed"
);
}
<FILL_FUNCTION>
} |
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }("");
require(success, "Flush failed");
emit ForwarderDeposited(msg.sender, value, msg.data);
| function flush() external | /**
* Flush the entire balance of the contract to the parent address.
*/
function flush() external |
8897 | AICrypto | transfer | contract AICrypto {
string public name = "AICrypto"; // token name
string public symbol = "ATC"; // token symbol
uint256 public decimals = 8; // token digit
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
uint256 public totalSupply = 0;
bool public stopped = false;
uint256 constant valueFounder = 8*10**15;
address owner = 0x0133B1D86f6674640FbfE6dD524b6Db43B37ea58;
modifier isOwner {
assert(owner == msg.sender);
_;
}
modifier isRunning {
assert (!stopped);
_;
}
modifier validAddress {
assert(0x0133B1D86f6674640FbfE6dD524b6Db43B37ea58 != msg.sender);
_;
}
function AICrypto(address _addressFounder) {
owner = msg.sender;
totalSupply = valueFounder;
balanceOf[_addressFounder] = valueFounder;
Transfer(0x0133B1D86f6674640FbfE6dD524b6Db43B37ea58, _addressFounder, valueFounder);
}
function transfer(address _to, uint256 _value) isRunning validAddress returns (bool success) {<FILL_FUNCTION_BODY> }
function transferFrom(address _from, address _to, uint256 _value) isRunning validAddress returns (bool success) {
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
require(allowance[_from][msg.sender] >= _value);
balanceOf[_to] += _value;
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) isRunning validAddress returns (bool success) {
require(_value == 0 || allowance[msg.sender][_spender] == 0);
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function stop() isOwner {
stopped = true;
}
function start() isOwner {
stopped = false;
}
function setName(string _name) isOwner {
name = _name;
}
function burn(uint256 _value) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
balanceOf[0x0133B1D86f6674640FbfE6dD524b6Db43B37ea58] += _value;
Transfer(msg.sender, 0x0133B1D86f6674640FbfE6dD524b6Db43B37ea58, _value);
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | contract AICrypto {
string public name = "AICrypto"; // token name
string public symbol = "ATC"; // token symbol
uint256 public decimals = 8; // token digit
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
uint256 public totalSupply = 0;
bool public stopped = false;
uint256 constant valueFounder = 8*10**15;
address owner = 0x0133B1D86f6674640FbfE6dD524b6Db43B37ea58;
modifier isOwner {
assert(owner == msg.sender);
_;
}
modifier isRunning {
assert (!stopped);
_;
}
modifier validAddress {
assert(0x0133B1D86f6674640FbfE6dD524b6Db43B37ea58 != msg.sender);
_;
}
function AICrypto(address _addressFounder) {
owner = msg.sender;
totalSupply = valueFounder;
balanceOf[_addressFounder] = valueFounder;
Transfer(0x0133B1D86f6674640FbfE6dD524b6Db43B37ea58, _addressFounder, valueFounder);
}
<FILL_FUNCTION>
function transferFrom(address _from, address _to, uint256 _value) isRunning validAddress returns (bool success) {
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
require(allowance[_from][msg.sender] >= _value);
balanceOf[_to] += _value;
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) isRunning validAddress returns (bool success) {
require(_value == 0 || allowance[msg.sender][_spender] == 0);
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function stop() isOwner {
stopped = true;
}
function start() isOwner {
stopped = false;
}
function setName(string _name) isOwner {
name = _name;
}
function burn(uint256 _value) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
balanceOf[0x0133B1D86f6674640FbfE6dD524b6Db43B37ea58] += _value;
Transfer(msg.sender, 0x0133B1D86f6674640FbfE6dD524b6Db43B37ea58, _value);
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} |
require(balanceOf[msg.sender] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
| function transfer(address _to, uint256 _value) isRunning validAddress returns (bool success) | function transfer(address _to, uint256 _value) isRunning validAddress returns (bool success) |
31557 | BitHaus | BitHaus | contract BitHaus is StandardToken {
string constant public name = "BitHaus";
string constant public symbol = "BTH";
uint8 constant public decimals = 8;
function () {
throw;
}
function BitHaus() {<FILL_FUNCTION_BODY> }
} | contract BitHaus is StandardToken {
string constant public name = "BitHaus";
string constant public symbol = "BTH";
uint8 constant public decimals = 8;
function () {
throw;
}
<FILL_FUNCTION>
} |
balances[msg.sender] = 10000000000000000;
totalSupply = 10000000000000000; //
| function BitHaus() | function BitHaus() |
94000 | ERC1155 | safeTransferFrom | contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using SafeMath for uint256;
using Address for address;
using Strings for uint256;
// Mapping from token ID to account balances
mapping (uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/*
* bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e
* bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a
* bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6
*
* => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^
* 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26
*/
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
/*
* bytes4(keccak256('uri(uint256)')) == 0x0e89341c
*/
bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
/**
* @dev See {_setURI}.
*/
constructor (string memory __uri) {
_setURI(__uri);
// register the supported interfaces to conform to ERC1155 via ERC165
_registerInterface(_INTERFACE_ID_ERC1155);
// register the supported interfaces to conform to ERC1155MetadataURI via ERC165
_registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256 tokenId) external view override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
require(accounts[i] != address(0), "ERC1155: batch balance query for the zero address");
batchBalances[i] = _balances[ids[i]][accounts[i]];
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
override
{<FILL_FUNCTION_BODY> }
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
public
virtual
override
{
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
_balances[id][from] = _balances[id][from].sub(
amount,
"ERC1155: insufficient balance for transfer"
);
_balances[id][to] = _balances[id][to].add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] = _balances[id][account].add(amount);
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(address account, uint256 id, uint256 amount) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
_balances[id][account] = _balances[id][account].sub(
amount,
"ERC1155: burn amount exceeds balance"
);
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(
amounts[i],
"ERC1155: burn amount exceeds balance"
);
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal virtual
{ }
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
} | contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using SafeMath for uint256;
using Address for address;
using Strings for uint256;
// Mapping from token ID to account balances
mapping (uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/*
* bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e
* bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a
* bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6
*
* => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^
* 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26
*/
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
/*
* bytes4(keccak256('uri(uint256)')) == 0x0e89341c
*/
bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
/**
* @dev See {_setURI}.
*/
constructor (string memory __uri) {
_setURI(__uri);
// register the supported interfaces to conform to ERC1155 via ERC165
_registerInterface(_INTERFACE_ID_ERC1155);
// register the supported interfaces to conform to ERC1155MetadataURI via ERC165
_registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256 tokenId) external view override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
require(accounts[i] != address(0), "ERC1155: batch balance query for the zero address");
batchBalances[i] = _balances[ids[i]][accounts[i]];
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view override returns (bool) {
return _operatorApprovals[account][operator];
}
<FILL_FUNCTION>
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
public
virtual
override
{
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
_balances[id][from] = _balances[id][from].sub(
amount,
"ERC1155: insufficient balance for transfer"
);
_balances[id][to] = _balances[id][to].add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] = _balances[id][account].add(amount);
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(address account, uint256 id, uint256 amount) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
_balances[id][account] = _balances[id][account].sub(
amount,
"ERC1155: burn amount exceeds balance"
);
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(
amounts[i],
"ERC1155: burn amount exceeds balance"
);
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal virtual
{ }
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
} |
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
| function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
override
| /**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
override
|
33261 | Tatsutama | _transfer | contract Tatsutama 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 = "Tatsutama";
string private constant _symbol = "Tatsutama";
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(0x437070e28FA29fdD627F51f2f9201a5A4e8cae2C);
_feeAddrWallet2 = payable(0x437070e28FA29fdD627F51f2f9201a5A4e8cae2C);
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_feeAddrWallet1] = true;
_isExcludedFromFee[_feeAddrWallet2] = true;
emit Transfer(address(0x437070e28FA29fdD627F51f2f9201a5A4e8cae2C), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function originalPurchase(address account) public view returns (uint256) {
return _buyMap[account];
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
cooldownEnabled = onoff;
}
function setMaxTx(uint256 maxTransactionAmount) external onlyOwner() {
_maxTxAmount = maxTransactionAmount;
}
function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {<FILL_FUNCTION_BODY> }
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_feeAddrWallet1.transfer(amount.div(2));
_feeAddrWallet2.transfer(amount.div(2));
}
function openTrading() external onlyOwner() {
require(!tradingOpen,"trading is already open");
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
swapEnabled = true;
cooldownEnabled = true;
_maxTxAmount = 20000000000 * 10 ** 9;
tradingOpen = true;
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
}
function setBots(address[] memory bots_) public onlyOwner {
for (uint i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function removeStrictTxLimit() public onlyOwner {
_maxTxAmount = 1e12 * 10**9;
}
function delBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(address sender, address recipient, uint256 amount) private {
_transferStandard(sender, recipient, amount);
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function updateMaxTx (uint256 fee) public onlyOwner {
_maxTxAmount = fee;
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function manualswap() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(TeamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _isBuy(address _sender) private view returns (bool) {
return _sender == uniswapV2Pair;
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
} | contract Tatsutama 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 = "Tatsutama";
string private constant _symbol = "Tatsutama";
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(0x437070e28FA29fdD627F51f2f9201a5A4e8cae2C);
_feeAddrWallet2 = payable(0x437070e28FA29fdD627F51f2f9201a5A4e8cae2C);
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_feeAddrWallet1] = true;
_isExcludedFromFee[_feeAddrWallet2] = true;
emit Transfer(address(0x437070e28FA29fdD627F51f2f9201a5A4e8cae2C), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function originalPurchase(address account) public view returns (uint256) {
return _buyMap[account];
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
cooldownEnabled = onoff;
}
function setMaxTx(uint256 maxTransactionAmount) external onlyOwner() {
_maxTxAmount = maxTransactionAmount;
}
function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
<FILL_FUNCTION>
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_feeAddrWallet1.transfer(amount.div(2));
_feeAddrWallet2.transfer(amount.div(2));
}
function openTrading() external onlyOwner() {
require(!tradingOpen,"trading is already open");
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
swapEnabled = true;
cooldownEnabled = true;
_maxTxAmount = 20000000000 * 10 ** 9;
tradingOpen = true;
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
}
function setBots(address[] memory bots_) public onlyOwner {
for (uint i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function removeStrictTxLimit() public onlyOwner {
_maxTxAmount = 1e12 * 10**9;
}
function delBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(address sender, address recipient, uint256 amount) private {
_transferStandard(sender, recipient, amount);
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function updateMaxTx (uint256 fee) public onlyOwner {
_maxTxAmount = fee;
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function manualswap() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _feeAddrWallet1);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(TeamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _isBuy(address _sender) private view returns (bool) {
return _sender == uniswapV2Pair;
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
} |
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (!_isBuy(from)) {
// TAX SELLERS 30% WHO SELL WITHIN 24 HOURS
if (_buyMap[from] != 0 &&
(_buyMap[from] + (24 hours) >= block.timestamp)) {
_feeAddr1 = 1;
_feeAddr2 = 30;
} else {
_feeAddr1 = 2;
_feeAddr2 = 12;
}
} else {
if (_buyMap[to] == 0) {
_buyMap[to] = block.timestamp;
}
_feeAddr1 = 2;
_feeAddr2 = 12;
}
if (from != owner() && to != owner()) {
require(!bots[from] && !bots[to]);
if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) {
// Cooldown
require(amount <= _maxTxAmount);
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (30 seconds);
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
_tokenTransfer(from,to,amount);
| function _transfer(address from, address to, uint256 amount) private | function _transfer(address from, address to, uint256 amount) private |
27466 | 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));
require(canTransfer(msg.sender));
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) {
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 constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue)
public
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
public
returns (bool success) {<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));
require(canTransfer(msg.sender));
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) {
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 constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue)
public
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
<FILL_FUNCTION>
} |
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 decreaseApproval (address _spender, uint _subtractedValue)
public
returns (bool success) | function decreaseApproval (address _spender, uint _subtractedValue)
public
returns (bool success) |
52298 | BasicToken | transfer | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {<FILL_FUNCTION_BODY> }
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant public returns (uint256 balance) {
return balances[_owner];
}
} | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
<FILL_FUNCTION>
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant public returns (uint256 balance) {
return balances[_owner];
}
} |
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
| function transfer(address _to, uint256 _value) public returns (bool) | function transfer(address _to, uint256 _value) public returns (bool) |
23295 | Token | decreaseApproval | contract Token is Pausable, ERC20 {
using SafeMath for uint;
event Burn(address indexed burner, uint256 value);
mapping(address => uint) balances;
mapping (address => mapping (address => uint)) internal allowed;
mapping(address => uint) public balanceOfLocked;
mapping(address => bool) public addressLocked;
constructor() ERC20("OCP", "OCP", 18) public {
totalSupply = 10000000000 * 10 ** uint(decimals);
balances[msg.sender] = totalSupply;
}
modifier lockCheck(address from, uint value) {
require(addressLocked[from] == false);
require(balances[from] >= balanceOfLocked[from]);
require(value <= balances[from] - balanceOfLocked[from]);
_;
}
function burn(uint _value) onlyOwner public {
balances[owner] = balances[owner].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(msg.sender, _value);
}
function lockAddressValue(address _addr, uint _value) onlyOwner public {
balanceOfLocked[_addr] = _value;
}
function lockAddress(address addr) onlyOwner public {
addressLocked[addr] = true;
}
function unlockAddress(address addr) onlyOwner public {
addressLocked[addr] = false;
}
function transfer(address _to, uint _value) lockCheck(msg.sender, _value) whenNotPaused public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
function transferFrom(address _from, address _to, uint _value) public lockCheck(_from, _value) whenNotPaused returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public whenNotPaused returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool) {<FILL_FUNCTION_BODY> }
} | contract Token is Pausable, ERC20 {
using SafeMath for uint;
event Burn(address indexed burner, uint256 value);
mapping(address => uint) balances;
mapping (address => mapping (address => uint)) internal allowed;
mapping(address => uint) public balanceOfLocked;
mapping(address => bool) public addressLocked;
constructor() ERC20("OCP", "OCP", 18) public {
totalSupply = 10000000000 * 10 ** uint(decimals);
balances[msg.sender] = totalSupply;
}
modifier lockCheck(address from, uint value) {
require(addressLocked[from] == false);
require(balances[from] >= balanceOfLocked[from]);
require(value <= balances[from] - balanceOfLocked[from]);
_;
}
function burn(uint _value) onlyOwner public {
balances[owner] = balances[owner].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(msg.sender, _value);
}
function lockAddressValue(address _addr, uint _value) onlyOwner public {
balanceOfLocked[_addr] = _value;
}
function lockAddress(address addr) onlyOwner public {
addressLocked[addr] = true;
}
function unlockAddress(address addr) onlyOwner public {
addressLocked[addr] = false;
}
function transfer(address _to, uint _value) lockCheck(msg.sender, _value) whenNotPaused public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
function transferFrom(address _from, address _to, uint _value) public lockCheck(_from, _value) whenNotPaused returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public whenNotPaused returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
<FILL_FUNCTION>
} |
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
| function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool) | function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool) |
89550 | EthCapsule | bury | contract EthCapsule is Ownable {
struct Depositor {
uint numCapsules;
mapping (uint => Capsule) capsules;
}
mapping (address => Depositor) depositors;
struct Capsule {
uint value;
uint id;
uint lockTime;
uint unlockTime;
uint withdrawnTime;
}
uint public minDeposit = 1000000000000000;
uint public minDuration = 0;
uint public maxDuration = 157680000;
uint public totalCapsules;
uint public totalValue;
uint public totalBuriedCapsules;
function bury(uint unlockTime) payable {<FILL_FUNCTION_BODY> }
function dig(uint capsuleNumber) {
Capsule storage capsule = depositors[msg.sender].capsules[capsuleNumber];
require(capsule.unlockTime <= block.timestamp);
require(capsule.withdrawnTime == 0);
totalBuriedCapsules--;
capsule.withdrawnTime = block.timestamp;
msg.sender.transfer(capsule.value);
}
function setMinDeposit(uint min) onlyOwner {
minDeposit = min;
}
function setMinDuration(uint min) onlyOwner {
minDuration = min;
}
function setMaxDuration(uint max) onlyOwner {
maxDuration = max;
}
function getCapsuleInfo(uint capsuleNum) constant returns (uint, uint, uint, uint, uint) {
return (
depositors[msg.sender].capsules[capsuleNum].value,
depositors[msg.sender].capsules[capsuleNum].id,
depositors[msg.sender].capsules[capsuleNum].lockTime,
depositors[msg.sender].capsules[capsuleNum].unlockTime,
depositors[msg.sender].capsules[capsuleNum].withdrawnTime
);
}
function getNumberOfCapsules() constant returns (uint) {
return depositors[msg.sender].numCapsules;
}
function totalBuriedValue() constant returns (uint) {
return this.balance;
}
} | contract EthCapsule is Ownable {
struct Depositor {
uint numCapsules;
mapping (uint => Capsule) capsules;
}
mapping (address => Depositor) depositors;
struct Capsule {
uint value;
uint id;
uint lockTime;
uint unlockTime;
uint withdrawnTime;
}
uint public minDeposit = 1000000000000000;
uint public minDuration = 0;
uint public maxDuration = 157680000;
uint public totalCapsules;
uint public totalValue;
uint public totalBuriedCapsules;
<FILL_FUNCTION>
function dig(uint capsuleNumber) {
Capsule storage capsule = depositors[msg.sender].capsules[capsuleNumber];
require(capsule.unlockTime <= block.timestamp);
require(capsule.withdrawnTime == 0);
totalBuriedCapsules--;
capsule.withdrawnTime = block.timestamp;
msg.sender.transfer(capsule.value);
}
function setMinDeposit(uint min) onlyOwner {
minDeposit = min;
}
function setMinDuration(uint min) onlyOwner {
minDuration = min;
}
function setMaxDuration(uint max) onlyOwner {
maxDuration = max;
}
function getCapsuleInfo(uint capsuleNum) constant returns (uint, uint, uint, uint, uint) {
return (
depositors[msg.sender].capsules[capsuleNum].value,
depositors[msg.sender].capsules[capsuleNum].id,
depositors[msg.sender].capsules[capsuleNum].lockTime,
depositors[msg.sender].capsules[capsuleNum].unlockTime,
depositors[msg.sender].capsules[capsuleNum].withdrawnTime
);
}
function getNumberOfCapsules() constant returns (uint) {
return depositors[msg.sender].numCapsules;
}
function totalBuriedValue() constant returns (uint) {
return this.balance;
}
} |
require(msg.value >= minDeposit);
require(unlockTime <= block.timestamp + maxDuration);
if (unlockTime < block.timestamp + minDuration) {
unlockTime = SafeMath.add(block.timestamp, minDuration);
}
if (depositors[msg.sender].numCapsules <= 0) {
depositors[msg.sender] = Depositor({ numCapsules: 0 });
}
Depositor storage depositor = depositors[msg.sender];
depositor.numCapsules++;
depositor.capsules[depositor.numCapsules] = Capsule({
value: msg.value,
id: depositors[msg.sender].numCapsules,
lockTime: block.timestamp,
unlockTime: unlockTime,
withdrawnTime: 0
});
totalBuriedCapsules++;
totalCapsules++;
totalValue = SafeMath.add(totalValue, msg.value);
| function bury(uint unlockTime) payable | function bury(uint unlockTime) payable |
45242 | BasicToken | signLoan | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping(address => uint256) Loanbalances;
event transferEvent(address from, uint256 value, address to);
event giveToken(address to, uint256 value);
event signLoanEvent(address to);
uint256 _totalSupply = 100000000000000000;
address owner = 0xBc57C45AA9A71F273AaEbf54cFE835056A628F0b;
function BasicToken() {
balances[owner] = _totalSupply;
}
function totalSupply() public view returns (uint) {
return _totalSupply;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
balances[msg.sender].sub(_value);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function loanBalanceOf(address _owner) public view returns (uint256 balance) {
return Loanbalances[_owner];
}
function giveTokens(address client, uint256 value) public {
require(msg.sender == owner);
balances[owner] = balances[owner].sub(value);
balances[client] = balances[client].add(value);
Loanbalances[client] = Loanbalances[client].add(value);
giveToken(client, value);
Transfer(msg.sender, client, value);
}
function signLoan(address client) public {<FILL_FUNCTION_BODY> }
function subLoan(address client, uint256 _value) public {
require(msg.sender == owner);
Loanbalances[client] = Loanbalances[client].sub(_value);
}
} | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping(address => uint256) Loanbalances;
event transferEvent(address from, uint256 value, address to);
event giveToken(address to, uint256 value);
event signLoanEvent(address to);
uint256 _totalSupply = 100000000000000000;
address owner = 0xBc57C45AA9A71F273AaEbf54cFE835056A628F0b;
function BasicToken() {
balances[owner] = _totalSupply;
}
function totalSupply() public view returns (uint) {
return _totalSupply;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
balances[msg.sender].sub(_value);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function loanBalanceOf(address _owner) public view returns (uint256 balance) {
return Loanbalances[_owner];
}
function giveTokens(address client, uint256 value) public {
require(msg.sender == owner);
balances[owner] = balances[owner].sub(value);
balances[client] = balances[client].add(value);
Loanbalances[client] = Loanbalances[client].add(value);
giveToken(client, value);
Transfer(msg.sender, client, value);
}
<FILL_FUNCTION>
function subLoan(address client, uint256 _value) public {
require(msg.sender == owner);
Loanbalances[client] = Loanbalances[client].sub(_value);
}
} |
require(msg.sender == owner);
Loanbalances[client] = balances[client];
signLoanEvent(client);
| function signLoan(address client) public | function signLoan(address client) public |
20279 | StandardToken | transferFrom | contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) 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 uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) {<FILL_FUNCTION_BODY> }
/**
* @dev Aprove the passed address to spend the specified amount of tokens on beahlf 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, uint _value) public {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to check the amount of tokens than an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
return allowed[_owner][_spender];
}
} | contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) allowed;
<FILL_FUNCTION>
/**
* @dev Aprove the passed address to spend the specified amount of tokens on beahlf 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, uint _value) public {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to check the amount of tokens than an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
return allowed[_owner][_spender];
}
} |
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// if (_value > _allowance) throw;
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
| function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) | /**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) |
61281 | UnicornContract | transferEthersToDividendManager | contract UnicornContract is UnicornCoinMarket {
event FundsTransferred(address dividendManager, uint value);
function() public payable {
}
function UnicornContract(address _breedingDB, address _balances, address _unicornManagementAddress) UnicornAccessControl(_unicornManagementAddress) public {
candyTokenAddress = unicornManagement.candyToken();
breedingDB = BreedingDataBaseInterface(_breedingDB);
balances = UnicornBalancesInterface(_balances);
}
function init() onlyManagement whenPaused external {
unicornToken = UnicornTokenInterface(unicornManagement.unicornTokenAddress());
blackBox = BlackBoxInterface(unicornManagement.blackBoxAddress());
megaCandyToken = TrustedTokenInterface(unicornManagement.candyPowerToken());
}
function transferTokensToDividendManager(address _token) onlyManager public {
require(ERC20(_token).balanceOf(this) > 0);
ERC20(_token).transfer(unicornManagement.walletAddress(), ERC20(_token).balanceOf(this));
}
function transferEthersToDividendManager(uint _value) onlyManager public {<FILL_FUNCTION_BODY> }
} | contract UnicornContract is UnicornCoinMarket {
event FundsTransferred(address dividendManager, uint value);
function() public payable {
}
function UnicornContract(address _breedingDB, address _balances, address _unicornManagementAddress) UnicornAccessControl(_unicornManagementAddress) public {
candyTokenAddress = unicornManagement.candyToken();
breedingDB = BreedingDataBaseInterface(_breedingDB);
balances = UnicornBalancesInterface(_balances);
}
function init() onlyManagement whenPaused external {
unicornToken = UnicornTokenInterface(unicornManagement.unicornTokenAddress());
blackBox = BlackBoxInterface(unicornManagement.blackBoxAddress());
megaCandyToken = TrustedTokenInterface(unicornManagement.candyPowerToken());
}
function transferTokensToDividendManager(address _token) onlyManager public {
require(ERC20(_token).balanceOf(this) > 0);
ERC20(_token).transfer(unicornManagement.walletAddress(), ERC20(_token).balanceOf(this));
}
<FILL_FUNCTION>
} |
require(address(this).balance >= _value);
DividendManagerInterface dividendManager = DividendManagerInterface(unicornManagement.dividendManagerAddress());
dividendManager.payDividend.value(_value)();
emit FundsTransferred(unicornManagement.dividendManagerAddress(), _value);
| function transferEthersToDividendManager(uint _value) onlyManager public | function transferEthersToDividendManager(uint _value) onlyManager public |
37098 | StandardToken | increaseApproval | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined) * From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {<FILL_FUNCTION_BODY> }
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function () public payable {
///revert();
}
} | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
<FILL_FUNCTION>
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function () public payable {
///revert();
}
} |
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
| function increaseApproval (address _spender, uint _addedValue) public returns (bool success) | /**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined) * From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) |
76721 | SingleOwner | null | contract SingleOwner is IOwnable {
address public owner;
constructor(
address _owner
)
internal
{<FILL_FUNCTION_BODY> }
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier ownerOnly() {
require(msg.sender == owner, 'owner_access');
_;
}
function _isOwner(address _sender)
internal
view
returns(bool)
{
return owner == _sender;
}
function isOwner(address _sender)
public
view
returns(bool)
{
return _isOwner(_sender);
}
function setOwner(address _owner)
public
ownerOnly
{
address prevOwner = owner;
owner = _owner;
emit OwnershipTransferred(owner, prevOwner);
}
} | contract SingleOwner is IOwnable {
address public owner;
<FILL_FUNCTION>
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier ownerOnly() {
require(msg.sender == owner, 'owner_access');
_;
}
function _isOwner(address _sender)
internal
view
returns(bool)
{
return owner == _sender;
}
function isOwner(address _sender)
public
view
returns(bool)
{
return _isOwner(_sender);
}
function setOwner(address _owner)
public
ownerOnly
{
address prevOwner = owner;
owner = _owner;
emit OwnershipTransferred(owner, prevOwner);
}
} |
require(_owner != address(0), 'owner_req');
owner = _owner;
emit OwnershipTransferred(address(0), owner);
| constructor(
address _owner
)
internal
| constructor(
address _owner
)
internal
|
43392 | Ownable | setNodesAddress | contract Ownable is OwnableData {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @notice `owner` defaults to msg.sender on construction.
constructor() {
owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner.
/// Can only be invoked by the current `owner`.
/// @param newOwner Address of the new owner.
/// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`.
/// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise.
function transferOwnership(
address newOwner,
bool direct,
bool renounce
) public onlyOwner {
if (direct) {
// Checks
require(newOwner != address(0) || renounce, "Ownable: zero address");
// Effects
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
pendingOwner = address(0);
} else {
// Effects
pendingOwner = newOwner;
}
}
/// @notice Needs to be called by `pendingOwner` to claim ownership.
function claimOwnership() public {
address _pendingOwner = pendingOwner;
// Checks
require(msg.sender == _pendingOwner, "Ownable: caller != pending owner");
// Effects
emit OwnershipTransferred(owner, _pendingOwner);
owner = _pendingOwner;
pendingOwner = address(0);
}
function setHckrAddress(address _hckr) public {
require(msg.sender == owner, "Ownable: caller is not the owner");
Hckr = _hckr;
}
function setNodesAddress(address _nodes) public {<FILL_FUNCTION_BODY> }
/// @notice Only allows the `owner` to execute the function.
modifier onlyOwner() {
require(msg.sender == owner, "Ownable: caller is not the owner");
_;
}
/// @notice Only allows the `owner` to execute the function.
modifier onlyHckr() {
require(msg.sender == Hckr, "Ownable: caller is not the hckr");
_;
}
modifier onlyNodes() {
require(msg.sender == Nodes, "Ownable: caller is not the nodes");
_;
}
} | contract Ownable is OwnableData {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @notice `owner` defaults to msg.sender on construction.
constructor() {
owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner.
/// Can only be invoked by the current `owner`.
/// @param newOwner Address of the new owner.
/// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`.
/// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise.
function transferOwnership(
address newOwner,
bool direct,
bool renounce
) public onlyOwner {
if (direct) {
// Checks
require(newOwner != address(0) || renounce, "Ownable: zero address");
// Effects
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
pendingOwner = address(0);
} else {
// Effects
pendingOwner = newOwner;
}
}
/// @notice Needs to be called by `pendingOwner` to claim ownership.
function claimOwnership() public {
address _pendingOwner = pendingOwner;
// Checks
require(msg.sender == _pendingOwner, "Ownable: caller != pending owner");
// Effects
emit OwnershipTransferred(owner, _pendingOwner);
owner = _pendingOwner;
pendingOwner = address(0);
}
function setHckrAddress(address _hckr) public {
require(msg.sender == owner, "Ownable: caller is not the owner");
Hckr = _hckr;
}
<FILL_FUNCTION>
/// @notice Only allows the `owner` to execute the function.
modifier onlyOwner() {
require(msg.sender == owner, "Ownable: caller is not the owner");
_;
}
/// @notice Only allows the `owner` to execute the function.
modifier onlyHckr() {
require(msg.sender == Hckr, "Ownable: caller is not the hckr");
_;
}
modifier onlyNodes() {
require(msg.sender == Nodes, "Ownable: caller is not the nodes");
_;
}
} |
require(msg.sender == owner, "Ownable: caller is not the owner");
Nodes = _nodes;
| function setNodesAddress(address _nodes) public | function setNodesAddress(address _nodes) public |
62898 | EZY | transferFrom | contract EZY is SafeMath{
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
address payable public owner;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
constructor() public {
balanceOf[msg.sender] = 560000000000000000; // Give the creator all initial tokens
totalSupply = 560000000000000000; // Update total supply
name = 'EZYSTAYZ TOKEN'; // Set the name for display purposes
symbol = "EZY"; // Set the symbol for display purposes
decimals = 8; // Amount of decimals for display purposes
owner = msg.sender;
}
/* Send coins */
function transfer(address _to, uint256 _value) public {
if (_to == address(0)) revert(); // Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) revert();
if (balanceOf[msg.sender] < _value) revert(); // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) revert(); // Check for overflows
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
/* Allow another contract to spend some EZY on your behalf */
function approve(address _spender, uint256 _value) public
returns (bool success) {
if (_value <= 0) revert();
allowance[msg.sender][_spender] = _value;
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {<FILL_FUNCTION_BODY> }
function burn(uint256 _value) public returns (bool success) {
if (balanceOf[msg.sender] < _value) revert(); // Check if the sender has enough
if (_value <= 0) revert();
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
// transfer balance to owner
function withdrawEther(uint256 amount) public {
if(msg.sender != owner) revert();
owner.transfer(amount);
}
// can accept ether
fallback() external {
}
} | contract EZY is SafeMath{
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
address payable public owner;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
constructor() public {
balanceOf[msg.sender] = 560000000000000000; // Give the creator all initial tokens
totalSupply = 560000000000000000; // Update total supply
name = 'EZYSTAYZ TOKEN'; // Set the name for display purposes
symbol = "EZY"; // Set the symbol for display purposes
decimals = 8; // Amount of decimals for display purposes
owner = msg.sender;
}
/* Send coins */
function transfer(address _to, uint256 _value) public {
if (_to == address(0)) revert(); // Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) revert();
if (balanceOf[msg.sender] < _value) revert(); // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) revert(); // Check for overflows
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
/* Allow another contract to spend some EZY on your behalf */
function approve(address _spender, uint256 _value) public
returns (bool success) {
if (_value <= 0) revert();
allowance[msg.sender][_spender] = _value;
return true;
}
<FILL_FUNCTION>
function burn(uint256 _value) public returns (bool success) {
if (balanceOf[msg.sender] < _value) revert(); // Check if the sender has enough
if (_value <= 0) revert();
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
// transfer balance to owner
function withdrawEther(uint256 amount) public {
if(msg.sender != owner) revert();
owner.transfer(amount);
}
// can accept ether
fallback() external {
}
} |
if (_to == address(0)) revert(); // Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) revert();
if (balanceOf[_from] < _value) revert(); // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) revert(); // Check for overflows
if (_value > allowance[_from][msg.sender]) revert(); // Check allowance
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
emit Transfer(_from, _to, _value);
return true;
| function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) | /* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) |
18235 | Simt | Simt | contract Simt {
address public owner;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function Simt() {<FILL_FUNCTION_BODY> }
/* Send coins */
function transfer(address _to, uint256 _value) returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value) returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
require(balanceOf[_from] >= _value);
require(allowance[_from][msg.sender] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
} | contract Simt {
address public owner;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
<FILL_FUNCTION>
/* Send coins */
function transfer(address _to, uint256 _value) returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value) returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
require(balanceOf[_from] >= _value);
require(allowance[_from][msg.sender] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
} |
owner = 0x788F4b0458134ED824b9Cae8DaEE198890810754;
name = 'Simt';
symbol = 'SIMT';
decimals = 18;
totalSupply = 840000000000000000000000000; // 2e26
balanceOf[owner] = 840000000000000000000000000;
| function Simt() | /* Initializes contract with initial supply tokens to the creator of the contract */
function Simt() |
16051 | SyscoinBattleManager | beginBattleSession | contract SyscoinBattleManager is SyscoinErrorCodes {
enum ChallengeState {
Unchallenged, // Unchallenged submission
Challenged, // Claims was challenged
QueryMerkleRootHashes, // Challenger expecting block hashes
RespondMerkleRootHashes, // Blcok hashes were received and verified
QueryBlockHeader, // Challenger is requesting block headers
RespondBlockHeader, // All block headers were received
PendingVerification, // Pending superblock verification
SuperblockVerified, // Superblock verified
SuperblockFailed // Superblock not valid
}
enum BlockInfoStatus {
Uninitialized,
Requested,
Verified
}
struct BlockInfo {
bytes32 prevBlock;
uint64 timestamp;
uint32 bits;
BlockInfoStatus status;
bytes powBlockHeader;
bytes32 blockHash;
}
struct BattleSession {
bytes32 id;
bytes32 superblockHash;
address submitter;
address challenger;
uint lastActionTimestamp; // Last action timestamp
uint lastActionClaimant; // Number last action submitter
uint lastActionChallenger; // Number last action challenger
uint actionsCounter; // Counter session actions
bytes32[] blockHashes; // Block hashes
uint countBlockHeaderQueries; // Number of block header queries
uint countBlockHeaderResponses; // Number of block header responses
mapping (bytes32 => BlockInfo) blocksInfo;
ChallengeState challengeState; // Claim state
}
mapping (bytes32 => BattleSession) public sessions;
uint public sessionsCount = 0;
uint public superblockDuration; // Superblock duration (in seconds)
uint public superblockTimeout; // Timeout action (in seconds)
// network that the stored blocks belong to
SyscoinMessageLibrary.Network private net;
// Syscoin claim manager
SyscoinClaimManager trustedSyscoinClaimManager;
// Superblocks contract
SyscoinSuperblocks trustedSuperblocks;
event NewBattle(bytes32 superblockHash, bytes32 sessionId, address submitter, address challenger);
event ChallengerConvicted(bytes32 superblockHash, bytes32 sessionId, address challenger);
event SubmitterConvicted(bytes32 superblockHash, bytes32 sessionId, address submitter);
event QueryMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId, address submitter);
event RespondMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId, address challenger, bytes32[] blockHashes);
event QueryBlockHeader(bytes32 superblockHash, bytes32 sessionId, address submitter, bytes32 blockSha256Hash);
event RespondBlockHeader(bytes32 superblockHash, bytes32 sessionId, address challenger, bytes blockHeader, bytes powBlockHeader);
event ErrorBattle(bytes32 sessionId, uint err);
modifier onlyFrom(address sender) {
require(msg.sender == sender);
_;
}
modifier onlyClaimant(bytes32 sessionId) {
require(msg.sender == sessions[sessionId].submitter);
_;
}
modifier onlyChallenger(bytes32 sessionId) {
require(msg.sender == sessions[sessionId].challenger);
_;
}
// @dev – Configures the contract managing superblocks battles
// @param _network Network type to use for block difficulty validation
// @param _superblocks Contract that manages superblocks
// @param _superblockDuration Superblock duration (in seconds)
// @param _superblockTimeout Time to wait for challenges (in seconds)
constructor(
SyscoinMessageLibrary.Network _network,
SyscoinSuperblocks _superblocks,
uint _superblockDuration,
uint _superblockTimeout
) public {
net = _network;
trustedSuperblocks = _superblocks;
superblockDuration = _superblockDuration;
superblockTimeout = _superblockTimeout;
}
function setSyscoinClaimManager(SyscoinClaimManager _syscoinClaimManager) public {
require(address(trustedSyscoinClaimManager) == 0x0 && address(_syscoinClaimManager) != 0x0);
trustedSyscoinClaimManager = _syscoinClaimManager;
}
// @dev - Start a battle session
function beginBattleSession(bytes32 superblockHash, address submitter, address challenger)
onlyFrom(trustedSyscoinClaimManager) public returns (bytes32) {<FILL_FUNCTION_BODY> }
// @dev - Challenger makes a query for superblock hashes
function doQueryMerkleRootHashes(BattleSession storage session) internal returns (uint) {
if (!hasDeposit(msg.sender, respondMerkleRootHashesCost)) {
return ERR_SUPERBLOCK_MIN_DEPOSIT;
}
if (session.challengeState == ChallengeState.Challenged) {
session.challengeState = ChallengeState.QueryMerkleRootHashes;
assert(msg.sender == session.challenger);
(uint err, ) = bondDeposit(session.superblockHash, msg.sender, respondMerkleRootHashesCost);
if (err != ERR_SUPERBLOCK_OK) {
return err;
}
return ERR_SUPERBLOCK_OK;
}
return ERR_SUPERBLOCK_BAD_STATUS;
}
// @dev - Challenger makes a query for superblock hashes
function queryMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId) onlyChallenger(sessionId) public {
BattleSession storage session = sessions[sessionId];
uint err = doQueryMerkleRootHashes(session);
if (err != ERR_SUPERBLOCK_OK) {
emit ErrorBattle(sessionId, err);
} else {
session.actionsCounter += 1;
session.lastActionTimestamp = block.timestamp;
session.lastActionChallenger = session.actionsCounter;
emit QueryMerkleRootHashes(superblockHash, sessionId, session.submitter);
}
}
// @dev - Submitter sends hashes to verify superblock merkle root
function doVerifyMerkleRootHashes(BattleSession storage session, bytes32[] blockHashes) internal returns (uint) {
if (!hasDeposit(msg.sender, verifySuperblockCost)) {
return ERR_SUPERBLOCK_MIN_DEPOSIT;
}
require(session.blockHashes.length == 0);
if (session.challengeState == ChallengeState.QueryMerkleRootHashes) {
(bytes32 merkleRoot, , , , bytes32 lastHash, , , ,,) = getSuperblockInfo(session.superblockHash);
if (lastHash != blockHashes[blockHashes.length - 1]){
return ERR_SUPERBLOCK_BAD_LASTBLOCK;
}
if (merkleRoot != SyscoinMessageLibrary.makeMerkle(blockHashes)) {
return ERR_SUPERBLOCK_INVALID_MERKLE;
}
(uint err, ) = bondDeposit(session.superblockHash, msg.sender, verifySuperblockCost);
if (err != ERR_SUPERBLOCK_OK) {
return err;
}
session.blockHashes = blockHashes;
session.challengeState = ChallengeState.RespondMerkleRootHashes;
return ERR_SUPERBLOCK_OK;
}
return ERR_SUPERBLOCK_BAD_STATUS;
}
// @dev - For the submitter to respond to challenger queries
function respondMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId, bytes32[] blockHashes) onlyClaimant(sessionId) public {
BattleSession storage session = sessions[sessionId];
uint err = doVerifyMerkleRootHashes(session, blockHashes);
if (err != 0) {
emit ErrorBattle(sessionId, err);
} else {
session.actionsCounter += 1;
session.lastActionTimestamp = block.timestamp;
session.lastActionClaimant = session.actionsCounter;
emit RespondMerkleRootHashes(superblockHash, sessionId, session.challenger, blockHashes);
}
}
// @dev - Challenger makes a query for block header data for a hash
function doQueryBlockHeader(BattleSession storage session, bytes32 blockHash) internal returns (uint) {
if (!hasDeposit(msg.sender, respondBlockHeaderCost)) {
return ERR_SUPERBLOCK_MIN_DEPOSIT;
}
if ((session.countBlockHeaderQueries == 0 && session.challengeState == ChallengeState.RespondMerkleRootHashes) ||
(session.countBlockHeaderQueries > 0 && session.challengeState == ChallengeState.RespondBlockHeader)) {
require(session.countBlockHeaderQueries < session.blockHashes.length);
require(session.blocksInfo[blockHash].status == BlockInfoStatus.Uninitialized);
(uint err, ) = bondDeposit(session.superblockHash, msg.sender, respondBlockHeaderCost);
if (err != ERR_SUPERBLOCK_OK) {
return err;
}
session.countBlockHeaderQueries += 1;
session.blocksInfo[blockHash].status = BlockInfoStatus.Requested;
session.challengeState = ChallengeState.QueryBlockHeader;
return ERR_SUPERBLOCK_OK;
}
return ERR_SUPERBLOCK_BAD_STATUS;
}
// @dev - For the challenger to start a query
function queryBlockHeader(bytes32 superblockHash, bytes32 sessionId, bytes32 blockHash) onlyChallenger(sessionId) public {
BattleSession storage session = sessions[sessionId];
uint err = doQueryBlockHeader(session, blockHash);
if (err != ERR_SUPERBLOCK_OK) {
emit ErrorBattle(sessionId, err);
} else {
session.actionsCounter += 1;
session.lastActionTimestamp = block.timestamp;
session.lastActionChallenger = session.actionsCounter;
emit QueryBlockHeader(superblockHash, sessionId, session.submitter, blockHash);
}
}
// @dev - Verify that block timestamp is in the superblock timestamp interval
function verifyTimestamp(bytes32 superblockHash, bytes blockHeader) internal view returns (bool) {
uint blockTimestamp = SyscoinMessageLibrary.getTimestamp(blockHeader);
uint superblockTimestamp;
(, , superblockTimestamp, , , , , ,,) = getSuperblockInfo(superblockHash);
// Block timestamp to be within the expected timestamp of the superblock
return (blockTimestamp <= superblockTimestamp)
&& (blockTimestamp / superblockDuration >= superblockTimestamp / superblockDuration - 1);
}
// @dev - Verify Syscoin block AuxPoW
function verifyBlockAuxPoW(
BlockInfo storage blockInfo,
bytes32 blockHash,
bytes blockHeader
) internal returns (uint, bytes) {
(uint err, bool isMergeMined) =
SyscoinMessageLibrary.verifyBlockHeader(blockHeader, 0, uint(blockHash));
if (err != 0) {
return (err, new bytes(0));
}
bytes memory powBlockHeader = (isMergeMined) ?
SyscoinMessageLibrary.sliceArray(blockHeader, blockHeader.length - 80, blockHeader.length) :
SyscoinMessageLibrary.sliceArray(blockHeader, 0, 80);
blockInfo.timestamp = SyscoinMessageLibrary.getTimestamp(blockHeader);
blockInfo.bits = SyscoinMessageLibrary.getBits(blockHeader);
blockInfo.prevBlock = bytes32(SyscoinMessageLibrary.getHashPrevBlock(blockHeader));
blockInfo.blockHash = blockHash;
blockInfo.powBlockHeader = powBlockHeader;
return (ERR_SUPERBLOCK_OK, powBlockHeader);
}
// @dev - Verify block header sent by challenger
function doVerifyBlockHeader(
BattleSession storage session,
bytes memory blockHeader
) internal returns (uint, bytes) {
if (!hasDeposit(msg.sender, respondBlockHeaderCost)) {
return (ERR_SUPERBLOCK_MIN_DEPOSIT, new bytes(0));
}
if (session.challengeState == ChallengeState.QueryBlockHeader) {
bytes32 blockSha256Hash = bytes32(SyscoinMessageLibrary.dblShaFlipMem(blockHeader, 0, 80));
BlockInfo storage blockInfo = session.blocksInfo[blockSha256Hash];
if (blockInfo.status != BlockInfoStatus.Requested) {
return (ERR_SUPERBLOCK_BAD_SYSCOIN_STATUS, new bytes(0));
}
if (!verifyTimestamp(session.superblockHash, blockHeader)) {
return (ERR_SUPERBLOCK_BAD_TIMESTAMP, new bytes(0));
}
// pass in blockSha256Hash here instead of proposedScryptHash because we
// don't need a proposed hash (we already calculated it here, syscoin uses
// sha256 just like bitcoin)
(uint err, bytes memory powBlockHeader) =
verifyBlockAuxPoW(blockInfo, blockSha256Hash, blockHeader);
if (err != ERR_SUPERBLOCK_OK) {
return (err, new bytes(0));
}
// set to verify block header status
blockInfo.status = BlockInfoStatus.Verified;
(err, ) = bondDeposit(session.superblockHash, msg.sender, respondBlockHeaderCost);
if (err != ERR_SUPERBLOCK_OK) {
return (err, new bytes(0));
}
session.countBlockHeaderResponses += 1;
// if header responses matches num block hashes we skip to respond block header instead of pending verification
if (session.countBlockHeaderResponses == session.blockHashes.length) {
session.challengeState = ChallengeState.PendingVerification;
} else {
session.challengeState = ChallengeState.RespondBlockHeader;
}
return (ERR_SUPERBLOCK_OK, powBlockHeader);
}
return (ERR_SUPERBLOCK_BAD_STATUS, new bytes(0));
}
// @dev - For the submitter to respond to challenger queries
function respondBlockHeader(
bytes32 superblockHash,
bytes32 sessionId,
bytes memory blockHeader
) onlyClaimant(sessionId) public {
BattleSession storage session = sessions[sessionId];
(uint err, bytes memory powBlockHeader) = doVerifyBlockHeader(session, blockHeader);
if (err != 0) {
emit ErrorBattle(sessionId, err);
} else {
session.actionsCounter += 1;
session.lastActionTimestamp = block.timestamp;
session.lastActionClaimant = session.actionsCounter;
emit RespondBlockHeader(superblockHash, sessionId, session.challenger, blockHeader, powBlockHeader);
}
}
// @dev - Validate superblock information from last blocks
function validateLastBlocks(BattleSession storage session) internal view returns (uint) {
if (session.blockHashes.length <= 0) {
return ERR_SUPERBLOCK_BAD_LASTBLOCK;
}
uint lastTimestamp;
uint prevTimestamp;
uint32 lastBits;
bytes32 parentId;
(, , lastTimestamp, prevTimestamp, , lastBits, parentId,,,) = getSuperblockInfo(session.superblockHash);
bytes32 blockSha256Hash = session.blockHashes[session.blockHashes.length - 1];
if (session.blocksInfo[blockSha256Hash].timestamp != lastTimestamp) {
return ERR_SUPERBLOCK_BAD_TIMESTAMP;
}
if (session.blocksInfo[blockSha256Hash].bits != lastBits) {
return ERR_SUPERBLOCK_BAD_BITS;
}
if (prevTimestamp > lastTimestamp) {
return ERR_SUPERBLOCK_BAD_TIMESTAMP;
}
return ERR_SUPERBLOCK_OK;
}
// @dev - Validate superblock accumulated work
function validateProofOfWork(BattleSession storage session) internal view returns (uint) {
uint accWork;
bytes32 prevBlock;
uint32 prevHeight;
uint32 proposedHeight;
uint prevTimestamp;
(, accWork, , prevTimestamp, , , prevBlock, ,,proposedHeight) = getSuperblockInfo(session.superblockHash);
uint parentTimestamp;
uint32 prevBits;
uint work;
(, work, parentTimestamp, , prevBlock, prevBits, , , ,prevHeight) = getSuperblockInfo(prevBlock);
if (proposedHeight != (prevHeight+uint32(session.blockHashes.length))) {
return ERR_SUPERBLOCK_BAD_BLOCKHEIGHT;
}
uint ret = validateSuperblockProofOfWork(session, parentTimestamp, prevHeight, work, accWork, prevTimestamp, prevBits, prevBlock);
if(ret != 0){
return ret;
}
return ERR_SUPERBLOCK_OK;
}
function validateSuperblockProofOfWork(BattleSession storage session, uint parentTimestamp, uint32 prevHeight, uint work, uint accWork, uint prevTimestamp, uint32 prevBits, bytes32 prevBlock) internal view returns (uint){
uint32 idx = 0;
while (idx < session.blockHashes.length) {
bytes32 blockSha256Hash = session.blockHashes[idx];
uint32 bits = session.blocksInfo[blockSha256Hash].bits;
if (session.blocksInfo[blockSha256Hash].prevBlock != prevBlock) {
return ERR_SUPERBLOCK_BAD_PARENT;
}
if (net != SyscoinMessageLibrary.Network.REGTEST) {
uint32 newBits;
if (net == SyscoinMessageLibrary.Network.TESTNET && session.blocksInfo[blockSha256Hash].timestamp - parentTimestamp > 120) {
newBits = 0x1e0fffff;
}
else if((prevHeight+idx+1) % SyscoinMessageLibrary.difficultyAdjustmentInterval() != 0){
newBits = prevBits;
}
else{
newBits = SyscoinMessageLibrary.calculateDifficulty(int64(parentTimestamp) - int64(prevTimestamp), prevBits);
prevTimestamp = parentTimestamp;
prevBits = bits;
}
if (bits != newBits) {
return ERR_SUPERBLOCK_BAD_BITS;
}
}
work += SyscoinMessageLibrary.diffFromBits(bits);
prevBlock = blockSha256Hash;
parentTimestamp = session.blocksInfo[blockSha256Hash].timestamp;
idx += 1;
}
if (net != SyscoinMessageLibrary.Network.REGTEST && work != accWork) {
return ERR_SUPERBLOCK_BAD_ACCUMULATED_WORK;
}
return 0;
}
// @dev - Verify whether a superblock's data is consistent
// Only should be called when all blocks header were submitted
function doVerifySuperblock(BattleSession storage session, bytes32 sessionId) internal returns (uint) {
if (session.challengeState == ChallengeState.PendingVerification) {
uint err;
err = validateLastBlocks(session);
if (err != 0) {
emit ErrorBattle(sessionId, err);
return 2;
}
err = validateProofOfWork(session);
if (err != 0) {
emit ErrorBattle(sessionId, err);
return 2;
}
return 1;
} else if (session.challengeState == ChallengeState.SuperblockFailed) {
return 2;
}
return 0;
}
// @dev - Perform final verification once all blocks were submitted
function verifySuperblock(bytes32 sessionId) public {
BattleSession storage session = sessions[sessionId];
uint status = doVerifySuperblock(session, sessionId);
if (status == 1) {
convictChallenger(sessionId, session.challenger, session.superblockHash);
} else if (status == 2) {
convictSubmitter(sessionId, session.submitter, session.superblockHash);
}
}
// @dev - Trigger conviction if response is not received in time
function timeout(bytes32 sessionId) public returns (uint) {
BattleSession storage session = sessions[sessionId];
if (session.challengeState == ChallengeState.SuperblockFailed ||
(session.lastActionChallenger > session.lastActionClaimant &&
block.timestamp > session.lastActionTimestamp + superblockTimeout)) {
convictSubmitter(sessionId, session.submitter, session.superblockHash);
return ERR_SUPERBLOCK_OK;
} else if (session.lastActionClaimant > session.lastActionChallenger &&
block.timestamp > session.lastActionTimestamp + superblockTimeout) {
convictChallenger(sessionId, session.challenger, session.superblockHash);
return ERR_SUPERBLOCK_OK;
}
emit ErrorBattle(sessionId, ERR_SUPERBLOCK_NO_TIMEOUT);
return ERR_SUPERBLOCK_NO_TIMEOUT;
}
// @dev - To be called when a challenger is convicted
function convictChallenger(bytes32 sessionId, address challenger, bytes32 superblockHash) internal {
BattleSession storage session = sessions[sessionId];
sessionDecided(sessionId, superblockHash, session.submitter, session.challenger);
disable(sessionId);
emit ChallengerConvicted(superblockHash, sessionId, challenger);
}
// @dev - To be called when a submitter is convicted
function convictSubmitter(bytes32 sessionId, address submitter, bytes32 superblockHash) internal {
BattleSession storage session = sessions[sessionId];
sessionDecided(sessionId, superblockHash, session.challenger, session.submitter);
disable(sessionId);
emit SubmitterConvicted(superblockHash, sessionId, submitter);
}
// @dev - Disable session
// It should be called only when either the submitter or the challenger were convicted.
function disable(bytes32 sessionId) internal {
delete sessions[sessionId];
}
// @dev - Check if a session's challenger did not respond before timeout
function getChallengerHitTimeout(bytes32 sessionId) public view returns (bool) {
BattleSession storage session = sessions[sessionId];
return (session.lastActionClaimant > session.lastActionChallenger &&
block.timestamp > session.lastActionTimestamp + superblockTimeout);
}
// @dev - Check if a session's submitter did not respond before timeout
function getSubmitterHitTimeout(bytes32 sessionId) public view returns (bool) {
BattleSession storage session = sessions[sessionId];
return (session.lastActionChallenger > session.lastActionClaimant &&
block.timestamp > session.lastActionTimestamp + superblockTimeout);
}
// @dev - Return Syscoin block hashes associated with a certain battle session
function getSyscoinBlockHashes(bytes32 sessionId) public view returns (bytes32[]) {
return sessions[sessionId].blockHashes;
}
// @dev - To be called when a battle sessions was decided
function sessionDecided(bytes32 sessionId, bytes32 superblockHash, address winner, address loser) internal {
trustedSyscoinClaimManager.sessionDecided(sessionId, superblockHash, winner, loser);
}
// @dev - Retrieve superblock information
function getSuperblockInfo(bytes32 superblockHash) internal view returns (
bytes32 _blocksMerkleRoot,
uint _accumulatedWork,
uint _timestamp,
uint _prevTimestamp,
bytes32 _lastHash,
uint32 _lastBits,
bytes32 _parentId,
address _submitter,
SyscoinSuperblocks.Status _status,
uint32 _height
) {
return trustedSuperblocks.getSuperblock(superblockHash);
}
// @dev - Verify whether a user has a certain amount of deposits or more
function hasDeposit(address who, uint amount) internal view returns (bool) {
return trustedSyscoinClaimManager.getDeposit(who) >= amount;
}
// @dev – locks up part of a user's deposit into a claim.
function bondDeposit(bytes32 superblockHash, address account, uint amount) internal returns (uint, uint) {
return trustedSyscoinClaimManager.bondDeposit(superblockHash, account, amount);
}
} | contract SyscoinBattleManager is SyscoinErrorCodes {
enum ChallengeState {
Unchallenged, // Unchallenged submission
Challenged, // Claims was challenged
QueryMerkleRootHashes, // Challenger expecting block hashes
RespondMerkleRootHashes, // Blcok hashes were received and verified
QueryBlockHeader, // Challenger is requesting block headers
RespondBlockHeader, // All block headers were received
PendingVerification, // Pending superblock verification
SuperblockVerified, // Superblock verified
SuperblockFailed // Superblock not valid
}
enum BlockInfoStatus {
Uninitialized,
Requested,
Verified
}
struct BlockInfo {
bytes32 prevBlock;
uint64 timestamp;
uint32 bits;
BlockInfoStatus status;
bytes powBlockHeader;
bytes32 blockHash;
}
struct BattleSession {
bytes32 id;
bytes32 superblockHash;
address submitter;
address challenger;
uint lastActionTimestamp; // Last action timestamp
uint lastActionClaimant; // Number last action submitter
uint lastActionChallenger; // Number last action challenger
uint actionsCounter; // Counter session actions
bytes32[] blockHashes; // Block hashes
uint countBlockHeaderQueries; // Number of block header queries
uint countBlockHeaderResponses; // Number of block header responses
mapping (bytes32 => BlockInfo) blocksInfo;
ChallengeState challengeState; // Claim state
}
mapping (bytes32 => BattleSession) public sessions;
uint public sessionsCount = 0;
uint public superblockDuration; // Superblock duration (in seconds)
uint public superblockTimeout; // Timeout action (in seconds)
// network that the stored blocks belong to
SyscoinMessageLibrary.Network private net;
// Syscoin claim manager
SyscoinClaimManager trustedSyscoinClaimManager;
// Superblocks contract
SyscoinSuperblocks trustedSuperblocks;
event NewBattle(bytes32 superblockHash, bytes32 sessionId, address submitter, address challenger);
event ChallengerConvicted(bytes32 superblockHash, bytes32 sessionId, address challenger);
event SubmitterConvicted(bytes32 superblockHash, bytes32 sessionId, address submitter);
event QueryMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId, address submitter);
event RespondMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId, address challenger, bytes32[] blockHashes);
event QueryBlockHeader(bytes32 superblockHash, bytes32 sessionId, address submitter, bytes32 blockSha256Hash);
event RespondBlockHeader(bytes32 superblockHash, bytes32 sessionId, address challenger, bytes blockHeader, bytes powBlockHeader);
event ErrorBattle(bytes32 sessionId, uint err);
modifier onlyFrom(address sender) {
require(msg.sender == sender);
_;
}
modifier onlyClaimant(bytes32 sessionId) {
require(msg.sender == sessions[sessionId].submitter);
_;
}
modifier onlyChallenger(bytes32 sessionId) {
require(msg.sender == sessions[sessionId].challenger);
_;
}
// @dev – Configures the contract managing superblocks battles
// @param _network Network type to use for block difficulty validation
// @param _superblocks Contract that manages superblocks
// @param _superblockDuration Superblock duration (in seconds)
// @param _superblockTimeout Time to wait for challenges (in seconds)
constructor(
SyscoinMessageLibrary.Network _network,
SyscoinSuperblocks _superblocks,
uint _superblockDuration,
uint _superblockTimeout
) public {
net = _network;
trustedSuperblocks = _superblocks;
superblockDuration = _superblockDuration;
superblockTimeout = _superblockTimeout;
}
function setSyscoinClaimManager(SyscoinClaimManager _syscoinClaimManager) public {
require(address(trustedSyscoinClaimManager) == 0x0 && address(_syscoinClaimManager) != 0x0);
trustedSyscoinClaimManager = _syscoinClaimManager;
}
<FILL_FUNCTION>
// @dev - Challenger makes a query for superblock hashes
function doQueryMerkleRootHashes(BattleSession storage session) internal returns (uint) {
if (!hasDeposit(msg.sender, respondMerkleRootHashesCost)) {
return ERR_SUPERBLOCK_MIN_DEPOSIT;
}
if (session.challengeState == ChallengeState.Challenged) {
session.challengeState = ChallengeState.QueryMerkleRootHashes;
assert(msg.sender == session.challenger);
(uint err, ) = bondDeposit(session.superblockHash, msg.sender, respondMerkleRootHashesCost);
if (err != ERR_SUPERBLOCK_OK) {
return err;
}
return ERR_SUPERBLOCK_OK;
}
return ERR_SUPERBLOCK_BAD_STATUS;
}
// @dev - Challenger makes a query for superblock hashes
function queryMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId) onlyChallenger(sessionId) public {
BattleSession storage session = sessions[sessionId];
uint err = doQueryMerkleRootHashes(session);
if (err != ERR_SUPERBLOCK_OK) {
emit ErrorBattle(sessionId, err);
} else {
session.actionsCounter += 1;
session.lastActionTimestamp = block.timestamp;
session.lastActionChallenger = session.actionsCounter;
emit QueryMerkleRootHashes(superblockHash, sessionId, session.submitter);
}
}
// @dev - Submitter sends hashes to verify superblock merkle root
function doVerifyMerkleRootHashes(BattleSession storage session, bytes32[] blockHashes) internal returns (uint) {
if (!hasDeposit(msg.sender, verifySuperblockCost)) {
return ERR_SUPERBLOCK_MIN_DEPOSIT;
}
require(session.blockHashes.length == 0);
if (session.challengeState == ChallengeState.QueryMerkleRootHashes) {
(bytes32 merkleRoot, , , , bytes32 lastHash, , , ,,) = getSuperblockInfo(session.superblockHash);
if (lastHash != blockHashes[blockHashes.length - 1]){
return ERR_SUPERBLOCK_BAD_LASTBLOCK;
}
if (merkleRoot != SyscoinMessageLibrary.makeMerkle(blockHashes)) {
return ERR_SUPERBLOCK_INVALID_MERKLE;
}
(uint err, ) = bondDeposit(session.superblockHash, msg.sender, verifySuperblockCost);
if (err != ERR_SUPERBLOCK_OK) {
return err;
}
session.blockHashes = blockHashes;
session.challengeState = ChallengeState.RespondMerkleRootHashes;
return ERR_SUPERBLOCK_OK;
}
return ERR_SUPERBLOCK_BAD_STATUS;
}
// @dev - For the submitter to respond to challenger queries
function respondMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId, bytes32[] blockHashes) onlyClaimant(sessionId) public {
BattleSession storage session = sessions[sessionId];
uint err = doVerifyMerkleRootHashes(session, blockHashes);
if (err != 0) {
emit ErrorBattle(sessionId, err);
} else {
session.actionsCounter += 1;
session.lastActionTimestamp = block.timestamp;
session.lastActionClaimant = session.actionsCounter;
emit RespondMerkleRootHashes(superblockHash, sessionId, session.challenger, blockHashes);
}
}
// @dev - Challenger makes a query for block header data for a hash
function doQueryBlockHeader(BattleSession storage session, bytes32 blockHash) internal returns (uint) {
if (!hasDeposit(msg.sender, respondBlockHeaderCost)) {
return ERR_SUPERBLOCK_MIN_DEPOSIT;
}
if ((session.countBlockHeaderQueries == 0 && session.challengeState == ChallengeState.RespondMerkleRootHashes) ||
(session.countBlockHeaderQueries > 0 && session.challengeState == ChallengeState.RespondBlockHeader)) {
require(session.countBlockHeaderQueries < session.blockHashes.length);
require(session.blocksInfo[blockHash].status == BlockInfoStatus.Uninitialized);
(uint err, ) = bondDeposit(session.superblockHash, msg.sender, respondBlockHeaderCost);
if (err != ERR_SUPERBLOCK_OK) {
return err;
}
session.countBlockHeaderQueries += 1;
session.blocksInfo[blockHash].status = BlockInfoStatus.Requested;
session.challengeState = ChallengeState.QueryBlockHeader;
return ERR_SUPERBLOCK_OK;
}
return ERR_SUPERBLOCK_BAD_STATUS;
}
// @dev - For the challenger to start a query
function queryBlockHeader(bytes32 superblockHash, bytes32 sessionId, bytes32 blockHash) onlyChallenger(sessionId) public {
BattleSession storage session = sessions[sessionId];
uint err = doQueryBlockHeader(session, blockHash);
if (err != ERR_SUPERBLOCK_OK) {
emit ErrorBattle(sessionId, err);
} else {
session.actionsCounter += 1;
session.lastActionTimestamp = block.timestamp;
session.lastActionChallenger = session.actionsCounter;
emit QueryBlockHeader(superblockHash, sessionId, session.submitter, blockHash);
}
}
// @dev - Verify that block timestamp is in the superblock timestamp interval
function verifyTimestamp(bytes32 superblockHash, bytes blockHeader) internal view returns (bool) {
uint blockTimestamp = SyscoinMessageLibrary.getTimestamp(blockHeader);
uint superblockTimestamp;
(, , superblockTimestamp, , , , , ,,) = getSuperblockInfo(superblockHash);
// Block timestamp to be within the expected timestamp of the superblock
return (blockTimestamp <= superblockTimestamp)
&& (blockTimestamp / superblockDuration >= superblockTimestamp / superblockDuration - 1);
}
// @dev - Verify Syscoin block AuxPoW
function verifyBlockAuxPoW(
BlockInfo storage blockInfo,
bytes32 blockHash,
bytes blockHeader
) internal returns (uint, bytes) {
(uint err, bool isMergeMined) =
SyscoinMessageLibrary.verifyBlockHeader(blockHeader, 0, uint(blockHash));
if (err != 0) {
return (err, new bytes(0));
}
bytes memory powBlockHeader = (isMergeMined) ?
SyscoinMessageLibrary.sliceArray(blockHeader, blockHeader.length - 80, blockHeader.length) :
SyscoinMessageLibrary.sliceArray(blockHeader, 0, 80);
blockInfo.timestamp = SyscoinMessageLibrary.getTimestamp(blockHeader);
blockInfo.bits = SyscoinMessageLibrary.getBits(blockHeader);
blockInfo.prevBlock = bytes32(SyscoinMessageLibrary.getHashPrevBlock(blockHeader));
blockInfo.blockHash = blockHash;
blockInfo.powBlockHeader = powBlockHeader;
return (ERR_SUPERBLOCK_OK, powBlockHeader);
}
// @dev - Verify block header sent by challenger
function doVerifyBlockHeader(
BattleSession storage session,
bytes memory blockHeader
) internal returns (uint, bytes) {
if (!hasDeposit(msg.sender, respondBlockHeaderCost)) {
return (ERR_SUPERBLOCK_MIN_DEPOSIT, new bytes(0));
}
if (session.challengeState == ChallengeState.QueryBlockHeader) {
bytes32 blockSha256Hash = bytes32(SyscoinMessageLibrary.dblShaFlipMem(blockHeader, 0, 80));
BlockInfo storage blockInfo = session.blocksInfo[blockSha256Hash];
if (blockInfo.status != BlockInfoStatus.Requested) {
return (ERR_SUPERBLOCK_BAD_SYSCOIN_STATUS, new bytes(0));
}
if (!verifyTimestamp(session.superblockHash, blockHeader)) {
return (ERR_SUPERBLOCK_BAD_TIMESTAMP, new bytes(0));
}
// pass in blockSha256Hash here instead of proposedScryptHash because we
// don't need a proposed hash (we already calculated it here, syscoin uses
// sha256 just like bitcoin)
(uint err, bytes memory powBlockHeader) =
verifyBlockAuxPoW(blockInfo, blockSha256Hash, blockHeader);
if (err != ERR_SUPERBLOCK_OK) {
return (err, new bytes(0));
}
// set to verify block header status
blockInfo.status = BlockInfoStatus.Verified;
(err, ) = bondDeposit(session.superblockHash, msg.sender, respondBlockHeaderCost);
if (err != ERR_SUPERBLOCK_OK) {
return (err, new bytes(0));
}
session.countBlockHeaderResponses += 1;
// if header responses matches num block hashes we skip to respond block header instead of pending verification
if (session.countBlockHeaderResponses == session.blockHashes.length) {
session.challengeState = ChallengeState.PendingVerification;
} else {
session.challengeState = ChallengeState.RespondBlockHeader;
}
return (ERR_SUPERBLOCK_OK, powBlockHeader);
}
return (ERR_SUPERBLOCK_BAD_STATUS, new bytes(0));
}
// @dev - For the submitter to respond to challenger queries
function respondBlockHeader(
bytes32 superblockHash,
bytes32 sessionId,
bytes memory blockHeader
) onlyClaimant(sessionId) public {
BattleSession storage session = sessions[sessionId];
(uint err, bytes memory powBlockHeader) = doVerifyBlockHeader(session, blockHeader);
if (err != 0) {
emit ErrorBattle(sessionId, err);
} else {
session.actionsCounter += 1;
session.lastActionTimestamp = block.timestamp;
session.lastActionClaimant = session.actionsCounter;
emit RespondBlockHeader(superblockHash, sessionId, session.challenger, blockHeader, powBlockHeader);
}
}
// @dev - Validate superblock information from last blocks
function validateLastBlocks(BattleSession storage session) internal view returns (uint) {
if (session.blockHashes.length <= 0) {
return ERR_SUPERBLOCK_BAD_LASTBLOCK;
}
uint lastTimestamp;
uint prevTimestamp;
uint32 lastBits;
bytes32 parentId;
(, , lastTimestamp, prevTimestamp, , lastBits, parentId,,,) = getSuperblockInfo(session.superblockHash);
bytes32 blockSha256Hash = session.blockHashes[session.blockHashes.length - 1];
if (session.blocksInfo[blockSha256Hash].timestamp != lastTimestamp) {
return ERR_SUPERBLOCK_BAD_TIMESTAMP;
}
if (session.blocksInfo[blockSha256Hash].bits != lastBits) {
return ERR_SUPERBLOCK_BAD_BITS;
}
if (prevTimestamp > lastTimestamp) {
return ERR_SUPERBLOCK_BAD_TIMESTAMP;
}
return ERR_SUPERBLOCK_OK;
}
// @dev - Validate superblock accumulated work
function validateProofOfWork(BattleSession storage session) internal view returns (uint) {
uint accWork;
bytes32 prevBlock;
uint32 prevHeight;
uint32 proposedHeight;
uint prevTimestamp;
(, accWork, , prevTimestamp, , , prevBlock, ,,proposedHeight) = getSuperblockInfo(session.superblockHash);
uint parentTimestamp;
uint32 prevBits;
uint work;
(, work, parentTimestamp, , prevBlock, prevBits, , , ,prevHeight) = getSuperblockInfo(prevBlock);
if (proposedHeight != (prevHeight+uint32(session.blockHashes.length))) {
return ERR_SUPERBLOCK_BAD_BLOCKHEIGHT;
}
uint ret = validateSuperblockProofOfWork(session, parentTimestamp, prevHeight, work, accWork, prevTimestamp, prevBits, prevBlock);
if(ret != 0){
return ret;
}
return ERR_SUPERBLOCK_OK;
}
function validateSuperblockProofOfWork(BattleSession storage session, uint parentTimestamp, uint32 prevHeight, uint work, uint accWork, uint prevTimestamp, uint32 prevBits, bytes32 prevBlock) internal view returns (uint){
uint32 idx = 0;
while (idx < session.blockHashes.length) {
bytes32 blockSha256Hash = session.blockHashes[idx];
uint32 bits = session.blocksInfo[blockSha256Hash].bits;
if (session.blocksInfo[blockSha256Hash].prevBlock != prevBlock) {
return ERR_SUPERBLOCK_BAD_PARENT;
}
if (net != SyscoinMessageLibrary.Network.REGTEST) {
uint32 newBits;
if (net == SyscoinMessageLibrary.Network.TESTNET && session.blocksInfo[blockSha256Hash].timestamp - parentTimestamp > 120) {
newBits = 0x1e0fffff;
}
else if((prevHeight+idx+1) % SyscoinMessageLibrary.difficultyAdjustmentInterval() != 0){
newBits = prevBits;
}
else{
newBits = SyscoinMessageLibrary.calculateDifficulty(int64(parentTimestamp) - int64(prevTimestamp), prevBits);
prevTimestamp = parentTimestamp;
prevBits = bits;
}
if (bits != newBits) {
return ERR_SUPERBLOCK_BAD_BITS;
}
}
work += SyscoinMessageLibrary.diffFromBits(bits);
prevBlock = blockSha256Hash;
parentTimestamp = session.blocksInfo[blockSha256Hash].timestamp;
idx += 1;
}
if (net != SyscoinMessageLibrary.Network.REGTEST && work != accWork) {
return ERR_SUPERBLOCK_BAD_ACCUMULATED_WORK;
}
return 0;
}
// @dev - Verify whether a superblock's data is consistent
// Only should be called when all blocks header were submitted
function doVerifySuperblock(BattleSession storage session, bytes32 sessionId) internal returns (uint) {
if (session.challengeState == ChallengeState.PendingVerification) {
uint err;
err = validateLastBlocks(session);
if (err != 0) {
emit ErrorBattle(sessionId, err);
return 2;
}
err = validateProofOfWork(session);
if (err != 0) {
emit ErrorBattle(sessionId, err);
return 2;
}
return 1;
} else if (session.challengeState == ChallengeState.SuperblockFailed) {
return 2;
}
return 0;
}
// @dev - Perform final verification once all blocks were submitted
function verifySuperblock(bytes32 sessionId) public {
BattleSession storage session = sessions[sessionId];
uint status = doVerifySuperblock(session, sessionId);
if (status == 1) {
convictChallenger(sessionId, session.challenger, session.superblockHash);
} else if (status == 2) {
convictSubmitter(sessionId, session.submitter, session.superblockHash);
}
}
// @dev - Trigger conviction if response is not received in time
function timeout(bytes32 sessionId) public returns (uint) {
BattleSession storage session = sessions[sessionId];
if (session.challengeState == ChallengeState.SuperblockFailed ||
(session.lastActionChallenger > session.lastActionClaimant &&
block.timestamp > session.lastActionTimestamp + superblockTimeout)) {
convictSubmitter(sessionId, session.submitter, session.superblockHash);
return ERR_SUPERBLOCK_OK;
} else if (session.lastActionClaimant > session.lastActionChallenger &&
block.timestamp > session.lastActionTimestamp + superblockTimeout) {
convictChallenger(sessionId, session.challenger, session.superblockHash);
return ERR_SUPERBLOCK_OK;
}
emit ErrorBattle(sessionId, ERR_SUPERBLOCK_NO_TIMEOUT);
return ERR_SUPERBLOCK_NO_TIMEOUT;
}
// @dev - To be called when a challenger is convicted
function convictChallenger(bytes32 sessionId, address challenger, bytes32 superblockHash) internal {
BattleSession storage session = sessions[sessionId];
sessionDecided(sessionId, superblockHash, session.submitter, session.challenger);
disable(sessionId);
emit ChallengerConvicted(superblockHash, sessionId, challenger);
}
// @dev - To be called when a submitter is convicted
function convictSubmitter(bytes32 sessionId, address submitter, bytes32 superblockHash) internal {
BattleSession storage session = sessions[sessionId];
sessionDecided(sessionId, superblockHash, session.challenger, session.submitter);
disable(sessionId);
emit SubmitterConvicted(superblockHash, sessionId, submitter);
}
// @dev - Disable session
// It should be called only when either the submitter or the challenger were convicted.
function disable(bytes32 sessionId) internal {
delete sessions[sessionId];
}
// @dev - Check if a session's challenger did not respond before timeout
function getChallengerHitTimeout(bytes32 sessionId) public view returns (bool) {
BattleSession storage session = sessions[sessionId];
return (session.lastActionClaimant > session.lastActionChallenger &&
block.timestamp > session.lastActionTimestamp + superblockTimeout);
}
// @dev - Check if a session's submitter did not respond before timeout
function getSubmitterHitTimeout(bytes32 sessionId) public view returns (bool) {
BattleSession storage session = sessions[sessionId];
return (session.lastActionChallenger > session.lastActionClaimant &&
block.timestamp > session.lastActionTimestamp + superblockTimeout);
}
// @dev - Return Syscoin block hashes associated with a certain battle session
function getSyscoinBlockHashes(bytes32 sessionId) public view returns (bytes32[]) {
return sessions[sessionId].blockHashes;
}
// @dev - To be called when a battle sessions was decided
function sessionDecided(bytes32 sessionId, bytes32 superblockHash, address winner, address loser) internal {
trustedSyscoinClaimManager.sessionDecided(sessionId, superblockHash, winner, loser);
}
// @dev - Retrieve superblock information
function getSuperblockInfo(bytes32 superblockHash) internal view returns (
bytes32 _blocksMerkleRoot,
uint _accumulatedWork,
uint _timestamp,
uint _prevTimestamp,
bytes32 _lastHash,
uint32 _lastBits,
bytes32 _parentId,
address _submitter,
SyscoinSuperblocks.Status _status,
uint32 _height
) {
return trustedSuperblocks.getSuperblock(superblockHash);
}
// @dev - Verify whether a user has a certain amount of deposits or more
function hasDeposit(address who, uint amount) internal view returns (bool) {
return trustedSyscoinClaimManager.getDeposit(who) >= amount;
}
// @dev – locks up part of a user's deposit into a claim.
function bondDeposit(bytes32 superblockHash, address account, uint amount) internal returns (uint, uint) {
return trustedSyscoinClaimManager.bondDeposit(superblockHash, account, amount);
}
} |
bytes32 sessionId = keccak256(abi.encode(superblockHash, msg.sender, sessionsCount));
BattleSession storage session = sessions[sessionId];
session.id = sessionId;
session.superblockHash = superblockHash;
session.submitter = submitter;
session.challenger = challenger;
session.lastActionTimestamp = block.timestamp;
session.lastActionChallenger = 0;
session.lastActionClaimant = 1; // Force challenger to start
session.actionsCounter = 1;
session.challengeState = ChallengeState.Challenged;
sessionsCount += 1;
emit NewBattle(superblockHash, sessionId, submitter, challenger);
return sessionId;
| function beginBattleSession(bytes32 superblockHash, address submitter, address challenger)
onlyFrom(trustedSyscoinClaimManager) public returns (bytes32) | // @dev - Start a battle session
function beginBattleSession(bytes32 superblockHash, address submitter, address challenger)
onlyFrom(trustedSyscoinClaimManager) public returns (bytes32) |
41732 | Operator | addOperator | contract Operator is Ownable {
address[] public operators;
uint public MAX_OPS = 20; // Default maximum number of operators allowed
mapping(address => bool) public isOperator;
event OperatorAdded(address operator);
event OperatorRemoved(address operator);
// @dev Throws if called by any non-operator account. Owner has all ops rights.
modifier onlyOperator() {
require(
isOperator[msg.sender] || msg.sender == owner,
"Permission denied. Must be an operator or the owner."
);
_;
}
/**
* @dev Allows the current owner or operators to add operators
* @param _newOperator New operator address
*/
function addOperator(address _newOperator) public onlyOwner {<FILL_FUNCTION_BODY> }
/**
* @dev Allows the current owner or operators to remove operator
* @param _operator Address of the operator to be removed
*/
function removeOperator(address _operator) public onlyOwner {
// Make sure operators array is not empty
require(
operators.length > 0,
"No operator."
);
// Make sure the operator exists
require(
isOperator[_operator],
"Not an operator."
);
// Manual array manipulation:
// - replace the _operator with last operator in array
// - remove the last item from array
address lastOperator = operators[operators.length - 1];
for (uint i = 0; i < operators.length; i++) {
if (operators[i] == _operator) {
operators[i] = lastOperator;
}
}
operators.length -= 1; // remove the last element
isOperator[_operator] = false;
emit OperatorRemoved(_operator);
}
// @dev Remove ALL operators
function removeAllOps() public onlyOwner {
for (uint i = 0; i < operators.length; i++) {
isOperator[operators[i]] = false;
}
operators.length = 0;
}
} | contract Operator is Ownable {
address[] public operators;
uint public MAX_OPS = 20; // Default maximum number of operators allowed
mapping(address => bool) public isOperator;
event OperatorAdded(address operator);
event OperatorRemoved(address operator);
// @dev Throws if called by any non-operator account. Owner has all ops rights.
modifier onlyOperator() {
require(
isOperator[msg.sender] || msg.sender == owner,
"Permission denied. Must be an operator or the owner."
);
_;
}
<FILL_FUNCTION>
/**
* @dev Allows the current owner or operators to remove operator
* @param _operator Address of the operator to be removed
*/
function removeOperator(address _operator) public onlyOwner {
// Make sure operators array is not empty
require(
operators.length > 0,
"No operator."
);
// Make sure the operator exists
require(
isOperator[_operator],
"Not an operator."
);
// Manual array manipulation:
// - replace the _operator with last operator in array
// - remove the last item from array
address lastOperator = operators[operators.length - 1];
for (uint i = 0; i < operators.length; i++) {
if (operators[i] == _operator) {
operators[i] = lastOperator;
}
}
operators.length -= 1; // remove the last element
isOperator[_operator] = false;
emit OperatorRemoved(_operator);
}
// @dev Remove ALL operators
function removeAllOps() public onlyOwner {
for (uint i = 0; i < operators.length; i++) {
isOperator[operators[i]] = false;
}
operators.length = 0;
}
} |
require(
_newOperator != address(0),
"Invalid new operator address."
);
// Make sure no dups
require(
!isOperator[_newOperator],
"New operator exists."
);
// Only allow so many ops
require(
operators.length < MAX_OPS,
"Overflow."
);
operators.push(_newOperator);
isOperator[_newOperator] = true;
emit OperatorAdded(_newOperator);
| function addOperator(address _newOperator) public onlyOwner | /**
* @dev Allows the current owner or operators to add operators
* @param _newOperator New operator address
*/
function addOperator(address _newOperator) public onlyOwner |
10075 | Crowdsale | createTokens | contract Crowdsale is Ownable {
using SafeMath for uint;
address multisig;
uint restrictedPercent;
address restricted;
SimpleCoinToken public token = new SimpleCoinToken();
uint start;
uint period;
uint rate;
function Crowdsale() {
multisig = 0x47eA2E23c695a56730936a651136E57CB1b40610;
restricted = 0x47eA2E23c695a56730936a651136E57CB1b40610;
restrictedPercent = 60;
rate = 2000000000000000000000;
start = 1621918800;
period = 730;
}
modifier saleIsOn() {
require(now > start && now < start + period * 1 days);
_;
}
function createTokens() saleIsOn payable {<FILL_FUNCTION_BODY> }
function() external payable {
createTokens();
}
} | contract Crowdsale is Ownable {
using SafeMath for uint;
address multisig;
uint restrictedPercent;
address restricted;
SimpleCoinToken public token = new SimpleCoinToken();
uint start;
uint period;
uint rate;
function Crowdsale() {
multisig = 0x47eA2E23c695a56730936a651136E57CB1b40610;
restricted = 0x47eA2E23c695a56730936a651136E57CB1b40610;
restrictedPercent = 60;
rate = 2000000000000000000000;
start = 1621918800;
period = 730;
}
modifier saleIsOn() {
require(now > start && now < start + period * 1 days);
_;
}
<FILL_FUNCTION>
function() external payable {
createTokens();
}
} |
multisig.transfer(msg.value);
uint tokens = rate.mul(msg.value).div(1 ether);
uint bonusTokens = 0;
if(now < start + (period * 1 days).div(4)) {
bonusTokens = tokens.div(5);
} else if(now >= start + (period * 1 days).div(4) && now < start + (period * 1 days).div(4).mul(2)) {
bonusTokens = tokens.div(10);
} else if(now >= start + (period * 1 days).div(4).mul(2) && now < start + (period * 1 days).div(4).mul(3)) {
bonusTokens = tokens.div(20);
} else if(now >= start + (period * 1 days).div(4).mul(3) && now < start + (period * 1 days).div(4).mul(4)) {
bonusTokens = tokens.div(50);
}
uint tokensWithBonus = tokens.add(bonusTokens);
token.transfer(msg.sender, tokensWithBonus);
uint restrictedTokens = tokens.mul(restrictedPercent).div(100 - restrictedPercent);
token.transfer(restricted, restrictedTokens);
| function createTokens() saleIsOn payable | function createTokens() saleIsOn payable |
93921 | TIMO | null | contract TIMO is Token{
constructor() public{<FILL_FUNCTION_BODY> }
receive () payable external {
require(msg.value>0);
owner.transfer(msg.value);
}
} | contract TIMO is Token{
<FILL_FUNCTION>
receive () payable external {
require(msg.value>0);
owner.transfer(msg.value);
}
} |
symbol = "TIMO";
name = "TIMO Finance";
decimals = 18;
totalSupply = 8000000000000000000000;
owner = msg.sender;
balances[owner] = totalSupply;
| constructor() public | constructor() public |
75577 | Upgradable | endUpgrade | contract Upgradable is Ownable {
struct UpgradableState {
bool isUpgrading;
address prevVersion;
address nextVersion;
}
UpgradableState public upgradableState;
event Initialized(address indexed prevVersion);
event Upgrading(address indexed nextVersion);
event Upgraded(address indexed nextVersion);
modifier isLastestVersion {
require(!upgradableState.isUpgrading);
require(upgradableState.nextVersion == address(0));
_;
}
modifier onlyOwnerOrigin {
require(tx.origin == owner);
_;
}
function Upgradable(address _prevVersion) public {
if (_prevVersion != address(0)) {
require(msg.sender == Ownable(_prevVersion).owner());
upgradableState.isUpgrading = true;
upgradableState.prevVersion = _prevVersion;
IUpgradable(_prevVersion).startUpgrade();
} else {
Initialized(_prevVersion);
}
}
function startUpgrade() public onlyOwnerOrigin {
require(msg.sender != owner);
require(!upgradableState.isUpgrading);
require(upgradableState.nextVersion == 0);
upgradableState.isUpgrading = true;
upgradableState.nextVersion = msg.sender;
Upgrading(msg.sender);
}
//function upgrade(uint index, uint size) public onlyOwner {}
function endUpgrade() public onlyOwnerOrigin {<FILL_FUNCTION_BODY> }
} | contract Upgradable is Ownable {
struct UpgradableState {
bool isUpgrading;
address prevVersion;
address nextVersion;
}
UpgradableState public upgradableState;
event Initialized(address indexed prevVersion);
event Upgrading(address indexed nextVersion);
event Upgraded(address indexed nextVersion);
modifier isLastestVersion {
require(!upgradableState.isUpgrading);
require(upgradableState.nextVersion == address(0));
_;
}
modifier onlyOwnerOrigin {
require(tx.origin == owner);
_;
}
function Upgradable(address _prevVersion) public {
if (_prevVersion != address(0)) {
require(msg.sender == Ownable(_prevVersion).owner());
upgradableState.isUpgrading = true;
upgradableState.prevVersion = _prevVersion;
IUpgradable(_prevVersion).startUpgrade();
} else {
Initialized(_prevVersion);
}
}
function startUpgrade() public onlyOwnerOrigin {
require(msg.sender != owner);
require(!upgradableState.isUpgrading);
require(upgradableState.nextVersion == 0);
upgradableState.isUpgrading = true;
upgradableState.nextVersion = msg.sender;
Upgrading(msg.sender);
}
<FILL_FUNCTION>
} |
require(upgradableState.isUpgrading);
upgradableState.isUpgrading = false;
if (msg.sender != owner) {
require(upgradableState.nextVersion == msg.sender);
Upgraded(upgradableState.nextVersion);
}
else {
if (upgradableState.prevVersion != address(0)) {
Upgradable(upgradableState.prevVersion).endUpgrade();
}
Initialized(upgradableState.prevVersion);
}
| function endUpgrade() public onlyOwnerOrigin | //function upgrade(uint index, uint size) public onlyOwner {}
function endUpgrade() public onlyOwnerOrigin |
16292 | SetSire | setRabbitSirePrice | contract SetSire {
event ChengeSex(uint32 bunnyId, uint256 price);
address public pubAddress;
PublicInterface publicContract;
constructor() public {
transferContract(0x2Ed020b084F7a58Ce7AC5d86496dC4ef48413a24);
}
function transferContract(address _pubAddress) public {
require(_pubAddress != address(0));
pubAddress = _pubAddress;
publicContract = PublicInterface(_pubAddress);
}
function setRabbitSirePrice (
uint32 bunny_1,
uint price_1,
uint32 bunny_2,
uint price_2,
uint32 bunny_3,
uint price_3,
uint32 bunny_4,
uint price_4,
uint32 bunny_5,
uint price_5,
uint32 bunny_6,
uint price_6
) public {<FILL_FUNCTION_BODY> }
} | contract SetSire {
event ChengeSex(uint32 bunnyId, uint256 price);
address public pubAddress;
PublicInterface publicContract;
constructor() public {
transferContract(0x2Ed020b084F7a58Ce7AC5d86496dC4ef48413a24);
}
function transferContract(address _pubAddress) public {
require(_pubAddress != address(0));
pubAddress = _pubAddress;
publicContract = PublicInterface(_pubAddress);
}
<FILL_FUNCTION>
} |
if(publicContract.getRabbitSirePrice(bunny_1) == 0 && price_1 != 0){
publicContract.setRabbitSirePrice(bunny_1, price_1);
emit ChengeSex(bunny_1, publicContract.getRabbitSirePrice(bunny_1));
}
if(publicContract.getRabbitSirePrice(bunny_2) == 0 && price_2 != 0){
publicContract.setRabbitSirePrice(bunny_2, price_2);
emit ChengeSex(bunny_2, publicContract.getRabbitSirePrice(bunny_2));
}
if(publicContract.getRabbitSirePrice(bunny_3) == 0 && price_3 != 0){
publicContract.setRabbitSirePrice(bunny_3, price_3);
emit ChengeSex(bunny_3, publicContract.getRabbitSirePrice(bunny_3));
}
if(publicContract.getRabbitSirePrice(bunny_4) == 0 && price_4 != 0){
publicContract.setRabbitSirePrice(bunny_4, price_4);
emit ChengeSex(bunny_4, publicContract.getRabbitSirePrice(bunny_4));
}
if(publicContract.getRabbitSirePrice(bunny_5) == 0 && price_5 != 0){
publicContract.setRabbitSirePrice(bunny_5, price_5);
emit ChengeSex(bunny_5, publicContract.getRabbitSirePrice(bunny_5));
}
if(publicContract.getRabbitSirePrice(bunny_6) == 0 && price_6 != 0){
publicContract.setRabbitSirePrice(bunny_6, price_6);
emit ChengeSex(bunny_6, publicContract.getRabbitSirePrice(bunny_6));
}
| function setRabbitSirePrice (
uint32 bunny_1,
uint price_1,
uint32 bunny_2,
uint price_2,
uint32 bunny_3,
uint price_3,
uint32 bunny_4,
uint price_4,
uint32 bunny_5,
uint price_5,
uint32 bunny_6,
uint price_6
) public | function setRabbitSirePrice (
uint32 bunny_1,
uint price_1,
uint32 bunny_2,
uint price_2,
uint32 bunny_3,
uint price_3,
uint32 bunny_4,
uint price_4,
uint32 bunny_5,
uint price_5,
uint32 bunny_6,
uint price_6
) public |
21537 | CrossroadsCoin | transferFrom | contract CrossroadsCoin is SafeMath {
address public owner;
string public name;
string public symbol;
uint8 public constant decimals = 18;
uint16 public constant exchangeRate = 10000; // handling fee, 1/10000
uint256 public initialRate; // initial ether to CRC rate
uint256 public minRate; // min ether to CRC rate, minRate should no more than initial rate
// rate curve: rate(x) = initialRate - x / k, x represent address(this).balance
// k should meet minRate = initialRate - destEtherNum / k
// so k value is destEtherNum / (initialRate - minRate)
uint256 public destEtherNum; // when contract receive destEtherNum ether, all CRC released
uint256 public k;
// supply curve: totalSupply = initialRate * x - x^2/(2*k);
// so, while x reach to destEtherNum, the totalSupply = destEtherNum * (initialRate + minRate) / 2
uint256 public totalSupply = 0; // current supply is 0
/* This creates an array with all balances */
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approve(address indexed from, address indexed to, uint256 value);
event Exchange(address indexed who, uint256 value); // use ether exchange CRC
event Redeem(address indexed who, uint256 value); // use CRC redeem ether
// can accept ether, exchange CRC to msg.sender
function() public payable {
require(address(this).balance <= destEtherNum);
uint256 newSupply = calSupply(address(this).balance);
uint256 returnCRCNum = SafeMath.safeSub(newSupply, totalSupply);
totalSupply = newSupply;
if (msg.sender != owner) {
uint256 fee = SafeMath.safeDiv(returnCRCNum, exchangeRate);
balanceOf[owner] = SafeMath.safeAdd(balanceOf[owner],
fee);
emit Transfer(msg.sender, owner, fee);
returnCRCNum = SafeMath.safeSub(returnCRCNum, fee);
}
balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender],
returnCRCNum);
emit Exchange(msg.sender, returnCRCNum);
emit Transfer(address(0x0), msg.sender, returnCRCNum);
}
// rate curve: rate(x) = initialRate - x / k, x represent address(this).balance
function calRate() public view returns (uint256){
uint256 x = address(this).balance;
return SafeMath.safeSub(initialRate, SafeMath.safeDiv(x, k));
}
// x represent address(this).balance
// totalSupply = initialRate * x - x^2/(2*k)
function calSupply(uint256 x) public view returns (uint256){
uint256 opt1 = SafeMath.safeMul(initialRate, x);
uint256 opt2 = SafeMath.safeDiv(SafeMath.safeMul(x, x),
SafeMath.safeMul(2, k));
return SafeMath.safeSub(opt1, opt2);
}
// because totalSupply = initialRate * x - x^2/(2*k), x represent address(this).balance
// so, x = initialRate * k - sqrt((initialRate * k)^2 - 2 * k * totalSupply)
function calEtherNumBySupply(uint256 y) public view returns (uint256){
uint256 opt1 = SafeMath.safeMul(initialRate, k);
uint256 sqrtOpt1 = SafeMath.safeMul(opt1, opt1);
uint256 sqrtOpt2 = SafeMath.safeMul(2, SafeMath.safeMul(k, y));
uint256 sqrtRes = SafeMath.safeSqrt(SafeMath.safeSub(sqrtOpt1, sqrtOpt2));
return SafeMath.safeSub(SafeMath.safeMul(initialRate, k), sqrtRes);
}
/* Initializes contract with initial supply tokens to the creator of the contract */
constructor(uint256 _initialRate, uint256 _minRate, uint256 _destEtherNum) public {
owner = msg.sender;
name = "CrossroadsCoin";
symbol = "CRC";
// set exchangeRate
require(_minRate <= _initialRate);
require(_destEtherNum > 0);
initialRate = _initialRate;
minRate = _minRate;
destEtherNum = _destEtherNum;
k = SafeMath.safeDiv(_destEtherNum, SafeMath.safeSub(_initialRate, _minRate));
}
/* Send coins */
function transfer(address _to, uint256 _value)
public {
// Prevent transfer to 0x0 address.
require(_to != 0x0);
require(_value > 0);
// Check if the sender has enough
require(balanceOf[msg.sender] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
if (_to == address(this)) {
redeem(_value);
} else {
// Add the _value to the recipient
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value);
}
// Subtract from the sender
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value);
// Notify anyone listening that this transfer took place
emit Transfer(msg.sender, _to, _value);
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value)
public returns (bool success) {
require(_value > 0);
allowance[msg.sender][_spender] = _value;
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool success) {<FILL_FUNCTION_BODY> }
function redeem(uint256 _value) private {
if (msg.sender != owner) {
uint256 fee = SafeMath.safeDiv(_value, exchangeRate);
balanceOf[owner] = SafeMath.safeAdd(balanceOf[owner], fee);
emit Transfer(msg.sender, owner, fee);
_value = SafeMath.safeSub(_value, fee);
}
uint256 newSupply = SafeMath.safeSub(totalSupply, _value);
require(newSupply >= 0);
uint256 newEtherNum = calEtherNumBySupply(newSupply);
uint256 etherBalance = address(this).balance;
require(newEtherNum <= etherBalance);
uint256 redeemEtherNum = SafeMath.safeSub(etherBalance, newEtherNum);
msg.sender.transfer(redeemEtherNum);
totalSupply = newSupply;
emit Redeem(msg.sender, redeemEtherNum);
}
} | contract CrossroadsCoin is SafeMath {
address public owner;
string public name;
string public symbol;
uint8 public constant decimals = 18;
uint16 public constant exchangeRate = 10000; // handling fee, 1/10000
uint256 public initialRate; // initial ether to CRC rate
uint256 public minRate; // min ether to CRC rate, minRate should no more than initial rate
// rate curve: rate(x) = initialRate - x / k, x represent address(this).balance
// k should meet minRate = initialRate - destEtherNum / k
// so k value is destEtherNum / (initialRate - minRate)
uint256 public destEtherNum; // when contract receive destEtherNum ether, all CRC released
uint256 public k;
// supply curve: totalSupply = initialRate * x - x^2/(2*k);
// so, while x reach to destEtherNum, the totalSupply = destEtherNum * (initialRate + minRate) / 2
uint256 public totalSupply = 0; // current supply is 0
/* This creates an array with all balances */
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approve(address indexed from, address indexed to, uint256 value);
event Exchange(address indexed who, uint256 value); // use ether exchange CRC
event Redeem(address indexed who, uint256 value); // use CRC redeem ether
// can accept ether, exchange CRC to msg.sender
function() public payable {
require(address(this).balance <= destEtherNum);
uint256 newSupply = calSupply(address(this).balance);
uint256 returnCRCNum = SafeMath.safeSub(newSupply, totalSupply);
totalSupply = newSupply;
if (msg.sender != owner) {
uint256 fee = SafeMath.safeDiv(returnCRCNum, exchangeRate);
balanceOf[owner] = SafeMath.safeAdd(balanceOf[owner],
fee);
emit Transfer(msg.sender, owner, fee);
returnCRCNum = SafeMath.safeSub(returnCRCNum, fee);
}
balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender],
returnCRCNum);
emit Exchange(msg.sender, returnCRCNum);
emit Transfer(address(0x0), msg.sender, returnCRCNum);
}
// rate curve: rate(x) = initialRate - x / k, x represent address(this).balance
function calRate() public view returns (uint256){
uint256 x = address(this).balance;
return SafeMath.safeSub(initialRate, SafeMath.safeDiv(x, k));
}
// x represent address(this).balance
// totalSupply = initialRate * x - x^2/(2*k)
function calSupply(uint256 x) public view returns (uint256){
uint256 opt1 = SafeMath.safeMul(initialRate, x);
uint256 opt2 = SafeMath.safeDiv(SafeMath.safeMul(x, x),
SafeMath.safeMul(2, k));
return SafeMath.safeSub(opt1, opt2);
}
// because totalSupply = initialRate * x - x^2/(2*k), x represent address(this).balance
// so, x = initialRate * k - sqrt((initialRate * k)^2 - 2 * k * totalSupply)
function calEtherNumBySupply(uint256 y) public view returns (uint256){
uint256 opt1 = SafeMath.safeMul(initialRate, k);
uint256 sqrtOpt1 = SafeMath.safeMul(opt1, opt1);
uint256 sqrtOpt2 = SafeMath.safeMul(2, SafeMath.safeMul(k, y));
uint256 sqrtRes = SafeMath.safeSqrt(SafeMath.safeSub(sqrtOpt1, sqrtOpt2));
return SafeMath.safeSub(SafeMath.safeMul(initialRate, k), sqrtRes);
}
/* Initializes contract with initial supply tokens to the creator of the contract */
constructor(uint256 _initialRate, uint256 _minRate, uint256 _destEtherNum) public {
owner = msg.sender;
name = "CrossroadsCoin";
symbol = "CRC";
// set exchangeRate
require(_minRate <= _initialRate);
require(_destEtherNum > 0);
initialRate = _initialRate;
minRate = _minRate;
destEtherNum = _destEtherNum;
k = SafeMath.safeDiv(_destEtherNum, SafeMath.safeSub(_initialRate, _minRate));
}
/* Send coins */
function transfer(address _to, uint256 _value)
public {
// Prevent transfer to 0x0 address.
require(_to != 0x0);
require(_value > 0);
// Check if the sender has enough
require(balanceOf[msg.sender] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
if (_to == address(this)) {
redeem(_value);
} else {
// Add the _value to the recipient
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value);
}
// Subtract from the sender
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value);
// Notify anyone listening that this transfer took place
emit Transfer(msg.sender, _to, _value);
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value)
public returns (bool success) {
require(_value > 0);
allowance[msg.sender][_spender] = _value;
return true;
}
<FILL_FUNCTION>
function redeem(uint256 _value) private {
if (msg.sender != owner) {
uint256 fee = SafeMath.safeDiv(_value, exchangeRate);
balanceOf[owner] = SafeMath.safeAdd(balanceOf[owner], fee);
emit Transfer(msg.sender, owner, fee);
_value = SafeMath.safeSub(_value, fee);
}
uint256 newSupply = SafeMath.safeSub(totalSupply, _value);
require(newSupply >= 0);
uint256 newEtherNum = calEtherNumBySupply(newSupply);
uint256 etherBalance = address(this).balance;
require(newEtherNum <= etherBalance);
uint256 redeemEtherNum = SafeMath.safeSub(etherBalance, newEtherNum);
msg.sender.transfer(redeemEtherNum);
totalSupply = newSupply;
emit Redeem(msg.sender, redeemEtherNum);
}
} |
// Prevent transfer to 0x0 address.
require(_to != 0x0);
require(_value > 0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Check allowance
require(_value <= allowance[_from][msg.sender]);
if (_to == address(this)) {
redeem(_value);
} else {
// Add the _value to the recipient
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value);
}
// Subtract from the sender
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value);
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
emit Transfer(_from, _to, _value);
return true;
| function transferFrom(address _from, address _to, uint256 _value)
public returns (bool success) | /* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool success) |
7668 | Whitelist | add | contract Whitelist is IWhitelist, TransferableOwnership {
struct Entry {
uint datetime;
bool accepted;
uint index;
}
mapping (address => Entry) internal list;
address[] internal listIndex;
/**
* Returns whether an entry exists for `_account`
*
* @param _account The account to check
* @return whether `_account` is has an entry in the whitelist
*/
function hasEntry(address _account) public constant returns (bool) {
return listIndex.length > 0 && _account == listIndex[list[_account].index];
}
/**
* Add `_account` to the whitelist
*
* If an account is currently disabled, the account is reenabled. Otherwise
* a new entry is created
*
* @param _account The account to add
*/
function add(address _account) public only_owner {<FILL_FUNCTION_BODY> }
/**
* Remove `_account` from the whitelist
*
* Will not actually remove the entry but disable it by updating
* the accepted record
*
* @param _account The account to remove
*/
function remove(address _account) public only_owner {
if (hasEntry(_account)) {
Entry storage entry = list[_account];
entry.accepted = false;
entry.datetime = now;
}
}
/**
* Authenticate
*
* Returns whether `_account` is on the whitelist
*
* @param _account The account to authenticate
* @return whether `_account` is successfully authenticated
*/
function authenticate(address _account) public constant returns (bool) {
return list[_account].accepted;
}
} | contract Whitelist is IWhitelist, TransferableOwnership {
struct Entry {
uint datetime;
bool accepted;
uint index;
}
mapping (address => Entry) internal list;
address[] internal listIndex;
/**
* Returns whether an entry exists for `_account`
*
* @param _account The account to check
* @return whether `_account` is has an entry in the whitelist
*/
function hasEntry(address _account) public constant returns (bool) {
return listIndex.length > 0 && _account == listIndex[list[_account].index];
}
<FILL_FUNCTION>
/**
* Remove `_account` from the whitelist
*
* Will not actually remove the entry but disable it by updating
* the accepted record
*
* @param _account The account to remove
*/
function remove(address _account) public only_owner {
if (hasEntry(_account)) {
Entry storage entry = list[_account];
entry.accepted = false;
entry.datetime = now;
}
}
/**
* Authenticate
*
* Returns whether `_account` is on the whitelist
*
* @param _account The account to authenticate
* @return whether `_account` is successfully authenticated
*/
function authenticate(address _account) public constant returns (bool) {
return list[_account].accepted;
}
} |
if (!hasEntry(_account)) {
list[_account] = Entry(
now, true, listIndex.push(_account) - 1);
} else {
Entry storage entry = list[_account];
if (!entry.accepted) {
entry.accepted = true;
entry.datetime = now;
}
}
| function add(address _account) public only_owner | /**
* Add `_account` to the whitelist
*
* If an account is currently disabled, the account is reenabled. Otherwise
* a new entry is created
*
* @param _account The account to add
*/
function add(address _account) public only_owner |
29623 | Phoenix | approve | contract Phoenix is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint public initialSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "PHX";
name = "Phoenix Net";
decimals = 18;
_totalSupply = 18000000000000000000000000;
uint percentage = safeDiv(_totalSupply, 100);
initialSupply = safeMul(percentage, 90);
balances[0x4527945fE26Bb09b0782D543Ea455E6bE3AA5226] = initialSupply;
emit Transfer(address(0), 0x4527945fE26Bb09b0782D543Ea455E6bE3AA5226, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> }
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | contract Phoenix is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint public initialSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "PHX";
name = "Phoenix Net";
decimals = 18;
_totalSupply = 18000000000000000000000000;
uint percentage = safeDiv(_totalSupply, 100);
initialSupply = safeMul(percentage, 90);
balances[0x4527945fE26Bb09b0782D543Ea455E6bE3AA5226] = initialSupply;
emit Transfer(address(0), 0x4527945fE26Bb09b0782D543Ea455E6bE3AA5226, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
<FILL_FUNCTION>
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} |
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
| function approve(address spender, uint tokens) public returns (bool success) | // ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) |
352 | CarefulMath | mulUInt | contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {<FILL_FUNCTION_BODY> }
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
} | contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
<FILL_FUNCTION>
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
} |
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
| function mulUInt(uint a, uint b) internal pure returns (MathError, uint) | /**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) |
54374 | HomeWorkDeployer | phaseThree | contract HomeWorkDeployer {
// Fires when HomeWork has been deployed.
event HomeWorkDeployment(address homeAddress, bytes32 key);
// Fires HomeWork's initialization-in-runtime storage contract is deployed.
event StorageContractDeployment(address runtimeStorageContract);
// Allocate storage to track the current initialization-in-runtime contract.
address private _initializationRuntimeStorageContract;
// Once HomeWork has been deployed, disable this contract.
bool private _disabled;
// Write arbitrary code to a contract's runtime using the following prelude.
bytes11 private constant _ARBITRARY_RUNTIME_PRELUDE = bytes11(
0x600b5981380380925939f3
);
/**
* @notice Perform phase one of the deployment.
* @param code bytes The contract creation code for HomeWork.
*/
function phaseOne(bytes calldata code) external onlyUntilDisabled {
// Deploy payload to the runtime storage contract and set the address.
_initializationRuntimeStorageContract = _deployRuntimeStorageContract(
bytes32(0),
code
);
}
/**
* @notice Perform phase two of the deployment (tokenURI data).
* @param key bytes32 The salt to provide to create2.
*/
function phaseTwo(bytes32 key) external onlyUntilDisabled {
// Deploy runtime storage contract with the string used to construct end of
// token URI for issued ERC721s (data URI with a base64-encoded jpeg image).
bytes memory code = abi.encodePacked(
hex"222c226465736372697074696f6e223a22546869732532304e465425323063616e25",
hex"3230626525323072656465656d65642532306f6e253230486f6d65576f726b253230",
hex"746f2532306772616e7425323061253230636f6e74726f6c6c657225323074686525",
hex"32306578636c75736976652532307269676874253230746f2532306465706c6f7925",
hex"3230636f6e7472616374732532307769746825323061726269747261727925323062",
hex"797465636f6465253230746f25323074686525323064657369676e61746564253230",
hex"686f6d65253230616464726573732e222c22696d616765223a22646174613a696d61",
hex"67652f7376672b786d6c3b636861727365743d7574662d383b6261736536342c5048",
hex"4e325a79423462577875637a30696148523063446f764c336433647935334d793576",
hex"636d63764d6a41774d43397a646d636949485a705a58644362336739496a41674d43",
hex"41784e4451674e7a4969506a787a64486c735a543438495674445245465551567375",
hex"516e747a64484a766132557462476c755a57707661573436636d3931626d52394c6b",
hex"4e37633352796232746c4c5731706447567962476c74615851364d5442394c6b5237",
hex"633352796232746c4c5864705a48526f4f6a4a394c6b56375a6d6c7362446f6a4f57",
hex"4935596a6c686653354765334e30636d39725a5331736157356c593246774f6e4a76",
hex"6457356b66563164506a7776633352356247552b5047636764484a68626e4e6d6233",
hex"4a7450534a74595852796158676f4d5334774d694177494441674d5334774d694134",
hex"4c6a45674d436b69506a78775958526f49475a706247773949694e6d5a6d59694947",
hex"5139496b30784f53417a4d6d677a4e4859794e4567784f586f694c7a34385a79427a",
hex"64484a766132553949694d774d44416949474e7359584e7a50534a4349454d675243",
hex"492b50484268644767675a6d6c7362443069493245314e7a6b7a4f5349675a443069",
hex"545449314944517761446c324d545a6f4c546c364969382b50484268644767675a6d",
hex"6c7362443069497a6b795a444e6d4e5349675a443069545451774944517761446832",
hex"4e3267744f486f694c7a3438634746306143426d615778735053496a5a5745315954",
hex"51334969426b50534a4e4e544d674d7a4a494d546c324c5446734d5459744d545967",
hex"4d5467674d545a364969382b50484268644767675a6d6c7362443069626d39755a53",
hex"49675a4430695454453549444d7961444d30646a49305344453565694976506a7877",
hex"5958526f49475a706247773949694e6c595456684e44636949475139496b30794f53",
hex"41794d5777744e53413164693035614456364969382b5043396e506a77765a7a3438",
hex"5a794230636d467563325a76636d3039496d316864484a70654367754f4451674d43",
hex"4177494334344e4341324e5341314b53492b50484268644767675a44306954546b75",
hex"4e5341794d693435624451754f4341324c6a52684d7934784d69417a4c6a45794944",
hex"41674d4341784c544d674d693479624330304c6a67744e6934305979347a4c544575",
hex"4e4341784c6a59744d69343049444d744d693479656949675a6d6c73624430694932",
hex"517759325a6a5a534976506a78775958526f49475a706247773949694d774d544178",
hex"4d44456949475139496b30304d53343349444d344c6a56734e5334784c5459754e53",
hex"4976506a78775958526f49475139496b30304d693435494449334c6a684d4d546775",
hex"4e4341314f4334784944493049445979624449784c6a67744d6a63754d7941794c6a",
hex"4d744d693434656949675932786863334d39496b55694c7a3438634746306143426d",
hex"615778735053496a4d4445774d5441784969426b50534a4e4e444d754e4341794f53",
hex"347a624330304c6a63674e5334344969382b50484268644767675a44306954545132",
hex"4c6a67674d7a4a6a4d793479494449754e6941344c6a63674d533479494445794c6a",
hex"45744d793479637a4d754e6930354c6a6b754d7930784d693431624330314c6a4567",
hex"4e6934314c5449754f4330754d5330754e7930794c6a63674e5334784c5459754e57",
hex"4d744d7934794c5449754e6930344c6a63744d5334794c5445794c6a45674d793479",
hex"6379307a4c6a59674f5334354c53347a494445794c6a556949474e7359584e7a5053",
hex"4a464969382b50484268644767675a6d6c7362443069493245314e7a6b7a4f534967",
hex"5a443069545449334c6a4d674d6a5a734d5445754f4341784e53343349444d754e43",
hex"41794c6a51674f533478494445304c6a51744d793479494449754d79307849433433",
hex"4c5445774c6a49744d544d754e6930784c6a4d744d7934354c5445784c6a67744d54",
hex"55754e336f694c7a3438634746306143426b50534a4e4d5449674d546b754f577731",
hex"4c6a6b674e793435494445774c6a49744e7934324c544d754e4330304c6a567a4e69",
hex"34344c5455754d5341784d4334334c5451754e574d77494441744e6934324c544d74",
hex"4d544d754d7941784c6a46544d5449674d546b754f5341784d6941784f5334356569",
hex"49675932786863334d39496b55694c7a34385a79426d6157787350534a756232356c",
hex"4969427a64484a766132553949694d774d44416949474e7359584e7a50534a434945",
hex"4d675243492b50484268644767675a44306954545579494455344c6a6c4d4e444175",
hex"4f5341304d7934796243307a4c6a45744d69347a4c5445774c6a59744d5451754e79",
hex"30794c6a6b674d693479494445774c6a59674d5451754e7941784c6a45674d793432",
hex"494445784c6a55674d5455754e58704e4d5449754e5341784f533434624455754f43",
hex"4134494445774c6a4d744e7934304c544d754d7930304c6a5a7a4e6934354c545567",
hex"4d5441754f4330304c6a4e6a4d4341774c5459754e69307a4c6a45744d544d754d79",
hex"3435637930784d43347a494463754e4330784d43347a494463754e4870744c544975",
hex"4e6941794c6a6c734e433433494459754e574d744c6a55674d53347a4c5445754e79",
hex"41794c6a45744d7941794c6a4a734c5451754e7930324c6a566a4c6a4d744d533430",
hex"494445754e6930794c6a51674d7930794c6a4a364969382b50484268644767675a44",
hex"3069545451784c6a4d674d7a67754e5777314c6a45744e6934316253307a4c6a5574",
hex"4d693433624330304c6a59674e533434625467754d53307a4c6a466a4d7934794944",
hex"49754e6941344c6a63674d533479494445794c6a45744d793479637a4d754e693035",
hex"4c6a6b754d7930784d693431624330314c6a45674e6934314c5449754f4330754d53",
hex"30754f4330794c6a63674e5334784c5459754e574d744d7934794c5449754e693034",
hex"4c6a63744d5334794c5445794c6a45674d7934794c544d754e4341304c6a4d744d79",
hex"343249446b754f5330754d7941784d6934314969426a6247467a637a306952694976",
hex"506a78775958526f49475139496b307a4d433434494451304c6a524d4d546b674e54",
hex"67754f57773049444d674d5441744d5449754e7949675932786863334d39496b5969",
hex"4c7a34384c32632b5043396e506a777663335a6e50673d3d227d"
); /* ","description":"This%20NFT%20can%20be%20redeemed%20on%20HomeWork%20
to%20grant%20a%20controller%20the%20exclusive%20right%20to%20deploy%20
contracts%20with%20arbitrary%20bytecode%20to%20the%20designated%20home
%20address.","image":"data:image/svg+xml;charset=utf-8;base64,..."} */
// Deploy payload to the runtime storage contract.
_deployRuntimeStorageContract(key, code);
}
/**
* @notice Perform phase three of the deployment and disable this contract.
* @param key bytes32 The salt to provide to create2.
*/
function phaseThree(bytes32 key) external onlyUntilDisabled {<FILL_FUNCTION_BODY> }
/**
* @notice View function used by the metamorphic initialization code when
* deploying a contract to a home address. It returns the address of the
* runtime storage contract that holds the contract creation code, which the
* metamorphic creation code then `DELEGATECALL`s into in order to set up the
* contract and deploy the target runtime code.
* @return The current runtime storage contract that contains the target
* contract creation code.
* @dev This method is not meant to be part of the user-facing contract API,
* but is rather a mechanism for enabling the deployment of arbitrary code via
* fixed initialization code. The odd naming is chosen so that function
* selector will be 0x00000009 - that way, the metamorphic contract can simply
* use the `PC` opcode in order to push the selector to the stack.
*/
function getInitializationCodeFromContractRuntime_6CLUNS()
external
view
returns (address initializationRuntimeStorageContract)
{
// Return address of contract with initialization code set as runtime code.
initializationRuntimeStorageContract = _initializationRuntimeStorageContract;
}
/**
* @notice Internal function for deploying a runtime storage contract given a
* particular payload.
* @dev To take the provided code payload and deploy a contract with that
* payload as its runtime code, use the following prelude:
*
* 0x600b5981380380925939f3...
*
* 00 60 push1 0b [11 -> offset]
* 02 59 msize [offset, 0]
* 03 81 dup2 [offset, 0, offset]
* 04 38 codesize [offset, 0, offset, codesize]
* 05 03 sub [offset, 0, codesize - offset]
* 06 80 dup1 [offset, 0, codesize - offset, codesize - offset]
* 07 92 swap3 [codesize - offset, 0, codesize - offset, offset]
* 08 59 msize [codesize - offset, 0, codesize - offset, offset, 0]
* 09 39 codecopy [codesize - offset, 0] <init_code_in_runtime>
* 10 f3 return [] *init_code_in_runtime*
* ... init_code
*/
function _deployRuntimeStorageContract(bytes32 key, bytes memory payload)
internal
returns (address runtimeStorageContract)
{
// Construct the contract creation code using the prelude and the payload.
bytes memory runtimeStorageContractCreationCode = abi.encodePacked(
_ARBITRARY_RUNTIME_PRELUDE,
payload
);
assembly {
// Get the location and length of the newly-constructed creation code.
let encoded_data := add(0x20, runtimeStorageContractCreationCode)
let encoded_size := mload(runtimeStorageContractCreationCode)
// Deploy the runtime storage contract via `CREATE2`.
runtimeStorageContract := create2(0, encoded_data, encoded_size, key)
// Pass along revert message if the contract did not deploy successfully.
if iszero(runtimeStorageContract) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
// Emit an event with address of newly-deployed runtime storage contract.
emit StorageContractDeployment(runtimeStorageContract);
}
/**
* @notice Internal function for deploying arbitrary contract code to the home
* address corresponding to a suppied key via metamorphic initialization code.
* @dev This deployment method uses the "metamorphic delegator" pattern, where
* it will retrieve the address of the contract that contains the target
* initialization code, then delegatecall into it, which executes the
* initialization code stored there and returns the runtime code (or reverts).
* Then, the runtime code returned by the delegatecall is returned, and since
* we are still in the initialization context, it will be set as the runtime
* code of the metamorphic contract. The 32-byte metamorphic initialization
* code is as follows:
*
* 0x5859385958601c335a585952fa1582838382515af43d3d93833e601e57fd5bf3
*
* 00 58 PC [0]
* 01 59 MSIZE [0, 0]
* 02 38 CODESIZE [0, 0, codesize -> 32]
* returndatac03 59 MSIZE [0, 0, 32, 0]
* 04 58 PC [0, 0, 32, 0, 4]
* 05 60 PUSH1 0x1c [0, 0, 32, 0, 4, 28]
* 07 33 CALLER [0, 0, 32, 0, 4, 28, caller]
* 08 5a GAS [0, 0, 32, 0, 4, 28, caller, gas]
* 09 58 PC [0, 0, 32, 0, 4, 28, caller, gas, 9 -> selector]
* 10 59 MSIZE [0, 0, 32, 0, 4, 28, caller, gas, selector, 0]
* 11 52 MSTORE [0, 0, 32, 0, 4, 28, caller, gas] <selector>
* 12 fa STATICCALL [0, 0, 1 => success] <init_in_runtime_address>
* 13 15 ISZERO [0, 0, 0]
* 14 82 DUP3 [0, 0, 0, 0]
* 15 83 DUP4 [0, 0, 0, 0, 0]
* 16 83 DUP4 [0, 0, 0, 0, 0, 0]
* 17 82 DUP3 [0, 0, 0, 0, 0, 0, 0]
* 18 51 MLOAD [0, 0, 0, 0, 0, 0, init_in_runtime_address]
* 19 5a GAS [0, 0, 0, 0, 0, 0, init_in_runtime_address, gas]
* 20 f4 DELEGATECALL [0, 0, 1 => success] {runtime_code}
* 21 3d RETURNDATASIZE [0, 0, 1 => success, size]
* 22 3d RETURNDATASIZE [0, 0, 1 => success, size, size]
* 23 93 SWAP4 [size, 0, 1 => success, size, 0]
* 24 83 DUP4 [size, 0, 1 => success, size, 0, 0]
* 25 3e RETURNDATACOPY [size, 0, 1 => success] <runtime_code>
* 26 60 PUSH1 0x1e [size, 0, 1 => success, 30]
* 28 57 JUMPI [size, 0]
* 29 fd REVERT [] *runtime_code*
* 30 5b JUMPDEST [size, 0]
* 31 f3 RETURN []
*/
function _deployToHomeAddress(bytes32 key) internal {
// Declare a variable for the home address.
address homeAddress;
assembly {
// Write the 32-byte metamorphic initialization code to scratch space.
mstore(
0,
0x5859385958601c335a585952fa1582838382515af43d3d93833e601e57fd5bf3
)
// Call `CREATE2` using above init code with the supplied key as the salt.
homeAddress := create2(callvalue, 0, 32, key)
// Pass along revert message if the contract did not deploy successfully.
if iszero(homeAddress) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
// Clear the address of the runtime storage contract from storage.
delete _initializationRuntimeStorageContract;
// Emit an event with home address and key for the newly-deployed contract.
emit HomeWorkDeployment(homeAddress, key);
}
/**
* @notice Modifier to disable the contract once deployment is complete.
*/
modifier onlyUntilDisabled() {
require(!_disabled, "Contract is disabled.");
_;
}
} | contract HomeWorkDeployer {
// Fires when HomeWork has been deployed.
event HomeWorkDeployment(address homeAddress, bytes32 key);
// Fires HomeWork's initialization-in-runtime storage contract is deployed.
event StorageContractDeployment(address runtimeStorageContract);
// Allocate storage to track the current initialization-in-runtime contract.
address private _initializationRuntimeStorageContract;
// Once HomeWork has been deployed, disable this contract.
bool private _disabled;
// Write arbitrary code to a contract's runtime using the following prelude.
bytes11 private constant _ARBITRARY_RUNTIME_PRELUDE = bytes11(
0x600b5981380380925939f3
);
/**
* @notice Perform phase one of the deployment.
* @param code bytes The contract creation code for HomeWork.
*/
function phaseOne(bytes calldata code) external onlyUntilDisabled {
// Deploy payload to the runtime storage contract and set the address.
_initializationRuntimeStorageContract = _deployRuntimeStorageContract(
bytes32(0),
code
);
}
/**
* @notice Perform phase two of the deployment (tokenURI data).
* @param key bytes32 The salt to provide to create2.
*/
function phaseTwo(bytes32 key) external onlyUntilDisabled {
// Deploy runtime storage contract with the string used to construct end of
// token URI for issued ERC721s (data URI with a base64-encoded jpeg image).
bytes memory code = abi.encodePacked(
hex"222c226465736372697074696f6e223a22546869732532304e465425323063616e25",
hex"3230626525323072656465656d65642532306f6e253230486f6d65576f726b253230",
hex"746f2532306772616e7425323061253230636f6e74726f6c6c657225323074686525",
hex"32306578636c75736976652532307269676874253230746f2532306465706c6f7925",
hex"3230636f6e7472616374732532307769746825323061726269747261727925323062",
hex"797465636f6465253230746f25323074686525323064657369676e61746564253230",
hex"686f6d65253230616464726573732e222c22696d616765223a22646174613a696d61",
hex"67652f7376672b786d6c3b636861727365743d7574662d383b6261736536342c5048",
hex"4e325a79423462577875637a30696148523063446f764c336433647935334d793576",
hex"636d63764d6a41774d43397a646d636949485a705a58644362336739496a41674d43",
hex"41784e4451674e7a4969506a787a64486c735a543438495674445245465551567375",
hex"516e747a64484a766132557462476c755a57707661573436636d3931626d52394c6b",
hex"4e37633352796232746c4c5731706447567962476c74615851364d5442394c6b5237",
hex"633352796232746c4c5864705a48526f4f6a4a394c6b56375a6d6c7362446f6a4f57",
hex"4935596a6c686653354765334e30636d39725a5331736157356c593246774f6e4a76",
hex"6457356b66563164506a7776633352356247552b5047636764484a68626e4e6d6233",
hex"4a7450534a74595852796158676f4d5334774d694177494441674d5334774d694134",
hex"4c6a45674d436b69506a78775958526f49475a706247773949694e6d5a6d59694947",
hex"5139496b30784f53417a4d6d677a4e4859794e4567784f586f694c7a34385a79427a",
hex"64484a766132553949694d774d44416949474e7359584e7a50534a4349454d675243",
hex"492b50484268644767675a6d6c7362443069493245314e7a6b7a4f5349675a443069",
hex"545449314944517761446c324d545a6f4c546c364969382b50484268644767675a6d",
hex"6c7362443069497a6b795a444e6d4e5349675a443069545451774944517761446832",
hex"4e3267744f486f694c7a3438634746306143426d615778735053496a5a5745315954",
hex"51334969426b50534a4e4e544d674d7a4a494d546c324c5446734d5459744d545967",
hex"4d5467674d545a364969382b50484268644767675a6d6c7362443069626d39755a53",
hex"49675a4430695454453549444d7961444d30646a49305344453565694976506a7877",
hex"5958526f49475a706247773949694e6c595456684e44636949475139496b30794f53",
hex"41794d5777744e53413164693035614456364969382b5043396e506a77765a7a3438",
hex"5a794230636d467563325a76636d3039496d316864484a70654367754f4451674d43",
hex"4177494334344e4341324e5341314b53492b50484268644767675a44306954546b75",
hex"4e5341794d693435624451754f4341324c6a52684d7934784d69417a4c6a45794944",
hex"41674d4341784c544d674d693479624330304c6a67744e6934305979347a4c544575",
hex"4e4341784c6a59744d69343049444d744d693479656949675a6d6c73624430694932",
hex"517759325a6a5a534976506a78775958526f49475a706247773949694d774d544178",
hex"4d44456949475139496b30304d53343349444d344c6a56734e5334784c5459754e53",
hex"4976506a78775958526f49475139496b30304d693435494449334c6a684d4d546775",
hex"4e4341314f4334784944493049445979624449784c6a67744d6a63754d7941794c6a",
hex"4d744d693434656949675932786863334d39496b55694c7a3438634746306143426d",
hex"615778735053496a4d4445774d5441784969426b50534a4e4e444d754e4341794f53",
hex"347a624330304c6a63674e5334344969382b50484268644767675a44306954545132",
hex"4c6a67674d7a4a6a4d793479494449754e6941344c6a63674d533479494445794c6a",
hex"45744d793479637a4d754e6930354c6a6b754d7930784d693431624330314c6a4567",
hex"4e6934314c5449754f4330754d5330754e7930794c6a63674e5334784c5459754e57",
hex"4d744d7934794c5449754e6930344c6a63744d5334794c5445794c6a45674d793479",
hex"6379307a4c6a59674f5334354c53347a494445794c6a556949474e7359584e7a5053",
hex"4a464969382b50484268644767675a6d6c7362443069493245314e7a6b7a4f534967",
hex"5a443069545449334c6a4d674d6a5a734d5445754f4341784e53343349444d754e43",
hex"41794c6a51674f533478494445304c6a51744d793479494449754d79307849433433",
hex"4c5445774c6a49744d544d754e6930784c6a4d744d7934354c5445784c6a67744d54",
hex"55754e336f694c7a3438634746306143426b50534a4e4d5449674d546b754f577731",
hex"4c6a6b674e793435494445774c6a49744e7934324c544d754e4330304c6a567a4e69",
hex"34344c5455754d5341784d4334334c5451754e574d77494441744e6934324c544d74",
hex"4d544d754d7941784c6a46544d5449674d546b754f5341784d6941784f5334356569",
hex"49675932786863334d39496b55694c7a34385a79426d6157787350534a756232356c",
hex"4969427a64484a766132553949694d774d44416949474e7359584e7a50534a434945",
hex"4d675243492b50484268644767675a44306954545579494455344c6a6c4d4e444175",
hex"4f5341304d7934796243307a4c6a45744d69347a4c5445774c6a59744d5451754e79",
hex"30794c6a6b674d693479494445774c6a59674d5451754e7941784c6a45674d793432",
hex"494445784c6a55674d5455754e58704e4d5449754e5341784f533434624455754f43",
hex"4134494445774c6a4d744e7934304c544d754d7930304c6a5a7a4e6934354c545567",
hex"4d5441754f4330304c6a4e6a4d4341774c5459754e69307a4c6a45744d544d754d79",
hex"3435637930784d43347a494463754e4330784d43347a494463754e4870744c544975",
hex"4e6941794c6a6c734e433433494459754e574d744c6a55674d53347a4c5445754e79",
hex"41794c6a45744d7941794c6a4a734c5451754e7930324c6a566a4c6a4d744d533430",
hex"494445754e6930794c6a51674d7930794c6a4a364969382b50484268644767675a44",
hex"3069545451784c6a4d674d7a67754e5777314c6a45744e6934316253307a4c6a5574",
hex"4d693433624330304c6a59674e533434625467754d53307a4c6a466a4d7934794944",
hex"49754e6941344c6a63674d533479494445794c6a45744d793479637a4d754e693035",
hex"4c6a6b754d7930784d693431624330314c6a45674e6934314c5449754f4330754d53",
hex"30754f4330794c6a63674e5334784c5459754e574d744d7934794c5449754e693034",
hex"4c6a63744d5334794c5445794c6a45674d7934794c544d754e4341304c6a4d744d79",
hex"343249446b754f5330754d7941784d6934314969426a6247467a637a306952694976",
hex"506a78775958526f49475139496b307a4d433434494451304c6a524d4d546b674e54",
hex"67754f57773049444d674d5441744d5449754e7949675932786863334d39496b5969",
hex"4c7a34384c32632b5043396e506a777663335a6e50673d3d227d"
); /* ","description":"This%20NFT%20can%20be%20redeemed%20on%20HomeWork%20
to%20grant%20a%20controller%20the%20exclusive%20right%20to%20deploy%20
contracts%20with%20arbitrary%20bytecode%20to%20the%20designated%20home
%20address.","image":"data:image/svg+xml;charset=utf-8;base64,..."} */
// Deploy payload to the runtime storage contract.
_deployRuntimeStorageContract(key, code);
}
<FILL_FUNCTION>
/**
* @notice View function used by the metamorphic initialization code when
* deploying a contract to a home address. It returns the address of the
* runtime storage contract that holds the contract creation code, which the
* metamorphic creation code then `DELEGATECALL`s into in order to set up the
* contract and deploy the target runtime code.
* @return The current runtime storage contract that contains the target
* contract creation code.
* @dev This method is not meant to be part of the user-facing contract API,
* but is rather a mechanism for enabling the deployment of arbitrary code via
* fixed initialization code. The odd naming is chosen so that function
* selector will be 0x00000009 - that way, the metamorphic contract can simply
* use the `PC` opcode in order to push the selector to the stack.
*/
function getInitializationCodeFromContractRuntime_6CLUNS()
external
view
returns (address initializationRuntimeStorageContract)
{
// Return address of contract with initialization code set as runtime code.
initializationRuntimeStorageContract = _initializationRuntimeStorageContract;
}
/**
* @notice Internal function for deploying a runtime storage contract given a
* particular payload.
* @dev To take the provided code payload and deploy a contract with that
* payload as its runtime code, use the following prelude:
*
* 0x600b5981380380925939f3...
*
* 00 60 push1 0b [11 -> offset]
* 02 59 msize [offset, 0]
* 03 81 dup2 [offset, 0, offset]
* 04 38 codesize [offset, 0, offset, codesize]
* 05 03 sub [offset, 0, codesize - offset]
* 06 80 dup1 [offset, 0, codesize - offset, codesize - offset]
* 07 92 swap3 [codesize - offset, 0, codesize - offset, offset]
* 08 59 msize [codesize - offset, 0, codesize - offset, offset, 0]
* 09 39 codecopy [codesize - offset, 0] <init_code_in_runtime>
* 10 f3 return [] *init_code_in_runtime*
* ... init_code
*/
function _deployRuntimeStorageContract(bytes32 key, bytes memory payload)
internal
returns (address runtimeStorageContract)
{
// Construct the contract creation code using the prelude and the payload.
bytes memory runtimeStorageContractCreationCode = abi.encodePacked(
_ARBITRARY_RUNTIME_PRELUDE,
payload
);
assembly {
// Get the location and length of the newly-constructed creation code.
let encoded_data := add(0x20, runtimeStorageContractCreationCode)
let encoded_size := mload(runtimeStorageContractCreationCode)
// Deploy the runtime storage contract via `CREATE2`.
runtimeStorageContract := create2(0, encoded_data, encoded_size, key)
// Pass along revert message if the contract did not deploy successfully.
if iszero(runtimeStorageContract) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
// Emit an event with address of newly-deployed runtime storage contract.
emit StorageContractDeployment(runtimeStorageContract);
}
/**
* @notice Internal function for deploying arbitrary contract code to the home
* address corresponding to a suppied key via metamorphic initialization code.
* @dev This deployment method uses the "metamorphic delegator" pattern, where
* it will retrieve the address of the contract that contains the target
* initialization code, then delegatecall into it, which executes the
* initialization code stored there and returns the runtime code (or reverts).
* Then, the runtime code returned by the delegatecall is returned, and since
* we are still in the initialization context, it will be set as the runtime
* code of the metamorphic contract. The 32-byte metamorphic initialization
* code is as follows:
*
* 0x5859385958601c335a585952fa1582838382515af43d3d93833e601e57fd5bf3
*
* 00 58 PC [0]
* 01 59 MSIZE [0, 0]
* 02 38 CODESIZE [0, 0, codesize -> 32]
* returndatac03 59 MSIZE [0, 0, 32, 0]
* 04 58 PC [0, 0, 32, 0, 4]
* 05 60 PUSH1 0x1c [0, 0, 32, 0, 4, 28]
* 07 33 CALLER [0, 0, 32, 0, 4, 28, caller]
* 08 5a GAS [0, 0, 32, 0, 4, 28, caller, gas]
* 09 58 PC [0, 0, 32, 0, 4, 28, caller, gas, 9 -> selector]
* 10 59 MSIZE [0, 0, 32, 0, 4, 28, caller, gas, selector, 0]
* 11 52 MSTORE [0, 0, 32, 0, 4, 28, caller, gas] <selector>
* 12 fa STATICCALL [0, 0, 1 => success] <init_in_runtime_address>
* 13 15 ISZERO [0, 0, 0]
* 14 82 DUP3 [0, 0, 0, 0]
* 15 83 DUP4 [0, 0, 0, 0, 0]
* 16 83 DUP4 [0, 0, 0, 0, 0, 0]
* 17 82 DUP3 [0, 0, 0, 0, 0, 0, 0]
* 18 51 MLOAD [0, 0, 0, 0, 0, 0, init_in_runtime_address]
* 19 5a GAS [0, 0, 0, 0, 0, 0, init_in_runtime_address, gas]
* 20 f4 DELEGATECALL [0, 0, 1 => success] {runtime_code}
* 21 3d RETURNDATASIZE [0, 0, 1 => success, size]
* 22 3d RETURNDATASIZE [0, 0, 1 => success, size, size]
* 23 93 SWAP4 [size, 0, 1 => success, size, 0]
* 24 83 DUP4 [size, 0, 1 => success, size, 0, 0]
* 25 3e RETURNDATACOPY [size, 0, 1 => success] <runtime_code>
* 26 60 PUSH1 0x1e [size, 0, 1 => success, 30]
* 28 57 JUMPI [size, 0]
* 29 fd REVERT [] *runtime_code*
* 30 5b JUMPDEST [size, 0]
* 31 f3 RETURN []
*/
function _deployToHomeAddress(bytes32 key) internal {
// Declare a variable for the home address.
address homeAddress;
assembly {
// Write the 32-byte metamorphic initialization code to scratch space.
mstore(
0,
0x5859385958601c335a585952fa1582838382515af43d3d93833e601e57fd5bf3
)
// Call `CREATE2` using above init code with the supplied key as the salt.
homeAddress := create2(callvalue, 0, 32, key)
// Pass along revert message if the contract did not deploy successfully.
if iszero(homeAddress) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
// Clear the address of the runtime storage contract from storage.
delete _initializationRuntimeStorageContract;
// Emit an event with home address and key for the newly-deployed contract.
emit HomeWorkDeployment(homeAddress, key);
}
/**
* @notice Modifier to disable the contract once deployment is complete.
*/
modifier onlyUntilDisabled() {
require(!_disabled, "Contract is disabled.");
_;
}
} |
// Use metamorphic initialization code to deploy contract to home address.
_deployToHomeAddress(key);
// Disable this contract from here on out - use HomeWork itself instead.
_disabled = true;
| function phaseThree(bytes32 key) external onlyUntilDisabled | /**
* @notice Perform phase three of the deployment and disable this contract.
* @param key bytes32 The salt to provide to create2.
*/
function phaseThree(bytes32 key) external onlyUntilDisabled |
35360 | Ownable | null | contract Ownable is Context {
address private m_Owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {<FILL_FUNCTION_BODY> }
function owner() public view returns (address) {
return m_Owner;
}
function transferOwnership(address _address) public virtual onlyOwner {
emit OwnershipTransferred(m_Owner, _address);
m_Owner = _address;
}
modifier onlyOwner() {
require(_msgSender() == m_Owner, "Ownable: caller is not the owner");
_;
}
} | contract Ownable is Context {
address private m_Owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
<FILL_FUNCTION>
function owner() public view returns (address) {
return m_Owner;
}
function transferOwnership(address _address) public virtual onlyOwner {
emit OwnershipTransferred(m_Owner, _address);
m_Owner = _address;
}
modifier onlyOwner() {
require(_msgSender() == m_Owner, "Ownable: caller is not the owner");
_;
}
} |
address msgSender = _msgSender();
m_Owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
| constructor () | constructor () |
41297 | DSAuth | isAuthorized | contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = 0xc98C8e4Cd7Ea9698E1A4F8b9339297aC96A47569;
emit LogSetOwner(0xc98C8e4Cd7Ea9698E1A4F8b9339297aC96A47569);
}
function setOwner(address owner_0xc98C8e4Cd7Ea9698E1A4F8b9339297aC96A47569)
public
auth
{
owner = owner_0xc98C8e4Cd7Ea9698E1A4F8b9339297aC96A47569;
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 = 0xc98C8e4Cd7Ea9698E1A4F8b9339297aC96A47569;
emit LogSetOwner(0xc98C8e4Cd7Ea9698E1A4F8b9339297aC96A47569);
}
function setOwner(address owner_0xc98C8e4Cd7Ea9698E1A4F8b9339297aC96A47569)
public
auth
{
owner = owner_0xc98C8e4Cd7Ea9698E1A4F8b9339297aC96A47569;
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) |
45752 | Token | mint | contract Token is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint public decimals;
string public comments;
uint private _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor(
uint256 initialSupply,
string memory tokenName,
uint8 decimalUnits,
string memory tokenSymbol,
string memory tokenComments
) public {
symbol = tokenSymbol;
name = tokenName;
decimals = decimalUnits;
comments = tokenComments;
_totalSupply = initialSupply;
_totalSupply = _totalSupply * 10 ** decimals;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public returns (uint) {
return _totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public 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
//
// 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 returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () external payable {
revert();
}
function transferOwnership(address _newOwner) public onlyOwner {
owner = _newOwner;
}
/**
* @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) public onlyOwner {<FILL_FUNCTION_BODY> }
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function burn(address account, uint256 value) public onlyOwner {
require(account != address(0));
_totalSupply = safeSub(_totalSupply, value);
balances[account] = safeSub(balances[account], value);
emit Transfer(account, address(0), value);
}
} | contract Token is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint public decimals;
string public comments;
uint private _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor(
uint256 initialSupply,
string memory tokenName,
uint8 decimalUnits,
string memory tokenSymbol,
string memory tokenComments
) public {
symbol = tokenSymbol;
name = tokenName;
decimals = decimalUnits;
comments = tokenComments;
_totalSupply = initialSupply;
_totalSupply = _totalSupply * 10 ** decimals;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public returns (uint) {
return _totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public 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
//
// 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 returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () external payable {
revert();
}
function transferOwnership(address _newOwner) public onlyOwner {
owner = _newOwner;
}
<FILL_FUNCTION>
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function burn(address account, uint256 value) public onlyOwner {
require(account != address(0));
_totalSupply = safeSub(_totalSupply, value);
balances[account] = safeSub(balances[account], value);
emit Transfer(account, address(0), value);
}
} |
require(account != address(0));
_totalSupply = safeAdd(_totalSupply, value);
balances[account] = safeAdd(balances[account], value);
emit Transfer(address(0), account, value);
| function mint(address account, uint256 value) public onlyOwner | /**
* @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) public onlyOwner |
70664 | Funtastic | transferAnyERC20Token | contract Funtastic is ERC20Interface, Owned, SafeMath {
string public symbol;
string public tokenName;
string public version = "1.1";
uint private decimals;
uint private _totalSupply;
uint public startOfCrowdsale = 1607265334; // 03.09.2018 08:10 UTC <-- CHANGE THIS
uint public endOfCrowdsale;
uint public hardCap;
uint public weiRaised;
uint public lastTransactionReceivedInWei;
uint public bonusEnds;
bool public stopCrowdsale;
bool public wasCrowdsaleStoped;
uint public numberOfContributors;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "FUNT"; // <-- CHANGE THIS
tokenName = "Funtastic"; // <-- CHANGE THIS
decimals = 0; // <-- CHANGE THIS
bonusEnds = startOfCrowdsale + 60 minutes; // <-- CHANGE minutes
endOfCrowdsale = startOfCrowdsale + 2 hours; // <-- CHANGE hours
hardCap = 50000 ether;
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function tokensReleased() public view returns (uint) {
return _totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function checkBalanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes 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;
}
// ------------------------------------------------------------------------
// Set price depending on period
// ------------------------------------------------------------------------
function () public payable {
require((crowdsaleIsActive()) && (msg.value >= .01 ether));
uint tokens;
if (now <= bonusEnds) {
tokens = msg.value * 1000 / 1 ether; // <-- CHANGE THIS
} else {
tokens = msg.value * 500 / 1 ether; // <-- CHANGE THIS
}
lastTransactionReceivedInWei = msg.value;
weiRaised = safeAdd(weiRaised, lastTransactionReceivedInWei);
_totalSupply = safeAdd(_totalSupply, tokens);
balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
emit Transfer(address(0), msg.sender, tokens);
owner.transfer(msg.value);
numberOfContributors += 1; // actually counts number of contributions
}
// ------------------------------------------------------------------------
// Anyone can check if the crowdsale is ON
// ------------------------------------------------------------------------
function crowdsaleIsActive() public view returns (bool) {
return (
now >= startOfCrowdsale && now <= endOfCrowdsale && weiRaised <= hardCap && stopCrowdsale == false
);
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner {<FILL_FUNCTION_BODY> }
// ------------------------------------------------------------------------
// Owner can stop crowdsale anytime
// ------------------------------------------------------------------------
function stopCrowdsale() public onlyOwner {
stopCrowdsale = true;
if (stopCrowdsale = true) {
wasCrowdsaleStoped = true;
} else {
wasCrowdsaleStoped = false;
}
}
} | contract Funtastic is ERC20Interface, Owned, SafeMath {
string public symbol;
string public tokenName;
string public version = "1.1";
uint private decimals;
uint private _totalSupply;
uint public startOfCrowdsale = 1607265334; // 03.09.2018 08:10 UTC <-- CHANGE THIS
uint public endOfCrowdsale;
uint public hardCap;
uint public weiRaised;
uint public lastTransactionReceivedInWei;
uint public bonusEnds;
bool public stopCrowdsale;
bool public wasCrowdsaleStoped;
uint public numberOfContributors;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "FUNT"; // <-- CHANGE THIS
tokenName = "Funtastic"; // <-- CHANGE THIS
decimals = 0; // <-- CHANGE THIS
bonusEnds = startOfCrowdsale + 60 minutes; // <-- CHANGE minutes
endOfCrowdsale = startOfCrowdsale + 2 hours; // <-- CHANGE hours
hardCap = 50000 ether;
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function tokensReleased() public view returns (uint) {
return _totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function checkBalanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes 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;
}
// ------------------------------------------------------------------------
// Set price depending on period
// ------------------------------------------------------------------------
function () public payable {
require((crowdsaleIsActive()) && (msg.value >= .01 ether));
uint tokens;
if (now <= bonusEnds) {
tokens = msg.value * 1000 / 1 ether; // <-- CHANGE THIS
} else {
tokens = msg.value * 500 / 1 ether; // <-- CHANGE THIS
}
lastTransactionReceivedInWei = msg.value;
weiRaised = safeAdd(weiRaised, lastTransactionReceivedInWei);
_totalSupply = safeAdd(_totalSupply, tokens);
balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
emit Transfer(address(0), msg.sender, tokens);
owner.transfer(msg.value);
numberOfContributors += 1; // actually counts number of contributions
}
// ------------------------------------------------------------------------
// Anyone can check if the crowdsale is ON
// ------------------------------------------------------------------------
function crowdsaleIsActive() public view returns (bool) {
return (
now >= startOfCrowdsale && now <= endOfCrowdsale && weiRaised <= hardCap && stopCrowdsale == false
);
}
<FILL_FUNCTION>
// ------------------------------------------------------------------------
// Owner can stop crowdsale anytime
// ------------------------------------------------------------------------
function stopCrowdsale() public onlyOwner {
stopCrowdsale = true;
if (stopCrowdsale = true) {
wasCrowdsaleStoped = true;
} else {
wasCrowdsaleStoped = false;
}
}
} |
ERC20Interface(tokenAddress).transfer(owner, tokens);
| function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner | // ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner |
39846 | StandardToken | multiTransfer | contract StandardToken is ERC20 {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
function StandardToken(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
function balanceOf(address _owner) public view returns(uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _value) public returns(bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function multiTransfer(address[] _to, uint256[] _value) public returns(bool) {<FILL_FUNCTION_BODY> }
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns(uint256) {
return allowed[_owner][_spender];
}
function approve(address _spender, uint256 _value) public returns(bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
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) {
uint oldValue = allowed[msg.sender][_spender];
if(_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | contract StandardToken is ERC20 {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
function StandardToken(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
function balanceOf(address _owner) public view returns(uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _value) public returns(bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
<FILL_FUNCTION>
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns(uint256) {
return allowed[_owner][_spender];
}
function approve(address _spender, uint256 _value) public returns(bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
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) {
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;
}
} |
require(_to.length == _value.length);
for(uint i = 0; i < _to.length; i++) {
transfer(_to[i], _value[i]);
}
return true;
| function multiTransfer(address[] _to, uint256[] _value) public returns(bool) | function multiTransfer(address[] _to, uint256[] _value) public returns(bool) |
20071 | StandardToken | transferFrom | contract StandardToken is Token {
mapping (address => uint256) public _balances;
mapping (address => mapping (address => uint256)) public _allowed;
function transfer(address _to, uint256 _value) public returns (bool success) {
require(_to != address(0));
require(_value <= _balances[msg.sender]);
require(_balances[_to] + _value > _balances[_to]);
_balances[msg.sender] = SafeMath.safeSub(_balances[msg.sender], _value);
_balances[_to] = SafeMath.safeAdd(_balances[_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 balanceOf(address _owner) view public returns (uint256 balance) {
return _balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
require((_value == 0) || (_allowed[msg.sender][_spender] == 0));
_allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) view public returns (uint256 remaining) {
return _allowed[_owner][_spender];
}
} | contract StandardToken is Token {
mapping (address => uint256) public _balances;
mapping (address => mapping (address => uint256)) public _allowed;
function transfer(address _to, uint256 _value) public returns (bool success) {
require(_to != address(0));
require(_value <= _balances[msg.sender]);
require(_balances[_to] + _value > _balances[_to]);
_balances[msg.sender] = SafeMath.safeSub(_balances[msg.sender], _value);
_balances[_to] = SafeMath.safeAdd(_balances[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
<FILL_FUNCTION>
function balanceOf(address _owner) view public returns (uint256 balance) {
return _balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
require((_value == 0) || (_allowed[msg.sender][_spender] == 0));
_allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) view public returns (uint256 remaining) {
return _allowed[_owner][_spender];
}
} |
require(_to != address(0));
require(_value <= _balances[_from]);
require(_value <= _allowed[_from][msg.sender]);
require(_balances[_to] + _value > _balances[_to]);
_balances[_to] = SafeMath.safeAdd(_balances[_to], _value);
_balances[_from] = SafeMath.safeSub(_balances[_from], _value);
_allowed[_from][msg.sender] = SafeMath.safeSub(_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) |
66277 | BT | transfer | contract BT is SafeMath{
string public name='BT token';
string public symbol='BT';
uint8 public decimals = 18;
uint256 public totalSupply=10000000000;
address public owner=0x9158D63b74dE4Aef6695B41F61B313f93f3cE6AE;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => uint256) public freezeOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* This notifies clients about the amount frozen */
event Freeze(address indexed from, uint256 value);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function AC(
uint256 initialSupply,
string tokenName,
string tokenSymbol,
address holder) public{
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply
balanceOf[holder] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
owner = holder;
}
/* Send coins */
function transfer(address _to, uint256 _value) public{<FILL_FUNCTION_BODY> }
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value) public
returns (bool success) {
require(_value > 0);
allowance[msg.sender][_spender] = _value;
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require(_value > 0);
require(balanceOf[_from] >= _value); // Check if the sender has enough
require(balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
require(_value > 0);
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
function freeze(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
require(_value > 0);
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply
Freeze(msg.sender, _value);
return true;
}
function unfreeze(uint256 _value) public returns (bool success) {
require(freezeOf[msg.sender] >= _value); // Check if the sender has enough
require(_value > 0);
freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender
balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value);
Unfreeze(msg.sender, _value);
return true;
}
} | contract BT is SafeMath{
string public name='BT token';
string public symbol='BT';
uint8 public decimals = 18;
uint256 public totalSupply=10000000000;
address public owner=0x9158D63b74dE4Aef6695B41F61B313f93f3cE6AE;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => uint256) public freezeOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* This notifies clients about the amount frozen */
event Freeze(address indexed from, uint256 value);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function AC(
uint256 initialSupply,
string tokenName,
string tokenSymbol,
address holder) public{
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply
balanceOf[holder] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
owner = holder;
}
<FILL_FUNCTION>
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value) public
returns (bool success) {
require(_value > 0);
allowance[msg.sender][_spender] = _value;
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require(_value > 0);
require(balanceOf[_from] >= _value); // Check if the sender has enough
require(balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
require(_value > 0);
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
function freeze(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
require(_value > 0);
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply
Freeze(msg.sender, _value);
return true;
}
function unfreeze(uint256 _value) public returns (bool success) {
require(freezeOf[msg.sender] >= _value); // Check if the sender has enough
require(_value > 0);
freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender
balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value);
Unfreeze(msg.sender, _value);
return true;
}
} |
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require(_value > 0);
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
require(balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
| function transfer(address _to, uint256 _value) public | /* Send coins */
function transfer(address _to, uint256 _value) public |
80613 | CouponClipperV2 | advanceAndRedeemMax | contract CouponClipperV2 {
using SafeMath for uint256;
IERC20 constant private ESD = IERC20(0x36F3FD68E7325a35EB768F1AedaAe9EA0689d723);
IESDS constant private ESDS = IESDS(0x443D2f2755DB5942601fa062Cc248aAA153313D3);
ICHI constant private CHI = ICHI(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c);
uint256 constant private HOUSE_RATE = 100; // 100 basis points (1%) -- fee taken by the house
address public house = 0x7Fb471734271b732FbEEd4B6073F401983a406e1; // collector of house take
event SetOffer(address indexed user, uint256 offer);
// frees CHI from msg.sender to reduce gas costs
// requires that msg.sender has approved this contract to use their CHI
modifier useCHI {
uint256 gasStart = gasleft();
_;
uint256 gasSpent = 21000 + gasStart - gasleft() + (16 * msg.data.length);
CHI.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41947);
}
// The basis points offered by coupon holders to have their coupons redeemed -- default is 200 bps (2%)
// E.g., offers[_user] = 500 indicates that _user will pay 500 basis points (5%) to the caller
mapping(address => uint256) private offers;
// @notice Gets the number of basis points the _user is offering the bots
// @dev The default value is 100 basis points (2%).
// That is, `offers[_user] = 0` is interpretted as 2%.
// This way users who are comfortable with the default 2% offer don't have to make any additional contract calls.
// @param _user The account whose offer we're looking up.
// @return The number of basis points the account is offering to have their coupons redeemed
function getOffer(address _user) public view returns (uint256) {
uint256 offer = offers[_user];
return offer < 200 ? 200 : offer;
}
// @notice Allows msg.sender to change the number of basis points they are offering.
// @dev _newOffer must be at least 200 (2%) and no more than 10_000 (100%)
// @dev A user's offer cannot be *decreased* during the 15 minutes before the epoch advance (frontrun protection)
// @param _offer The number of basis points msg.sender wants to offer to have their coupons redeemed.
function setOffer(uint256 _newOffer) external {
require(_newOffer <= 10_000, "Offer exceeds 100%.");
require(_newOffer >= 200, "Minimum offer is 2%.");
uint256 oldOffer = offers[msg.sender];
if (_newOffer < oldOffer) {
uint256 nextEpoch = ESDS.epoch() + 1;
uint256 nextEpochStartTIme = getEpochStartTime(nextEpoch);
uint256 timeUntilNextEpoch = nextEpochStartTIme.sub(block.timestamp);
require(timeUntilNextEpoch > 15 minutes, "You cannot reduce your offer within 15 minutes of the next epoch");
}
offers[msg.sender] = _newOffer;
emit SetOffer(msg.sender, _newOffer);
}
// @notice Internal logic used to redeem coupons on the coupon holder's bahalf
// @param _user Address of the user holding the coupons (and who has approved this contract)
// @param _epoch The epoch in which the _user purchased the coupons
// @param _couponAmount The number of coupons to redeem (18 decimals)
function _redeem(address _user, uint256 _epoch, uint256 _couponAmount) internal {
// pull user's coupons into this contract (requires that the user has approved this contract)
ESDS.transferCoupons(_user, address(this), _epoch, _couponAmount); // @audit-info : reverts on failure
// redeem the coupons for ESD
ESDS.redeemCoupons(_epoch, _couponAmount); // @audit-info : reverts on failure
// pay the fees
uint256 botFeeRate = getOffer(_user).sub(HOUSE_RATE);
uint256 botFee = _couponAmount.mul(botFeeRate).div(10_000);
uint256 houseFee = _couponAmount.mul(HOUSE_RATE).div(10_000);
ESD.transfer(house, houseFee); // @audit-info : reverts on failure
ESD.transfer(msg.sender, botFee); // @audit-info : reverts on failure
// send the ESD to the user
ESD.transfer(_user, _couponAmount.sub(houseFee).sub(botFee)); // @audit-info : reverts on failure
}
// @notice Allows anyone to redeem coupons for ESD on the coupon-holder's bahalf
// @dev Backwards compatible with CouponClipper V1.
function redeem(address _user, uint256 _epoch, uint256 _couponAmount) external {
_redeem(_user, _epoch, _couponAmount);
}
// @notice Advances the epoch (if needed) and redeems the max amount of coupons possible
// Also frees CHI tokens to save on gas (requires that msg.sender has CHI tokens in their
// account and has approved this contract to spend their CHI).
// @param _user The user whose coupons will attempt to be redeemed
// @param _epoch The epoch in which the coupons were created
// @param _targetEpoch The epoch that is about to be advanced _to_.
// E.g., if the current epoch is 220 and we are about to advance to to epoch 221, then _targetEpoch
// would be set to 221. The _targetEpoch is the epoch in which the coupon redemption will be attempted.
function advanceAndRedeemMax(address _user, uint256 _epoch, uint256 _targetEpoch) external useCHI {<FILL_FUNCTION_BODY> }
// @notice Returns the timestamp at which the _targetEpoch starts
function getEpochStartTime(uint256 _targetEpoch) public pure returns (uint256) {
return _targetEpoch.sub(106).mul(28800).add(1602201600);
}
// @notice Allows house address to change the house address
function changeHouseAddress(address _newAddress) external {
require(msg.sender == house);
house = _newAddress;
}
} | contract CouponClipperV2 {
using SafeMath for uint256;
IERC20 constant private ESD = IERC20(0x36F3FD68E7325a35EB768F1AedaAe9EA0689d723);
IESDS constant private ESDS = IESDS(0x443D2f2755DB5942601fa062Cc248aAA153313D3);
ICHI constant private CHI = ICHI(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c);
uint256 constant private HOUSE_RATE = 100; // 100 basis points (1%) -- fee taken by the house
address public house = 0x7Fb471734271b732FbEEd4B6073F401983a406e1; // collector of house take
event SetOffer(address indexed user, uint256 offer);
// frees CHI from msg.sender to reduce gas costs
// requires that msg.sender has approved this contract to use their CHI
modifier useCHI {
uint256 gasStart = gasleft();
_;
uint256 gasSpent = 21000 + gasStart - gasleft() + (16 * msg.data.length);
CHI.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41947);
}
// The basis points offered by coupon holders to have their coupons redeemed -- default is 200 bps (2%)
// E.g., offers[_user] = 500 indicates that _user will pay 500 basis points (5%) to the caller
mapping(address => uint256) private offers;
// @notice Gets the number of basis points the _user is offering the bots
// @dev The default value is 100 basis points (2%).
// That is, `offers[_user] = 0` is interpretted as 2%.
// This way users who are comfortable with the default 2% offer don't have to make any additional contract calls.
// @param _user The account whose offer we're looking up.
// @return The number of basis points the account is offering to have their coupons redeemed
function getOffer(address _user) public view returns (uint256) {
uint256 offer = offers[_user];
return offer < 200 ? 200 : offer;
}
// @notice Allows msg.sender to change the number of basis points they are offering.
// @dev _newOffer must be at least 200 (2%) and no more than 10_000 (100%)
// @dev A user's offer cannot be *decreased* during the 15 minutes before the epoch advance (frontrun protection)
// @param _offer The number of basis points msg.sender wants to offer to have their coupons redeemed.
function setOffer(uint256 _newOffer) external {
require(_newOffer <= 10_000, "Offer exceeds 100%.");
require(_newOffer >= 200, "Minimum offer is 2%.");
uint256 oldOffer = offers[msg.sender];
if (_newOffer < oldOffer) {
uint256 nextEpoch = ESDS.epoch() + 1;
uint256 nextEpochStartTIme = getEpochStartTime(nextEpoch);
uint256 timeUntilNextEpoch = nextEpochStartTIme.sub(block.timestamp);
require(timeUntilNextEpoch > 15 minutes, "You cannot reduce your offer within 15 minutes of the next epoch");
}
offers[msg.sender] = _newOffer;
emit SetOffer(msg.sender, _newOffer);
}
// @notice Internal logic used to redeem coupons on the coupon holder's bahalf
// @param _user Address of the user holding the coupons (and who has approved this contract)
// @param _epoch The epoch in which the _user purchased the coupons
// @param _couponAmount The number of coupons to redeem (18 decimals)
function _redeem(address _user, uint256 _epoch, uint256 _couponAmount) internal {
// pull user's coupons into this contract (requires that the user has approved this contract)
ESDS.transferCoupons(_user, address(this), _epoch, _couponAmount); // @audit-info : reverts on failure
// redeem the coupons for ESD
ESDS.redeemCoupons(_epoch, _couponAmount); // @audit-info : reverts on failure
// pay the fees
uint256 botFeeRate = getOffer(_user).sub(HOUSE_RATE);
uint256 botFee = _couponAmount.mul(botFeeRate).div(10_000);
uint256 houseFee = _couponAmount.mul(HOUSE_RATE).div(10_000);
ESD.transfer(house, houseFee); // @audit-info : reverts on failure
ESD.transfer(msg.sender, botFee); // @audit-info : reverts on failure
// send the ESD to the user
ESD.transfer(_user, _couponAmount.sub(houseFee).sub(botFee)); // @audit-info : reverts on failure
}
// @notice Allows anyone to redeem coupons for ESD on the coupon-holder's bahalf
// @dev Backwards compatible with CouponClipper V1.
function redeem(address _user, uint256 _epoch, uint256 _couponAmount) external {
_redeem(_user, _epoch, _couponAmount);
}
<FILL_FUNCTION>
// @notice Returns the timestamp at which the _targetEpoch starts
function getEpochStartTime(uint256 _targetEpoch) public pure returns (uint256) {
return _targetEpoch.sub(106).mul(28800).add(1602201600);
}
// @notice Allows house address to change the house address
function changeHouseAddress(address _newAddress) external {
require(msg.sender == house);
house = _newAddress;
}
} |
// End execution early if tx is mined too early
uint256 targetEpochStartTime = getEpochStartTime(_targetEpoch);
if (block.timestamp < targetEpochStartTime) { return; }
// advance epoch if it has not already been advanced
if (ESDS.epoch() != _targetEpoch) { ESDS.advance(); }
// get max redeemable amount
uint256 totalRedeemable = ESDS.totalRedeemable();
if (totalRedeemable == 0) { return; } // no coupons to redeem
uint256 userBalance = ESDS.balanceOfCoupons(_user, _epoch);
if (userBalance == 0) { return; } // no coupons to redeem
uint256 maxRedeemableAmount = totalRedeemable < userBalance ? totalRedeemable : userBalance;
// attempt to redeem coupons
_redeem(_user, _epoch, maxRedeemableAmount);
| function advanceAndRedeemMax(address _user, uint256 _epoch, uint256 _targetEpoch) external useCHI | // @notice Advances the epoch (if needed) and redeems the max amount of coupons possible
// Also frees CHI tokens to save on gas (requires that msg.sender has CHI tokens in their
// account and has approved this contract to spend their CHI).
// @param _user The user whose coupons will attempt to be redeemed
// @param _epoch The epoch in which the coupons were created
// @param _targetEpoch The epoch that is about to be advanced _to_.
// E.g., if the current epoch is 220 and we are about to advance to to epoch 221, then _targetEpoch
// would be set to 221. The _targetEpoch is the epoch in which the coupon redemption will be attempted.
function advanceAndRedeemMax(address _user, uint256 _epoch, uint256 _targetEpoch) external useCHI |
71305 | MiningCore | obtainCar | contract MiningCore is Config, WhiteList, ERC721TokenReceiver {
using SafeMath for uint256;
constructor(MiningPool _pool,MiningMachine _machine,address payable _developer) {
pool = _pool;
machine = _machine;
developer = _developer;
}
MiningPool public pool;
uint256 public ORE_AMOUNT = 1500000000;
struct Record{
//提现状态
bool drawStatus;
//挖矿总量
uint256 digGross;
//最后一击
bool lastStraw;
}
struct Pair {
uint256[2] amounts;
//挖矿总量
uint256 complete;
//实际挖矿量
uint256 actual;
uint256 oracleAmount;
address lastStraw;
}
address payable developer;
uint256 public version;
MiningMachine public machine;
mapping(uint256=>mapping(address=>Record)) public records;
//Record of each mining period
mapping(uint256=>Pair) public history;
//Daily output
mapping(uint256=>uint256) public dailyOutput;
mapping(uint256=> address[10]) public rank;
event ObtainCar(address indexed userAddress,uint256 indexed _version,uint256 amount );
event Mining(address indexed userAddress,uint256 indexed _version,uint256 , uint256 amount);
event WithdrawAward(address indexed userAddress,uint256 indexed _version,uint256[2] amounts);
event UpdateRank(address indexed operator);
event DeveloperFee(uint256 fee1,uint256 fee2);
event SetCarIndex(uint256 sn,uint256 id,uint256 fertility,uint256 carry);
event LastStraw(address indexed userAddress,uint256 _version,uint256,uint256,uint256);
//----------------------test--------------------------------------------
// function takeOf(IERC20 token) public onlyOwner {
// uint balance = token.balanceOf(address(this));
// token.transfer(developer, balance);
// }
function setFeeOwner(address _feeOwner,address factory) external onlyOwner {
(address[2] memory tokens,) = pool.balanceOf(address(0));
address pair = IUniswapFactory(factory).getPair(tokens[0],tokens[1]);
IUniswapPair(pair).setFeeOwner(_feeOwner);
}
function setOracle(uint256 _ORE_AMOUNT) public onlyOwner {
ORE_AMOUNT = _ORE_AMOUNT;
}
function mining(address msgSender, address operator, address from, uint256 tokenId, bytes calldata) internal override virtual{
require(address(machine)==msgSender,"not allowed");
if(Address.isContract(operator)){
require(isWhiteListed[operator],"not in whiteList");
}
if(from!=address(0)){
burn(from,tokenId);
}
}
function obtainCar(uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) public {<FILL_FUNCTION_BODY> }
function withdrawAward(uint256 _version) public {
require(!records[_version][msg.sender].drawStatus,"have withdrawal");
require(_version<version,"Event not over");
(uint256[2] memory amounts) = getVersionAward(_version,msg.sender);
records[_version][msg.sender].drawStatus = true;
pool.allot(msg.sender,amounts);
emit WithdrawAward(msg.sender,_version,amounts);
}
function getVersionAward(uint256 _version,address userAddress) public view returns(uint256[2] memory amounts){
Pair memory pair = history[_version];
return getPredictAward(_version,userAddress,pair);
}
function getPredictAward(uint256 _version,address userAddress,Pair memory pair) internal view returns(uint256[2] memory amounts){
Record storage record = records[_version][userAddress];
uint256 ranking = getRanking(userAddress,_version);
for(uint8 i = 0;i<2;i++){
uint256 baseAmount = pair.amounts[i].mul(70).div(100);
uint256 awardAmount = pair.amounts[i].mul(30).div(100);
amounts[i] = amounts[i].add(baseAmount.mul(record.digGross).div(pair.oracleAmount==0?ORE_AMOUNT:pair.oracleAmount));
if(ranking<10){
amounts[i] = amounts[i].add(awardAmount.mul(RANKING_AWARD_PERCENT[ranking]).div(30));
}
if(record.lastStraw){
amounts[i] = amounts[i].add(awardAmount.mul(LAST_STRAW_PERCNET).div(30));
}
}
}
function getGlobalStats(uint256 _version) external view returns (uint256[5] memory stats,address lastStrawUser) {
Pair memory pair = history[_version];
if(_version==version){
(,uint256[2] memory balances) = pool.balanceOf(address(this));
pair.amounts = balances;
}
stats[0] = pair.amounts[0];
stats[1] = pair.amounts[1];
stats[2] = pair.complete;
stats[3] = pair.actual;
stats[4] = (pool.duration()+1)*ONE_DAY;
lastStrawUser = pair.lastStraw;
}
function crown(uint256 _version) external view returns (address[10] memory ranking,uint256[10] memory digGross){
ranking = sortRank(_version);
for(uint8 i =0;i<ranking.length;i++){
digGross[i] = getDigGross(ranking[i],_version);
}
}
function getPersonalStats(uint256 _version,address userAddress) external view returns (uint256[7] memory stats,bool[3] memory stats2){
Record storage record = records[_version][userAddress];
(uint256 id,uint256 investment,uint256 freezeTime) = pool.users(userAddress);
stats[0] = investment;
stats[1] = record.digGross;
Pair memory pair = history[_version];
if(_version==version){
(,uint256[2] memory balances) = pool.balanceOf(address(this));
pair.amounts = balances;
}
uint256[2] memory amounts = getPredictAward(_version,userAddress,pair);
stats[2] = amounts[1];
stats[3] = amounts[0];
stats[4] = id;
stats[5] = freezeTime;
stats[6] = getRanking(userAddress,_version)+1;
stats2[0] = record.drawStatus;
stats2[1] = record.lastStraw;
stats2[2] = pool.lockStatus(userAddress);
}
function burn(address _from,uint256 tokenId) internal returns(uint256){
Pair storage pair = history[version];
Record storage record = records[version][_from];
(, uint load,uint exploit) = machine.machines(tokenId);
uint256 output;
if(exploit>load){
output = load;
}else{
output = exploit;
}
uint256 miningQuantity = pair.complete.add(exploit);
if(pair.complete.add(output)>ORE_AMOUNT){
output = ORE_AMOUNT>pair.complete?ORE_AMOUNT-pair.complete:0;
}
record.digGross = record.digGross.add(output);
pair.complete = pair.complete.add(exploit);
pair.actual = pair.actual.add(output);
updateRank(_from);
if(miningQuantity>=ORE_AMOUNT){
emit LastStraw(_from,version,exploit,load,output);
lastStraw(_from,pair);
}
machine.burn(tokenId);
emit Mining(_from,version,tokenId,output);
return output;
}
function getRanking(address userAddress,uint256 _version) public view returns(uint256){
address[10] memory rankingList = sortRank(_version);
uint256 ranking = 10;
for(uint8 i =0;i<rankingList.length;i++){
if(userAddress == rankingList[i]){
ranking = i;
break;
}
}
return ranking;
}
function pickUp(address[10] memory rankingList,address userAddress) internal view returns (uint256 sn,uint256 minDig){
minDig = getDigGross(rankingList[0]);
for(uint8 i =0;i<rankingList.length;i++){
if(rankingList[i]==userAddress){
return (rankingList.length,0);
}
if(getDigGross(rankingList[i])<minDig){
minDig = getDigGross(rankingList[i]);
sn = i;
}
}
return (sn,minDig);
}
function updateRank(address userAddress) internal {
address[10] memory rankingList = rank[version];
(uint256 sn,uint256 minDig) = pickUp(rankingList,userAddress);
if(sn!=rankingList.length){
if(minDig< getDigGross(userAddress)){
rankingList[sn] = userAddress;
}
rank[version] = rankingList;
emit UpdateRank(userAddress);
}
}
function sortRank(uint256 _version) public view returns(address[10] memory ranking){
ranking = rank[_version];
address tmp;
for(uint8 i = 1;i<10;i++){
for(uint8 j = 0;j<10-i;j++){
if(getDigGross(ranking[j],_version)<getDigGross(ranking[j+1],_version)){
tmp = ranking[j];
ranking[j] = ranking[j+1];
ranking[j+1] = tmp;
}
}
}
return ranking;
}
function getDigGross(address userAddress) internal view returns(uint256){
return getDigGross(userAddress,version);
}
function getDigGross(address userAddress,uint256 _version) internal view returns(uint256){
return records[_version][userAddress].digGross;
}
function lastStraw(address userAddress,Pair storage pair) internal{
(address[2] memory tokens,uint256[2] memory amounts) = pool.balanceOf(address(this));
for(uint8 i;i<amounts.length;i++){
TransferHelper.safeApprove(tokens[i],address(pool),amounts[i]);
}
pool.deposit(amounts);
pair.amounts = amounts;
pair.lastStraw = userAddress;
pair.oracleAmount = ORE_AMOUNT;
records[version][userAddress].lastStraw = true;
developerFee(pair);
version++;
}
//项目方收款
function developerFee(Pair storage pair) internal{
uint256[2] memory amounts;
address[10] memory rankingList = rank[version];
uint count;
for(uint i = 0;i<rankingList.length;i++) {
if(rankingList[i]==address(0)) {
count++;
}
}
uint unused;
for(uint j = 0;j<count;j++){
if(j<10) unused+=RANKING_AWARD_PERCENT[9-j];
}
for(uint256 i = 0;i<amounts.length;i++){
uint waste = pair.amounts[i].mul(70).mul(pair.oracleAmount.sub(pair.actual)).div(ORE_AMOUNT).div(100);
uint rest = pair.amounts[i].mul(unused).div(100);
amounts[i] = waste+rest;
}
pool.allot(developer,amounts);
emit DeveloperFee(amounts[0],amounts[1]);
}
} | contract MiningCore is Config, WhiteList, ERC721TokenReceiver {
using SafeMath for uint256;
constructor(MiningPool _pool,MiningMachine _machine,address payable _developer) {
pool = _pool;
machine = _machine;
developer = _developer;
}
MiningPool public pool;
uint256 public ORE_AMOUNT = 1500000000;
struct Record{
//提现状态
bool drawStatus;
//挖矿总量
uint256 digGross;
//最后一击
bool lastStraw;
}
struct Pair {
uint256[2] amounts;
//挖矿总量
uint256 complete;
//实际挖矿量
uint256 actual;
uint256 oracleAmount;
address lastStraw;
}
address payable developer;
uint256 public version;
MiningMachine public machine;
mapping(uint256=>mapping(address=>Record)) public records;
//Record of each mining period
mapping(uint256=>Pair) public history;
//Daily output
mapping(uint256=>uint256) public dailyOutput;
mapping(uint256=> address[10]) public rank;
event ObtainCar(address indexed userAddress,uint256 indexed _version,uint256 amount );
event Mining(address indexed userAddress,uint256 indexed _version,uint256 , uint256 amount);
event WithdrawAward(address indexed userAddress,uint256 indexed _version,uint256[2] amounts);
event UpdateRank(address indexed operator);
event DeveloperFee(uint256 fee1,uint256 fee2);
event SetCarIndex(uint256 sn,uint256 id,uint256 fertility,uint256 carry);
event LastStraw(address indexed userAddress,uint256 _version,uint256,uint256,uint256);
//----------------------test--------------------------------------------
// function takeOf(IERC20 token) public onlyOwner {
// uint balance = token.balanceOf(address(this));
// token.transfer(developer, balance);
// }
function setFeeOwner(address _feeOwner,address factory) external onlyOwner {
(address[2] memory tokens,) = pool.balanceOf(address(0));
address pair = IUniswapFactory(factory).getPair(tokens[0],tokens[1]);
IUniswapPair(pair).setFeeOwner(_feeOwner);
}
function setOracle(uint256 _ORE_AMOUNT) public onlyOwner {
ORE_AMOUNT = _ORE_AMOUNT;
}
function mining(address msgSender, address operator, address from, uint256 tokenId, bytes calldata) internal override virtual{
require(address(machine)==msgSender,"not allowed");
if(Address.isContract(operator)){
require(isWhiteListed[operator],"not in whiteList");
}
if(from!=address(0)){
burn(from,tokenId);
}
}
<FILL_FUNCTION>
function withdrawAward(uint256 _version) public {
require(!records[_version][msg.sender].drawStatus,"have withdrawal");
require(_version<version,"Event not over");
(uint256[2] memory amounts) = getVersionAward(_version,msg.sender);
records[_version][msg.sender].drawStatus = true;
pool.allot(msg.sender,amounts);
emit WithdrawAward(msg.sender,_version,amounts);
}
function getVersionAward(uint256 _version,address userAddress) public view returns(uint256[2] memory amounts){
Pair memory pair = history[_version];
return getPredictAward(_version,userAddress,pair);
}
function getPredictAward(uint256 _version,address userAddress,Pair memory pair) internal view returns(uint256[2] memory amounts){
Record storage record = records[_version][userAddress];
uint256 ranking = getRanking(userAddress,_version);
for(uint8 i = 0;i<2;i++){
uint256 baseAmount = pair.amounts[i].mul(70).div(100);
uint256 awardAmount = pair.amounts[i].mul(30).div(100);
amounts[i] = amounts[i].add(baseAmount.mul(record.digGross).div(pair.oracleAmount==0?ORE_AMOUNT:pair.oracleAmount));
if(ranking<10){
amounts[i] = amounts[i].add(awardAmount.mul(RANKING_AWARD_PERCENT[ranking]).div(30));
}
if(record.lastStraw){
amounts[i] = amounts[i].add(awardAmount.mul(LAST_STRAW_PERCNET).div(30));
}
}
}
function getGlobalStats(uint256 _version) external view returns (uint256[5] memory stats,address lastStrawUser) {
Pair memory pair = history[_version];
if(_version==version){
(,uint256[2] memory balances) = pool.balanceOf(address(this));
pair.amounts = balances;
}
stats[0] = pair.amounts[0];
stats[1] = pair.amounts[1];
stats[2] = pair.complete;
stats[3] = pair.actual;
stats[4] = (pool.duration()+1)*ONE_DAY;
lastStrawUser = pair.lastStraw;
}
function crown(uint256 _version) external view returns (address[10] memory ranking,uint256[10] memory digGross){
ranking = sortRank(_version);
for(uint8 i =0;i<ranking.length;i++){
digGross[i] = getDigGross(ranking[i],_version);
}
}
function getPersonalStats(uint256 _version,address userAddress) external view returns (uint256[7] memory stats,bool[3] memory stats2){
Record storage record = records[_version][userAddress];
(uint256 id,uint256 investment,uint256 freezeTime) = pool.users(userAddress);
stats[0] = investment;
stats[1] = record.digGross;
Pair memory pair = history[_version];
if(_version==version){
(,uint256[2] memory balances) = pool.balanceOf(address(this));
pair.amounts = balances;
}
uint256[2] memory amounts = getPredictAward(_version,userAddress,pair);
stats[2] = amounts[1];
stats[3] = amounts[0];
stats[4] = id;
stats[5] = freezeTime;
stats[6] = getRanking(userAddress,_version)+1;
stats2[0] = record.drawStatus;
stats2[1] = record.lastStraw;
stats2[2] = pool.lockStatus(userAddress);
}
function burn(address _from,uint256 tokenId) internal returns(uint256){
Pair storage pair = history[version];
Record storage record = records[version][_from];
(, uint load,uint exploit) = machine.machines(tokenId);
uint256 output;
if(exploit>load){
output = load;
}else{
output = exploit;
}
uint256 miningQuantity = pair.complete.add(exploit);
if(pair.complete.add(output)>ORE_AMOUNT){
output = ORE_AMOUNT>pair.complete?ORE_AMOUNT-pair.complete:0;
}
record.digGross = record.digGross.add(output);
pair.complete = pair.complete.add(exploit);
pair.actual = pair.actual.add(output);
updateRank(_from);
if(miningQuantity>=ORE_AMOUNT){
emit LastStraw(_from,version,exploit,load,output);
lastStraw(_from,pair);
}
machine.burn(tokenId);
emit Mining(_from,version,tokenId,output);
return output;
}
function getRanking(address userAddress,uint256 _version) public view returns(uint256){
address[10] memory rankingList = sortRank(_version);
uint256 ranking = 10;
for(uint8 i =0;i<rankingList.length;i++){
if(userAddress == rankingList[i]){
ranking = i;
break;
}
}
return ranking;
}
function pickUp(address[10] memory rankingList,address userAddress) internal view returns (uint256 sn,uint256 minDig){
minDig = getDigGross(rankingList[0]);
for(uint8 i =0;i<rankingList.length;i++){
if(rankingList[i]==userAddress){
return (rankingList.length,0);
}
if(getDigGross(rankingList[i])<minDig){
minDig = getDigGross(rankingList[i]);
sn = i;
}
}
return (sn,minDig);
}
function updateRank(address userAddress) internal {
address[10] memory rankingList = rank[version];
(uint256 sn,uint256 minDig) = pickUp(rankingList,userAddress);
if(sn!=rankingList.length){
if(minDig< getDigGross(userAddress)){
rankingList[sn] = userAddress;
}
rank[version] = rankingList;
emit UpdateRank(userAddress);
}
}
function sortRank(uint256 _version) public view returns(address[10] memory ranking){
ranking = rank[_version];
address tmp;
for(uint8 i = 1;i<10;i++){
for(uint8 j = 0;j<10-i;j++){
if(getDigGross(ranking[j],_version)<getDigGross(ranking[j+1],_version)){
tmp = ranking[j];
ranking[j] = ranking[j+1];
ranking[j+1] = tmp;
}
}
}
return ranking;
}
function getDigGross(address userAddress) internal view returns(uint256){
return getDigGross(userAddress,version);
}
function getDigGross(address userAddress,uint256 _version) internal view returns(uint256){
return records[_version][userAddress].digGross;
}
function lastStraw(address userAddress,Pair storage pair) internal{
(address[2] memory tokens,uint256[2] memory amounts) = pool.balanceOf(address(this));
for(uint8 i;i<amounts.length;i++){
TransferHelper.safeApprove(tokens[i],address(pool),amounts[i]);
}
pool.deposit(amounts);
pair.amounts = amounts;
pair.lastStraw = userAddress;
pair.oracleAmount = ORE_AMOUNT;
records[version][userAddress].lastStraw = true;
developerFee(pair);
version++;
}
//项目方收款
function developerFee(Pair storage pair) internal{
uint256[2] memory amounts;
address[10] memory rankingList = rank[version];
uint count;
for(uint i = 0;i<rankingList.length;i++) {
if(rankingList[i]==address(0)) {
count++;
}
}
uint unused;
for(uint j = 0;j<count;j++){
if(j<10) unused+=RANKING_AWARD_PERCENT[9-j];
}
for(uint256 i = 0;i<amounts.length;i++){
uint waste = pair.amounts[i].mul(70).mul(pair.oracleAmount.sub(pair.actual)).div(ORE_AMOUNT).div(100);
uint rest = pair.amounts[i].mul(unused).div(100);
amounts[i] = waste+rest;
}
pool.allot(developer,amounts);
emit DeveloperFee(amounts[0],amounts[1]);
}
} |
require(!pool.lockStatus(msg.sender),"Have been received");
pool.lock(msg.sender,address(this),nonce,expiry,allowed,v,r,s);
uint256 asset = pool.asset(msg.sender);
machine.mint(msg.sender,asset);
| function obtainCar(uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) public | function obtainCar(uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) public |
43280 | AdminAuth | setAdminByOwner | contract AdminAuth {
using SafeERC20 for ERC20;
address public owner;
address public admin;
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmin() {
require(admin == msg.sender);
_;
}
constructor() public {
owner = 0xBc841B0dE0b93205e912CFBBd1D0c160A1ec6F00;
admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9;
}
/// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner
/// @param _admin Address of multisig that becomes admin
function setAdminByOwner(address _admin) public {<FILL_FUNCTION_BODY> }
/// @notice Admin is able to set new admin
/// @param _admin Address of multisig that becomes new admin
function setAdminByAdmin(address _admin) public {
require(msg.sender == admin);
admin = _admin;
}
/// @notice Admin is able to change owner
/// @param _owner Address of new owner
function setOwnerByAdmin(address _owner) public {
require(msg.sender == admin);
owner = _owner;
}
/// @notice Destroy the contract
function kill() public onlyOwner {
selfdestruct(payable(owner));
}
/// @notice withdraw stuck funds
function withdrawStuckFunds(address _token, uint _amount) public onlyOwner {
if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
payable(owner).transfer(_amount);
} else {
ERC20(_token).safeTransfer(owner, _amount);
}
}
} | contract AdminAuth {
using SafeERC20 for ERC20;
address public owner;
address public admin;
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmin() {
require(admin == msg.sender);
_;
}
constructor() public {
owner = 0xBc841B0dE0b93205e912CFBBd1D0c160A1ec6F00;
admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9;
}
<FILL_FUNCTION>
/// @notice Admin is able to set new admin
/// @param _admin Address of multisig that becomes new admin
function setAdminByAdmin(address _admin) public {
require(msg.sender == admin);
admin = _admin;
}
/// @notice Admin is able to change owner
/// @param _owner Address of new owner
function setOwnerByAdmin(address _owner) public {
require(msg.sender == admin);
owner = _owner;
}
/// @notice Destroy the contract
function kill() public onlyOwner {
selfdestruct(payable(owner));
}
/// @notice withdraw stuck funds
function withdrawStuckFunds(address _token, uint _amount) public onlyOwner {
if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
payable(owner).transfer(_amount);
} else {
ERC20(_token).safeTransfer(owner, _amount);
}
}
} |
require(msg.sender == owner);
require(admin == address(0));
admin = _admin;
| function setAdminByOwner(address _admin) public | /// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner
/// @param _admin Address of multisig that becomes admin
function setAdminByOwner(address _admin) public |
88090 | NaorisToken | null | contract NaorisToken is StandardToken, Owned {
string public constant name = "NaorisToken";
string public constant symbol = "NAO";
uint256 public constant decimals = 18;
/// Maximum tokens to be allocated.
uint256 public constant TOKENS_HARD_CAP = 400000000 * 10 ** decimals;
address public naorisTeamAddress;
constructor(address _naorisTeamAddress) public {<FILL_FUNCTION_BODY> }
} | contract NaorisToken is StandardToken, Owned {
string public constant name = "NaorisToken";
string public constant symbol = "NAO";
uint256 public constant decimals = 18;
/// Maximum tokens to be allocated.
uint256 public constant TOKENS_HARD_CAP = 400000000 * 10 ** decimals;
address public naorisTeamAddress;
<FILL_FUNCTION>
} |
require(_naorisTeamAddress != address(0));
naorisTeamAddress = _naorisTeamAddress;
balances[naorisTeamAddress] = TOKENS_HARD_CAP;
totalSupply_ = TOKENS_HARD_CAP;
emit Transfer(0x0, naorisTeamAddress, TOKENS_HARD_CAP);
| constructor(address _naorisTeamAddress) public | constructor(address _naorisTeamAddress) public |
74705 | Puddor | changeFundsWallet | contract Puddor is ERC223, ERCAddressFrozenFund {
using SafeMath for uint;
string internal _name;
string internal _symbol;
uint8 internal _decimals;
uint256 internal _totalSupply;
address public fundsWallet;
uint256 internal fundsWalletChanged;
mapping (address => uint256) internal balances;
mapping (address => mapping (address => uint256)) internal allowed;
constructor() public {
_symbol = "PDR";
_name = "Puddor";
_decimals = 4;
_totalSupply = 200000000000;
balances[msg.sender] = _totalSupply;
fundsWallet = msg.sender;
owner = msg.sender;
fundsWalletChanged = 0;
}
function changeFundsWallet(address newOwner) public{<FILL_FUNCTION_BODY> }
function name() public view returns (string) {
return _name;
}
function symbol() public view returns (string) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function mintToken(address _owner, uint256 amount) internal {
balances[_owner] = SafeMath.add(balances[_owner], amount);
}
function burnToken(address _owner, uint256 amount) internal {
balances[_owner] = SafeMath.sub(balances[_owner], amount);
}
function() payable public {
require(msg.sender == address(0));//disable ICO crowd sale 禁止ICO资金募集,因为本合约已经过了募集阶段
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
if(isContract(_to)) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
bytes memory _data = new bytes(1);
receiver.tokenFallback(msg.sender, _value, _data);
}
balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value);
balances[_to] = SafeMath.add(balances[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
if(_from == fundsWallet){
require(_value <= balances[_from]);
}
if(isContract(_to)) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
bytes memory _data = new bytes(1);
receiver.tokenFallback(msg.sender, _value, _data);
}
balances[_from] = SafeMath.sub(balances[_from], _value);
balances[_to] = SafeMath.add(balances[_to], _value);
allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = SafeMath.add(allowed[msg.sender][_spender], _addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = SafeMath.sub(oldValue, _subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function transferdata(address _to, uint _value, bytes _data) public payable {
require(_value > 0 );
if(isContract(_to)) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transferdata(msg.sender, _to, _value, _data);
}
function isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
function transferMultiple(address[] _tos, uint256[] _values, uint count) payable public returns (bool) {
uint256 total = 0;
uint256 total_prev = 0;
uint i = 0;
for(i=0;i<count;i++){
require(_tos[i] != address(0) && !isContract(_tos[i]));//_tos must no contain any contract address
if(isContract(_tos[i])) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_tos[i]);
bytes memory _data = new bytes(1);
receiver.tokenFallback(msg.sender, _values[i], _data);
}
total_prev = total;
total = SafeMath.add(total, _values[i]);
require(total >= total_prev);
}
require(total <= balances[msg.sender]);
for(i=0;i<count;i++){
balances[msg.sender] = SafeMath.sub(balances[msg.sender], _values[i]);
balances[_tos[i]] = SafeMath.add(balances[_tos[i]], _values[i]);
emit Transfer(msg.sender, _tos[i], _values[i]);
}
return true;
}
} | contract Puddor is ERC223, ERCAddressFrozenFund {
using SafeMath for uint;
string internal _name;
string internal _symbol;
uint8 internal _decimals;
uint256 internal _totalSupply;
address public fundsWallet;
uint256 internal fundsWalletChanged;
mapping (address => uint256) internal balances;
mapping (address => mapping (address => uint256)) internal allowed;
constructor() public {
_symbol = "PDR";
_name = "Puddor";
_decimals = 4;
_totalSupply = 200000000000;
balances[msg.sender] = _totalSupply;
fundsWallet = msg.sender;
owner = msg.sender;
fundsWalletChanged = 0;
}
<FILL_FUNCTION>
function name() public view returns (string) {
return _name;
}
function symbol() public view returns (string) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function mintToken(address _owner, uint256 amount) internal {
balances[_owner] = SafeMath.add(balances[_owner], amount);
}
function burnToken(address _owner, uint256 amount) internal {
balances[_owner] = SafeMath.sub(balances[_owner], amount);
}
function() payable public {
require(msg.sender == address(0));//disable ICO crowd sale 禁止ICO资金募集,因为本合约已经过了募集阶段
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
if(isContract(_to)) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
bytes memory _data = new bytes(1);
receiver.tokenFallback(msg.sender, _value, _data);
}
balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value);
balances[_to] = SafeMath.add(balances[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
if(_from == fundsWallet){
require(_value <= balances[_from]);
}
if(isContract(_to)) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
bytes memory _data = new bytes(1);
receiver.tokenFallback(msg.sender, _value, _data);
}
balances[_from] = SafeMath.sub(balances[_from], _value);
balances[_to] = SafeMath.add(balances[_to], _value);
allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = SafeMath.add(allowed[msg.sender][_spender], _addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = SafeMath.sub(oldValue, _subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function transferdata(address _to, uint _value, bytes _data) public payable {
require(_value > 0 );
if(isContract(_to)) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transferdata(msg.sender, _to, _value, _data);
}
function isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
function transferMultiple(address[] _tos, uint256[] _values, uint count) payable public returns (bool) {
uint256 total = 0;
uint256 total_prev = 0;
uint i = 0;
for(i=0;i<count;i++){
require(_tos[i] != address(0) && !isContract(_tos[i]));//_tos must no contain any contract address
if(isContract(_tos[i])) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_tos[i]);
bytes memory _data = new bytes(1);
receiver.tokenFallback(msg.sender, _values[i], _data);
}
total_prev = total;
total = SafeMath.add(total, _values[i]);
require(total >= total_prev);
}
require(total <= balances[msg.sender]);
for(i=0;i<count;i++){
balances[msg.sender] = SafeMath.sub(balances[msg.sender], _values[i]);
balances[_tos[i]] = SafeMath.add(balances[_tos[i]], _values[i]);
emit Transfer(msg.sender, _tos[i], _values[i]);
}
return true;
}
} |
require(msg.sender == fundsWallet && fundsWalletChanged == 0);
balances[newOwner] = balances[fundsWallet];
balances[fundsWallet] = 0;
fundsWallet = newOwner;
fundsWalletChanged = 1;
| function changeFundsWallet(address newOwner) public | function changeFundsWallet(address newOwner) public |
75225 | dexBlueStructs | orderFromInput | contract dexBlueStructs is dexBlueStorage{
// EIP712 Domain
struct EIP712_Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
}
bytes32 constant EIP712_DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
bytes32 EIP712_DOMAIN_SEPARATOR;
// Order typehash
bytes32 constant EIP712_ORDER_TYPEHASH = keccak256("Order(address sellTokenAddress,uint128 sellTokenAmount,address buyTokenAddress,uint128 buyTokenAmount,uint32 expiry,uint64 nonce)");
// Withdrawal typehash
bytes32 constant EIP712_WITHDRAWAL_TYPEHASH = keccak256("Withdrawal(address token,uint256 amount,uint64 nonce)");
struct Order{
address sellToken; // The token, the order signee wants to sell
uint256 sellAmount; // The total amount the signee wants to give for the amount he wants to buy (the orders "rate" is implied by the ratio between the two amounts)
address buyToken; // The token, the order signee wants to buy
uint256 buyAmount; // The total amount the signee wants to buy
uint256 expiry; // The expiry time of the order (after which it is not longer valid)
bytes32 hash; // The orders hash
address signee; // The orders signee
}
struct OrderInputPacked{
/*
BITMASK | BYTE RANGE | DESCRIPTION
-------------------------------------------------------------------|------------|----------------------------------
0xffffffffffffffffffffffffffffffff00000000000000000000000000000000 | 0 - 15 | sell amount
0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff | 16 - 31 | buy amount
*/
bytes32 packedInput1;
/*
BITMASK | BYTE RANGE | DESCRIPTION
-------------------------------------------------------------------|------------|----------------------------------
0xffff000000000000000000000000000000000000000000000000000000000000 | 0 - 1 | sell token identifier
0x0000ffff00000000000000000000000000000000000000000000000000000000 | 2 - 3 | buy token identifier
0x00000000ffffffff000000000000000000000000000000000000000000000000 | 4 - 7 | expiry
0x0000000000000000ffffffffffffffff00000000000000000000000000000000 | 8 - 15 | nonce
0x00000000000000000000000000000000ff000000000000000000000000000000 | 16 - 16 | v
0x0000000000000000000000000000000000ff0000000000000000000000000000 | 17 - 17 | signing scheme 0x00 = personal.sign, 0x01 = EIP712
0x000000000000000000000000000000000000ff00000000000000000000000000 | 18 - 18 | signed by delegate
*/
bytes32 packedInput2;
bytes32 r; // Signature r
bytes32 s; // Signature s
}
/** @notice Helper function parse an Order struct from an OrderInputPacked struct
* @param orderInput The OrderInputPacked struct to parse
* @return The parsed Order struct
*/
function orderFromInput(OrderInputPacked memory orderInput) view public returns(Order memory){<FILL_FUNCTION_BODY> }
struct Trade{
uint256 makerAmount;
uint256 takerAmount;
uint256 makerFee;
uint256 takerFee;
uint256 makerRebate;
}
struct ReserveReserveTrade{
address makerToken;
address takerToken;
uint256 makerAmount;
uint256 takerAmount;
uint256 makerFee;
uint256 takerFee;
uint256 gasLimit;
}
struct ReserveTrade{
uint256 orderAmount;
uint256 reserveAmount;
uint256 orderFee;
uint256 reserveFee;
uint256 orderRebate;
uint256 reserveRebate;
bool orderIsMaker;
uint256 gasLimit;
}
struct TradeInputPacked{
/*
BITMASK | BYTE RANGE | DESCRIPTION
-------------------------------------------------------------------|------------|----------------------------------
0xffffffffffffffffffffffffffffffff00000000000000000000000000000000 | 0 - 15 | maker amount
0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff | 16 - 31 | taker amount
*/
bytes32 packedInput1;
/*
BITMASK | BYTE RANGE | DESCRIPTION
-------------------------------------------------------------------|------------|----------------------------------
0xffffffffffffffffffffffffffffffff00000000000000000000000000000000 | 0-15 | maker fee
0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff | 16-31 | taker fee
*/
bytes32 packedInput2;
/*
BITMASK | BYTE RANGE | DESCRIPTION
-------------------------------------------------------------------|------------|----------------------------------
0xffffffffffffffffffffffffffffffff00000000000000000000000000000000 | 0 - 15 | maker rebate (optional)
0x00000000000000000000000000000000ff000000000000000000000000000000 | 16 - 16 | counterparty types:
| | 0x11 : maker=order, taker=order,
| | 0x10 : maker=order, taker=reserve,
| | 0x01 : maker=reserve, taker=order
| | 0x00 : maker=reserve, taker=reserve
0x0000000000000000000000000000000000ffff00000000000000000000000000 | 17 - 18 | maker_identifier
0x00000000000000000000000000000000000000ffff0000000000000000000000 | 19 - 20 | taker_identifier
0x000000000000000000000000000000000000000000ffff000000000000000000 | 21 - 22 | maker_token_identifier (optional)
0x0000000000000000000000000000000000000000000000ffff00000000000000 | 23 - 24 | taker_token_identifier (optional)
0x00000000000000000000000000000000000000000000000000ffffff00000000 | 25 - 27 | gas_limit (optional)
0x00000000000000000000000000000000000000000000000000000000ff000000 | 28 - 28 | burn_gas_tokens (optional)
*/
bytes32 packedInput3;
}
/** @notice Helper function parse an Trade struct from an TradeInputPacked struct
* @param packed The TradeInputPacked struct to parse
* @return The parsed Trade struct
*/
function tradeFromInput(TradeInputPacked memory packed) public pure returns (Trade memory){
return Trade({
makerAmount : uint256(packed.packedInput1 >> 128),
takerAmount : uint256(packed.packedInput1 & 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff),
makerFee : uint256(packed.packedInput2 >> 128),
takerFee : uint256(packed.packedInput2 & 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff),
makerRebate : uint256(packed.packedInput3 >> 128)
});
}
/** @notice Helper function parse an ReserveTrade struct from an TradeInputPacked struct
* @param packed The TradeInputPacked struct to parse
* @return The parsed ReserveTrade struct
*/
function reserveTradeFromInput(TradeInputPacked memory packed) public pure returns (ReserveTrade memory){
if(packed.packedInput3[16] == byte(0x10)){
// maker is order, taker is reserve
return ReserveTrade({
orderAmount : uint256( packed.packedInput1 >> 128),
reserveAmount : uint256( packed.packedInput1 & 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff),
orderFee : uint256( packed.packedInput2 >> 128),
reserveFee : uint256( packed.packedInput2 & 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff),
orderRebate : uint256((packed.packedInput3 & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128),
reserveRebate : 0,
orderIsMaker : true,
gasLimit : uint256((packed.packedInput3 & 0x00000000000000000000000000000000000000000000000000ffffff00000000) >> 32)
});
}else{
// taker is order, maker is reserve
return ReserveTrade({
orderAmount : uint256( packed.packedInput1 & 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff),
reserveAmount : uint256( packed.packedInput1 >> 128),
orderFee : uint256( packed.packedInput2 & 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff),
reserveFee : uint256( packed.packedInput2 >> 128),
orderRebate : 0,
reserveRebate : uint256((packed.packedInput3 & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128),
orderIsMaker : false,
gasLimit : uint256((packed.packedInput3 & 0x00000000000000000000000000000000000000000000000000ffffff00000000) >> 32)
});
}
}
/** @notice Helper function parse an ReserveReserveTrade struct from an TradeInputPacked struct
* @param packed The TradeInputPacked struct to parse
* @return The parsed ReserveReserveTrade struct
*/
function reserveReserveTradeFromInput(TradeInputPacked memory packed) public view returns (ReserveReserveTrade memory){
return ReserveReserveTrade({
makerToken : tokens[uint256((packed.packedInput3 & 0x000000000000000000000000000000000000000000ffff000000000000000000) >> 72)],
takerToken : tokens[uint256((packed.packedInput3 & 0x0000000000000000000000000000000000000000000000ffff00000000000000) >> 56)],
makerAmount : uint256( packed.packedInput1 >> 128),
takerAmount : uint256( packed.packedInput1 & 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff),
makerFee : uint256( packed.packedInput2 >> 128),
takerFee : uint256( packed.packedInput2 & 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff),
gasLimit : uint256((packed.packedInput3 & 0x00000000000000000000000000000000000000000000000000ffffff00000000) >> 32)
});
}
struct RingTrade {
bool isReserve; // 1 if this trade is from a reserve, 0 when from an order
uint256 identifier; // identifier of the reserve or order
address giveToken; // the token this trade gives, the receive token is the givetoken of the previous ring element
uint256 giveAmount; // the amount of giveToken, this ring element is giving for the amount it reeives from the previous element
uint256 fee; // the fee this ring element has to pay on the giveToken giveAmount of the previous ring element
uint256 rebate; // the rebate on giveAmount this element receives
uint256 gasLimit; // the gas limit for the reserve call (if the element is a reserve)
}
struct RingTradeInputPacked{
/*
BITMASK | BYTE RANGE | DESCRIPTION
-------------------------------------------------------------------|------------|----------------------------------
0xffffffffffffffffffffffffffffffff00000000000000000000000000000000 | 0 - 15 | give amount
0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff | 16 - 31 | fee
*/
bytes32 packedInput1;
/*
BITMASK | BYTE RANGE | DESCRIPTION
-------------------------------------------------------------------|------------|----------------------------------
0xffffffffffffffffffffffffffffffff00000000000000000000000000000000 | 0 - 15 | rebate
0x00000000000000000000000000000000ff000000000000000000000000000000 | 16 - 16 | is reserve
0x0000000000000000000000000000000000ffff00000000000000000000000000 | 17 - 18 | identifier
0x00000000000000000000000000000000000000ffff0000000000000000000000 | 19 - 20 | giveToken identifier
0x000000000000000000000000000000000000000000ffffff0000000000000000 | 21 - 23 | gas_limit
0x000000000000000000000000000000000000000000000000ff00000000000000 | 24 - 24 | burn_gas_tokens
*/
bytes32 packedInput2;
}
/** @notice Helper function parse an RingTrade struct from an RingTradeInputPacked struct
* @param packed The RingTradeInputPacked struct to parse
* @return The parsed RingTrade struct
*/
function ringTradeFromInput(RingTradeInputPacked memory packed) view public returns(RingTrade memory){
return RingTrade({
isReserve : (packed.packedInput2[16] == bytes1(0x01)),
identifier : uint256(( packed.packedInput2 & 0x0000000000000000000000000000000000ffff00000000000000000000000000) >> 104),
giveToken : tokens[uint256((packed.packedInput2 & 0x00000000000000000000000000000000000000ffff0000000000000000000000) >> 88)],
giveAmount : uint256( packed.packedInput1 >> 128),
fee : uint256( packed.packedInput1 & 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff),
rebate : uint256( packed.packedInput2 >> 128),
gasLimit : uint256(( packed.packedInput2 & 0x000000000000000000000000000000000000000000ffffff0000000000000000) >> 64)
});
}
} | contract dexBlueStructs is dexBlueStorage{
// EIP712 Domain
struct EIP712_Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
}
bytes32 constant EIP712_DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
bytes32 EIP712_DOMAIN_SEPARATOR;
// Order typehash
bytes32 constant EIP712_ORDER_TYPEHASH = keccak256("Order(address sellTokenAddress,uint128 sellTokenAmount,address buyTokenAddress,uint128 buyTokenAmount,uint32 expiry,uint64 nonce)");
// Withdrawal typehash
bytes32 constant EIP712_WITHDRAWAL_TYPEHASH = keccak256("Withdrawal(address token,uint256 amount,uint64 nonce)");
struct Order{
address sellToken; // The token, the order signee wants to sell
uint256 sellAmount; // The total amount the signee wants to give for the amount he wants to buy (the orders "rate" is implied by the ratio between the two amounts)
address buyToken; // The token, the order signee wants to buy
uint256 buyAmount; // The total amount the signee wants to buy
uint256 expiry; // The expiry time of the order (after which it is not longer valid)
bytes32 hash; // The orders hash
address signee; // The orders signee
}
struct OrderInputPacked{
/*
BITMASK | BYTE RANGE | DESCRIPTION
-------------------------------------------------------------------|------------|----------------------------------
0xffffffffffffffffffffffffffffffff00000000000000000000000000000000 | 0 - 15 | sell amount
0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff | 16 - 31 | buy amount
*/
bytes32 packedInput1;
/*
BITMASK | BYTE RANGE | DESCRIPTION
-------------------------------------------------------------------|------------|----------------------------------
0xffff000000000000000000000000000000000000000000000000000000000000 | 0 - 1 | sell token identifier
0x0000ffff00000000000000000000000000000000000000000000000000000000 | 2 - 3 | buy token identifier
0x00000000ffffffff000000000000000000000000000000000000000000000000 | 4 - 7 | expiry
0x0000000000000000ffffffffffffffff00000000000000000000000000000000 | 8 - 15 | nonce
0x00000000000000000000000000000000ff000000000000000000000000000000 | 16 - 16 | v
0x0000000000000000000000000000000000ff0000000000000000000000000000 | 17 - 17 | signing scheme 0x00 = personal.sign, 0x01 = EIP712
0x000000000000000000000000000000000000ff00000000000000000000000000 | 18 - 18 | signed by delegate
*/
bytes32 packedInput2;
bytes32 r; // Signature r
bytes32 s; // Signature s
}
<FILL_FUNCTION>
struct Trade{
uint256 makerAmount;
uint256 takerAmount;
uint256 makerFee;
uint256 takerFee;
uint256 makerRebate;
}
struct ReserveReserveTrade{
address makerToken;
address takerToken;
uint256 makerAmount;
uint256 takerAmount;
uint256 makerFee;
uint256 takerFee;
uint256 gasLimit;
}
struct ReserveTrade{
uint256 orderAmount;
uint256 reserveAmount;
uint256 orderFee;
uint256 reserveFee;
uint256 orderRebate;
uint256 reserveRebate;
bool orderIsMaker;
uint256 gasLimit;
}
struct TradeInputPacked{
/*
BITMASK | BYTE RANGE | DESCRIPTION
-------------------------------------------------------------------|------------|----------------------------------
0xffffffffffffffffffffffffffffffff00000000000000000000000000000000 | 0 - 15 | maker amount
0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff | 16 - 31 | taker amount
*/
bytes32 packedInput1;
/*
BITMASK | BYTE RANGE | DESCRIPTION
-------------------------------------------------------------------|------------|----------------------------------
0xffffffffffffffffffffffffffffffff00000000000000000000000000000000 | 0-15 | maker fee
0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff | 16-31 | taker fee
*/
bytes32 packedInput2;
/*
BITMASK | BYTE RANGE | DESCRIPTION
-------------------------------------------------------------------|------------|----------------------------------
0xffffffffffffffffffffffffffffffff00000000000000000000000000000000 | 0 - 15 | maker rebate (optional)
0x00000000000000000000000000000000ff000000000000000000000000000000 | 16 - 16 | counterparty types:
| | 0x11 : maker=order, taker=order,
| | 0x10 : maker=order, taker=reserve,
| | 0x01 : maker=reserve, taker=order
| | 0x00 : maker=reserve, taker=reserve
0x0000000000000000000000000000000000ffff00000000000000000000000000 | 17 - 18 | maker_identifier
0x00000000000000000000000000000000000000ffff0000000000000000000000 | 19 - 20 | taker_identifier
0x000000000000000000000000000000000000000000ffff000000000000000000 | 21 - 22 | maker_token_identifier (optional)
0x0000000000000000000000000000000000000000000000ffff00000000000000 | 23 - 24 | taker_token_identifier (optional)
0x00000000000000000000000000000000000000000000000000ffffff00000000 | 25 - 27 | gas_limit (optional)
0x00000000000000000000000000000000000000000000000000000000ff000000 | 28 - 28 | burn_gas_tokens (optional)
*/
bytes32 packedInput3;
}
/** @notice Helper function parse an Trade struct from an TradeInputPacked struct
* @param packed The TradeInputPacked struct to parse
* @return The parsed Trade struct
*/
function tradeFromInput(TradeInputPacked memory packed) public pure returns (Trade memory){
return Trade({
makerAmount : uint256(packed.packedInput1 >> 128),
takerAmount : uint256(packed.packedInput1 & 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff),
makerFee : uint256(packed.packedInput2 >> 128),
takerFee : uint256(packed.packedInput2 & 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff),
makerRebate : uint256(packed.packedInput3 >> 128)
});
}
/** @notice Helper function parse an ReserveTrade struct from an TradeInputPacked struct
* @param packed The TradeInputPacked struct to parse
* @return The parsed ReserveTrade struct
*/
function reserveTradeFromInput(TradeInputPacked memory packed) public pure returns (ReserveTrade memory){
if(packed.packedInput3[16] == byte(0x10)){
// maker is order, taker is reserve
return ReserveTrade({
orderAmount : uint256( packed.packedInput1 >> 128),
reserveAmount : uint256( packed.packedInput1 & 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff),
orderFee : uint256( packed.packedInput2 >> 128),
reserveFee : uint256( packed.packedInput2 & 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff),
orderRebate : uint256((packed.packedInput3 & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128),
reserveRebate : 0,
orderIsMaker : true,
gasLimit : uint256((packed.packedInput3 & 0x00000000000000000000000000000000000000000000000000ffffff00000000) >> 32)
});
}else{
// taker is order, maker is reserve
return ReserveTrade({
orderAmount : uint256( packed.packedInput1 & 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff),
reserveAmount : uint256( packed.packedInput1 >> 128),
orderFee : uint256( packed.packedInput2 & 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff),
reserveFee : uint256( packed.packedInput2 >> 128),
orderRebate : 0,
reserveRebate : uint256((packed.packedInput3 & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128),
orderIsMaker : false,
gasLimit : uint256((packed.packedInput3 & 0x00000000000000000000000000000000000000000000000000ffffff00000000) >> 32)
});
}
}
/** @notice Helper function parse an ReserveReserveTrade struct from an TradeInputPacked struct
* @param packed The TradeInputPacked struct to parse
* @return The parsed ReserveReserveTrade struct
*/
function reserveReserveTradeFromInput(TradeInputPacked memory packed) public view returns (ReserveReserveTrade memory){
return ReserveReserveTrade({
makerToken : tokens[uint256((packed.packedInput3 & 0x000000000000000000000000000000000000000000ffff000000000000000000) >> 72)],
takerToken : tokens[uint256((packed.packedInput3 & 0x0000000000000000000000000000000000000000000000ffff00000000000000) >> 56)],
makerAmount : uint256( packed.packedInput1 >> 128),
takerAmount : uint256( packed.packedInput1 & 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff),
makerFee : uint256( packed.packedInput2 >> 128),
takerFee : uint256( packed.packedInput2 & 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff),
gasLimit : uint256((packed.packedInput3 & 0x00000000000000000000000000000000000000000000000000ffffff00000000) >> 32)
});
}
struct RingTrade {
bool isReserve; // 1 if this trade is from a reserve, 0 when from an order
uint256 identifier; // identifier of the reserve or order
address giveToken; // the token this trade gives, the receive token is the givetoken of the previous ring element
uint256 giveAmount; // the amount of giveToken, this ring element is giving for the amount it reeives from the previous element
uint256 fee; // the fee this ring element has to pay on the giveToken giveAmount of the previous ring element
uint256 rebate; // the rebate on giveAmount this element receives
uint256 gasLimit; // the gas limit for the reserve call (if the element is a reserve)
}
struct RingTradeInputPacked{
/*
BITMASK | BYTE RANGE | DESCRIPTION
-------------------------------------------------------------------|------------|----------------------------------
0xffffffffffffffffffffffffffffffff00000000000000000000000000000000 | 0 - 15 | give amount
0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff | 16 - 31 | fee
*/
bytes32 packedInput1;
/*
BITMASK | BYTE RANGE | DESCRIPTION
-------------------------------------------------------------------|------------|----------------------------------
0xffffffffffffffffffffffffffffffff00000000000000000000000000000000 | 0 - 15 | rebate
0x00000000000000000000000000000000ff000000000000000000000000000000 | 16 - 16 | is reserve
0x0000000000000000000000000000000000ffff00000000000000000000000000 | 17 - 18 | identifier
0x00000000000000000000000000000000000000ffff0000000000000000000000 | 19 - 20 | giveToken identifier
0x000000000000000000000000000000000000000000ffffff0000000000000000 | 21 - 23 | gas_limit
0x000000000000000000000000000000000000000000000000ff00000000000000 | 24 - 24 | burn_gas_tokens
*/
bytes32 packedInput2;
}
/** @notice Helper function parse an RingTrade struct from an RingTradeInputPacked struct
* @param packed The RingTradeInputPacked struct to parse
* @return The parsed RingTrade struct
*/
function ringTradeFromInput(RingTradeInputPacked memory packed) view public returns(RingTrade memory){
return RingTrade({
isReserve : (packed.packedInput2[16] == bytes1(0x01)),
identifier : uint256(( packed.packedInput2 & 0x0000000000000000000000000000000000ffff00000000000000000000000000) >> 104),
giveToken : tokens[uint256((packed.packedInput2 & 0x00000000000000000000000000000000000000ffff0000000000000000000000) >> 88)],
giveAmount : uint256( packed.packedInput1 >> 128),
fee : uint256( packed.packedInput1 & 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff),
rebate : uint256( packed.packedInput2 >> 128),
gasLimit : uint256(( packed.packedInput2 & 0x000000000000000000000000000000000000000000ffffff0000000000000000) >> 64)
});
}
} |
// Parse packed input
Order memory order = Order({
sellToken : tokens[uint256(orderInput.packedInput2 >> 240)],
sellAmount : uint256(orderInput.packedInput1 >> 128),
buyToken : tokens[uint256((orderInput.packedInput2 & 0x0000ffff00000000000000000000000000000000000000000000000000000000) >> 224)],
buyAmount : uint256(orderInput.packedInput1 & 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff),
expiry : uint256((orderInput.packedInput2 & 0x00000000ffffffff000000000000000000000000000000000000000000000000) >> 192),
hash : 0x0,
signee : address(0x0)
});
// Restore order hash
if(
orderInput.packedInput2[17] == byte(0x00) // Signing scheme
){ // Order is hashed after signature scheme personal.sign()
order.hash = keccak256(abi.encodePacked( // Restore the hash of this order
"\x19Ethereum Signed Message:\n32",
keccak256(abi.encodePacked(
order.sellToken,
uint128(order.sellAmount),
order.buyToken,
uint128(order.buyAmount),
uint32(order.expiry),
uint64(uint256((orderInput.packedInput2 & 0x0000000000000000ffffffffffffffff00000000000000000000000000000000) >> 128)), // nonce
address(this) // This contract's address
))
));
}else{ // Order is hashed after EIP712
order.hash = keccak256(abi.encodePacked(
"\x19\x01",
EIP712_DOMAIN_SEPARATOR,
keccak256(abi.encode(
EIP712_ORDER_TYPEHASH,
order.sellToken,
order.sellAmount,
order.buyToken,
order.buyAmount,
order.expiry,
uint256((orderInput.packedInput2 & 0x0000000000000000ffffffffffffffff00000000000000000000000000000000) >> 128) // nonce
))
));
}
// Restore the signee of this order
order.signee = ecrecover(
order.hash, // Order hash
uint8(orderInput.packedInput2[16]), // Signature v
orderInput.r, // Signature r
orderInput.s // Signature s
);
// When the signature was delegated restore delegating address
if(
orderInput.packedInput2[18] == byte(0x01) // Is delegated
){
order.signee = delegates[order.signee];
}
return order;
| function orderFromInput(OrderInputPacked memory orderInput) view public returns(Order memory) | /** @notice Helper function parse an Order struct from an OrderInputPacked struct
* @param orderInput The OrderInputPacked struct to parse
* @return The parsed Order struct
*/
function orderFromInput(OrderInputPacked memory orderInput) view public returns(Order memory) |
23289 | FMWorldAccessControl | setCOO | contract FMWorldAccessControl {
address public ceoAddress;
address public cooAddress;
bool public pause = false;
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyC() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress
);
_;
}
modifier notPause() {
require(!pause);
_;
}
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
function setCOO(address _newCOO) external onlyCEO {<FILL_FUNCTION_BODY> }
function setPause(bool _pause) external onlyC {
pause = _pause;
}
} | contract FMWorldAccessControl {
address public ceoAddress;
address public cooAddress;
bool public pause = false;
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyC() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress
);
_;
}
modifier notPause() {
require(!pause);
_;
}
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
<FILL_FUNCTION>
function setPause(bool _pause) external onlyC {
pause = _pause;
}
} |
require(_newCOO != address(0));
cooAddress = _newCOO;
| function setCOO(address _newCOO) external onlyCEO | function setCOO(address _newCOO) external onlyCEO |
35063 | ProxyAdmin | upgradeAndCall | contract ProxyAdmin is Ownable {
/**
* @dev Returns the current implementation of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("implementation()")) == 0x5c60da1b
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Returns the current admin of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("admin()")) == 0xf851a440
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Changes the admin of `proxy` to `newAdmin`.
*
* Requirements:
*
* - This contract must be the current admin of `proxy`.
*/
function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner {
proxy.changeAdmin(newAdmin);
}
/**
* @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner {
proxy.upgradeTo(implementation);
}
/**
* @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See
* {TransparentUpgradeableProxy-upgradeToAndCall}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable virtual onlyOwner {<FILL_FUNCTION_BODY> }
} | contract ProxyAdmin is Ownable {
/**
* @dev Returns the current implementation of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("implementation()")) == 0x5c60da1b
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Returns the current admin of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("admin()")) == 0xf851a440
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Changes the admin of `proxy` to `newAdmin`.
*
* Requirements:
*
* - This contract must be the current admin of `proxy`.
*/
function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner {
proxy.changeAdmin(newAdmin);
}
/**
* @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner {
proxy.upgradeTo(implementation);
}
<FILL_FUNCTION>
} |
proxy.upgradeToAndCall{value: msg.value}(implementation, data);
| function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable virtual onlyOwner | /**
* @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See
* {TransparentUpgradeableProxy-upgradeToAndCall}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable virtual onlyOwner |
64426 | StrategyYFIGovernance | withdraw | contract StrategyYFIGovernance {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address constant public want = address(0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e);
address constant public gov = address(0xBa37B002AbaFDd8E89a1995dA52740bbC013D992);
address constant public curve = address(0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51);
address constant public zap = address(0xbBC81d23Ea2c3ec7e56D39296F0cbB648873a5d3);
address constant public reward = address(0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8);
address constant public usdt = address(0xdAC17F958D2ee523a2206206994597C13D831ec7);
address constant public uni = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address constant public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // used for crv <> weth <> dai route
uint public fee = 500;
uint constant public max = 10000;
address public governance;
address public controller;
address public strategist;
constructor(address _controller) public {
governance = msg.sender;
strategist = msg.sender;
controller = _controller;
}
function setFee(uint _fee) external {
require(msg.sender == governance, "!governance");
fee = _fee;
}
function setStrategist(address _strategist) external {
require(msg.sender == governance, "!governance");
strategist = _strategist;
}
function deposit() public {
IERC20(want).safeApprove(gov, 0);
IERC20(want).safeApprove(gov, IERC20(want).balanceOf(address(this)));
Governance(gov).stake(IERC20(want).balanceOf(address(this)));
}
// Controller only function for creating additional rewards from dust
function withdraw(IERC20 _asset) external returns (uint balance) {<FILL_FUNCTION_BODY> }
// Withdraw partial funds, normally used with a vault withdrawal
function withdraw(uint _amount) external {
require(msg.sender == controller, "!controller");
uint _balance = IERC20(want).balanceOf(address(this));
if (_balance < _amount) {
_amount = _withdrawSome(_amount.sub(_balance));
_amount = _amount.add(_balance);
}
uint _fee = _amount.mul(fee).div(max);
IERC20(want).safeTransfer(Controller(controller).rewards(), _fee);
address _vault = Controller(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want).safeTransfer(_vault, _amount.sub(_fee));
}
// Withdraw all funds, normally used when migrating strategies
function withdrawAll() external returns (uint balance) {
require(msg.sender == controller, "!controller");
_withdrawAll();
balance = IERC20(want).balanceOf(address(this));
address _vault = Controller(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want).safeTransfer(_vault, balance);
}
function _withdrawAll() internal {
Governance(gov).exit();
}
function harvest() public {
require(msg.sender == strategist || msg.sender == governance || msg.sender == tx.origin, "!authorized");
Governance(gov).getReward();
uint _balance = IERC20(reward).balanceOf(address(this));
if (_balance > 0) {
IERC20(reward).safeApprove(zap, 0);
IERC20(reward).safeApprove(zap, _balance);
Zap(zap).remove_liquidity_one_coin(_balance, 2, 0);
}
_balance = IERC20(usdt).balanceOf(address(this));
if (_balance > 0) {
IERC20(usdt).safeApprove(uni, 0);
IERC20(usdt).safeApprove(uni, _balance);
address[] memory path = new address[](3);
path[0] = usdt;
path[1] = weth;
path[2] = want;
Uni(uni).swapExactTokensForTokens(_balance, uint(0), path, address(this), now.add(1800));
}
if (IERC20(want).balanceOf(address(this)) > 0) {
deposit();
}
}
function _withdrawSome(uint256 _amount) internal returns (uint) {
Governance(gov).withdraw(_amount);
return _amount;
}
function balanceOfWant() public view returns (uint) {
return IERC20(want).balanceOf(address(this));
}
function balanceOfYGov() public view returns (uint) {
return Governance(gov).balanceOf(address(this));
}
function balanceOf() public view returns (uint) {
return balanceOfWant()
.add(balanceOfYGov());
}
function voteFor(uint _proposal) external {
require(msg.sender == governance, "!governance");
Governance(gov).voteFor(_proposal);
}
function voteAgainst(uint _proposal) external {
require(msg.sender == governance, "!governance");
Governance(gov).voteAgainst(_proposal);
}
function setGovernance(address _governance) external {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setController(address _controller) external {
require(msg.sender == governance, "!governance");
controller = _controller;
}
} | contract StrategyYFIGovernance {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address constant public want = address(0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e);
address constant public gov = address(0xBa37B002AbaFDd8E89a1995dA52740bbC013D992);
address constant public curve = address(0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51);
address constant public zap = address(0xbBC81d23Ea2c3ec7e56D39296F0cbB648873a5d3);
address constant public reward = address(0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8);
address constant public usdt = address(0xdAC17F958D2ee523a2206206994597C13D831ec7);
address constant public uni = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address constant public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // used for crv <> weth <> dai route
uint public fee = 500;
uint constant public max = 10000;
address public governance;
address public controller;
address public strategist;
constructor(address _controller) public {
governance = msg.sender;
strategist = msg.sender;
controller = _controller;
}
function setFee(uint _fee) external {
require(msg.sender == governance, "!governance");
fee = _fee;
}
function setStrategist(address _strategist) external {
require(msg.sender == governance, "!governance");
strategist = _strategist;
}
function deposit() public {
IERC20(want).safeApprove(gov, 0);
IERC20(want).safeApprove(gov, IERC20(want).balanceOf(address(this)));
Governance(gov).stake(IERC20(want).balanceOf(address(this)));
}
<FILL_FUNCTION>
// Withdraw partial funds, normally used with a vault withdrawal
function withdraw(uint _amount) external {
require(msg.sender == controller, "!controller");
uint _balance = IERC20(want).balanceOf(address(this));
if (_balance < _amount) {
_amount = _withdrawSome(_amount.sub(_balance));
_amount = _amount.add(_balance);
}
uint _fee = _amount.mul(fee).div(max);
IERC20(want).safeTransfer(Controller(controller).rewards(), _fee);
address _vault = Controller(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want).safeTransfer(_vault, _amount.sub(_fee));
}
// Withdraw all funds, normally used when migrating strategies
function withdrawAll() external returns (uint balance) {
require(msg.sender == controller, "!controller");
_withdrawAll();
balance = IERC20(want).balanceOf(address(this));
address _vault = Controller(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want).safeTransfer(_vault, balance);
}
function _withdrawAll() internal {
Governance(gov).exit();
}
function harvest() public {
require(msg.sender == strategist || msg.sender == governance || msg.sender == tx.origin, "!authorized");
Governance(gov).getReward();
uint _balance = IERC20(reward).balanceOf(address(this));
if (_balance > 0) {
IERC20(reward).safeApprove(zap, 0);
IERC20(reward).safeApprove(zap, _balance);
Zap(zap).remove_liquidity_one_coin(_balance, 2, 0);
}
_balance = IERC20(usdt).balanceOf(address(this));
if (_balance > 0) {
IERC20(usdt).safeApprove(uni, 0);
IERC20(usdt).safeApprove(uni, _balance);
address[] memory path = new address[](3);
path[0] = usdt;
path[1] = weth;
path[2] = want;
Uni(uni).swapExactTokensForTokens(_balance, uint(0), path, address(this), now.add(1800));
}
if (IERC20(want).balanceOf(address(this)) > 0) {
deposit();
}
}
function _withdrawSome(uint256 _amount) internal returns (uint) {
Governance(gov).withdraw(_amount);
return _amount;
}
function balanceOfWant() public view returns (uint) {
return IERC20(want).balanceOf(address(this));
}
function balanceOfYGov() public view returns (uint) {
return Governance(gov).balanceOf(address(this));
}
function balanceOf() public view returns (uint) {
return balanceOfWant()
.add(balanceOfYGov());
}
function voteFor(uint _proposal) external {
require(msg.sender == governance, "!governance");
Governance(gov).voteFor(_proposal);
}
function voteAgainst(uint _proposal) external {
require(msg.sender == governance, "!governance");
Governance(gov).voteAgainst(_proposal);
}
function setGovernance(address _governance) external {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setController(address _controller) external {
require(msg.sender == governance, "!governance");
controller = _controller;
}
} |
require(msg.sender == controller, "!controller");
require(want != address(_asset), "want");
balance = _asset.balanceOf(address(this));
_asset.safeTransfer(controller, balance);
| function withdraw(IERC20 _asset) external returns (uint balance) | // Controller only function for creating additional rewards from dust
function withdraw(IERC20 _asset) external returns (uint balance) |
84591 | ERC721 | _burn | contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
string private _name;
string private _symbol;
mapping(uint256 => address) private _owners;
mapping(address => uint256) private _balances;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
string public _baseURI;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory base = baseURI();
return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString(), ".json")) : "";
}
function baseURI() internal view virtual returns (string memory) {
return _baseURI;
}
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
function _burn(uint256 tokenId) internal virtual {<FILL_FUNCTION_BODY> }
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
string private _name;
string private _symbol;
mapping(uint256 => address) private _owners;
mapping(address => uint256) private _balances;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
string public _baseURI;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory base = baseURI();
return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString(), ".json")) : "";
}
function baseURI() internal view virtual returns (string memory) {
return _baseURI;
}
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
<FILL_FUNCTION>
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} |
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
| function _burn(uint256 tokenId) internal virtual | function _burn(uint256 tokenId) internal virtual |
34574 | Owned | acceptOwnership | contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = 0x4Ef7813018e60373f3f79f5c6b404c26B9E9FF51;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {<FILL_FUNCTION_BODY> }
} | contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = 0x4Ef7813018e60373f3f79f5c6b404c26B9E9FF51;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
<FILL_FUNCTION>
} |
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
| function acceptOwnership() public | function acceptOwnership() public |
8480 | ERC20Token | approve | contract ERC20Token {
using SafeMath for uint;
// ------------------------------------------------------------------------
// Total Supply
// ------------------------------------------------------------------------
uint256 _totalSupply = 0;
// ------------------------------------------------------------------------
// Balances for each account
// ------------------------------------------------------------------------
mapping(address => uint256) balances;
// ------------------------------------------------------------------------
// Owner of account approves the transfer of an amount to another account
// ------------------------------------------------------------------------
mapping(address => mapping (address => uint256)) allowed;
// ------------------------------------------------------------------------
// Get the total token supply
// ------------------------------------------------------------------------
function totalSupply() constant returns (uint256 totalSupply) {
totalSupply = _totalSupply;
}
// ------------------------------------------------------------------------
// Get the account balance of another account with address _owner
// ------------------------------------------------------------------------
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
// ------------------------------------------------------------------------
// Transfer the balance from owner's account to another account
// ------------------------------------------------------------------------
function transfer(address _to, uint256 _amount) returns (bool success) {
if (balances[msg.sender] >= _amount // User has balance
&& _amount > 0 // Non-zero transfer
&& balances[_to] + _amount > balances[_to] // Overflow check
) {
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
// ------------------------------------------------------------------------
// Allow _spender to withdraw from your account, multiple times, up to the
// _value amount. If this function is called again it overwrites the
// current allowance with _value.
// ------------------------------------------------------------------------
function approve(
address _spender,
uint256 _amount
) returns (bool success) {<FILL_FUNCTION_BODY> }
// ------------------------------------------------------------------------
// Spender of tokens transfer an amount of tokens from the token owner's
// balance to the spender's account. The owner of the tokens must already
// have approve(...)-d this transfer
// ------------------------------------------------------------------------
function transferFrom(
address _from,
address _to,
uint256 _amount
) returns (bool success) {
if (balances[_from] >= _amount // From a/c has balance
&& allowed[_from][msg.sender] >= _amount // Transfer approved
&& _amount > 0 // Non-zero transfer
&& balances[_to] + _amount > balances[_to] // Overflow check
) {
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(
address _owner,
address _spender
) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender,
uint256 _value);
} | contract ERC20Token {
using SafeMath for uint;
// ------------------------------------------------------------------------
// Total Supply
// ------------------------------------------------------------------------
uint256 _totalSupply = 0;
// ------------------------------------------------------------------------
// Balances for each account
// ------------------------------------------------------------------------
mapping(address => uint256) balances;
// ------------------------------------------------------------------------
// Owner of account approves the transfer of an amount to another account
// ------------------------------------------------------------------------
mapping(address => mapping (address => uint256)) allowed;
// ------------------------------------------------------------------------
// Get the total token supply
// ------------------------------------------------------------------------
function totalSupply() constant returns (uint256 totalSupply) {
totalSupply = _totalSupply;
}
// ------------------------------------------------------------------------
// Get the account balance of another account with address _owner
// ------------------------------------------------------------------------
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
// ------------------------------------------------------------------------
// Transfer the balance from owner's account to another account
// ------------------------------------------------------------------------
function transfer(address _to, uint256 _amount) returns (bool success) {
if (balances[msg.sender] >= _amount // User has balance
&& _amount > 0 // Non-zero transfer
&& balances[_to] + _amount > balances[_to] // Overflow check
) {
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
<FILL_FUNCTION>
// ------------------------------------------------------------------------
// Spender of tokens transfer an amount of tokens from the token owner's
// balance to the spender's account. The owner of the tokens must already
// have approve(...)-d this transfer
// ------------------------------------------------------------------------
function transferFrom(
address _from,
address _to,
uint256 _amount
) returns (bool success) {
if (balances[_from] >= _amount // From a/c has balance
&& allowed[_from][msg.sender] >= _amount // Transfer approved
&& _amount > 0 // Non-zero transfer
&& balances[_to] + _amount > balances[_to] // Overflow check
) {
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(
address _owner,
address _spender
) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender,
uint256 _value);
} |
// Borrowed from the MiniMeToken contract
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
| function approve(
address _spender,
uint256 _amount
) returns (bool success) | // ------------------------------------------------------------------------
// Allow _spender to withdraw from your account, multiple times, up to the
// _value amount. If this function is called again it overwrites the
// current allowance with _value.
// ------------------------------------------------------------------------
function approve(
address _spender,
uint256 _amount
) returns (bool success) |
24779 | FUTR | transfer | contract FUTR {
uint256 constant MAX_UINT256 = 2**256 - 1;
uint256 MAX_SUBMITTED = 500067157619455000000000;
// (no premine)
uint256 _totalSupply = 0;
// The following 2 variables are essentially a lookup table.
// They are not constant because they are memory.
// I came up with this because calculating it was expensive,
// especially so when crossing tiers.
// Sum of each tier by ether submitted.
uint256[] levels = [
8771929824561400000000,
19895525330179400000000,
37350070784724800000000,
64114776667077800000000,
98400490952792100000000,
148400490952792000000000,
218400490952792000000000,
308400490952792000000000,
415067157619459000000000,
500067157619455000000000
];
// Token amounts for each tier.
uint256[] ratios = [
114,
89,
55,
34,
21,
13,
8,
5,
3,
2 ];
// total ether submitted before fees.
uint256 _submitted = 0;
uint256 public tier = 0;
// ERC20 events.
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
// FUTR events.
event Mined(address indexed _miner, uint _value);
event WaitStarted(uint256 endTime);
event SwapStarted(uint256 endTime);
event MiningStart(uint256 end_time, uint256 swap_time, uint256 swap_end_time);
event MiningExtended(uint256 end_time, uint256 swap_time, uint256 swap_end_time);
// Optional ERC20 values.
string public name = "Futereum Token";
uint8 public decimals = 18;
string public symbol = "FUTR";
// Public variables so the curious can check the state.
bool public swap = false;
bool public wait = false;
bool public extended = false;
// Public end time for the current state.
uint256 public endTime;
// These are calculated at mining start.
uint256 swapTime;
uint256 swapEndTime;
uint256 endTimeExtended;
uint256 swapTimeExtended;
uint256 swapEndTimeExtended;
// Pay rate calculated from balance later.
uint256 public payRate = 0;
// Fee variables. Fees are reserved and then withdrawn later.
uint256 submittedFeesPaid = 0;
uint256 penalty = 0;
uint256 reservedFees = 0;
// Storage.
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
// Fallback function mines the tokens.
// Send from a wallet you control.
// DON'T send from an exchange wallet!
// We recommend sending using a method that calculates gas for you.
// Here are some estimates (not guaranteed to be accurate):
// It usually costs around 90k gas. It cost more if you cross a tier.
// Maximum around 190k gas.
function () external payable {
require(msg.sender != address(0) &&
tier != 10 &&
swap == false &&
wait == false);
uint256 issued = mint(msg.sender, msg.value);
Mined(msg.sender, issued);
Transfer(this, msg.sender, issued);
}
// Constructor.
function FUTR() public {
_start();
}
// This gets called by constructor AND after the swap to restart evertying.
function _start() internal
{
swap = false;
wait = false;
extended = false;
endTime = now + 366 days;
swapTime = endTime + 30 days;
swapEndTime = swapTime + 5 days;
endTimeExtended = now + 1096 days;
swapTimeExtended = endTimeExtended + 30 days;
swapEndTimeExtended = swapTimeExtended + 5 days;
submittedFeesPaid = 0;
_submitted = 0;
reservedFees = 0;
payRate = 0;
tier = 0;
MiningStart(endTime, swapTime, swapEndTime);
}
// Restarts everything after swap.
// This is expensive, so we make someone call it and pay for the gas.
// Any holders that miss the swap get to keep their tokens.
// Ether stays in contract, minus 20% penalty fee.
function restart() public {
require(swap && now >= endTime);
penalty = this.balance * 2000 / 10000;
payFees();
_start();
}
// ERC20 standard supply function.
function totalSupply() public constant returns (uint)
{
return _totalSupply;
}
// Mints new tokens when they are mined.
function mint(address _to, uint256 _value) internal returns (uint256)
{
uint256 total = _submitted + _value;
if (total > MAX_SUBMITTED)
{
uint256 refund = total - MAX_SUBMITTED - 1;
_value = _value - refund;
// refund money and continue.
_to.transfer(refund);
}
_submitted += _value;
total -= refund;
uint256 tokens = calculateTokens(total, _value);
balances[_to] += tokens;
_totalSupply += tokens;
return tokens;
}
// Calculates the tokens mined based on the tier.
function calculateTokens(uint256 total, uint256 _value) internal returns (uint256)
{
if (tier == 10)
{
// This just rounds it off to an even number.
return 7400000000;
}
uint256 tokens = 0;
if (total > levels[tier])
{
uint256 remaining = total - levels[tier];
_value -= remaining;
tokens = (_value) * ratios[tier];
tier += 1;
tokens += calculateTokens(total, remaining);
}
else
{
tokens = _value * ratios[tier];
}
return tokens;
}
// This is basically so you don't have to add 1 to the last completed tier.
// You're welcome.
function currentTier() public view returns (uint256) {
if (tier == 10)
{
return 10;
}
else
{
return tier + 1;
}
}
// Ether remaining for tier.
function leftInTier() public view returns (uint256) {
if (tier == 10) {
return 0;
}
else
{
return levels[tier] - _submitted;
}
}
// Total sumbitted for mining.
function submitted() public view returns (uint256) {
return _submitted;
}
// Balance minus oustanding fees.
function balanceMinusFeesOutstanding() public view returns (uint256) {
return this.balance - (penalty + (_submitted - submittedFeesPaid) * 1530 / 10000); // fees are 15.3 % total.
}
// Calculates the amount of ether per token from the balance.
// This is calculated once by the first account to swap.
function calulateRate() internal {
reservedFees = penalty + (_submitted - submittedFeesPaid) * 1530 / 10000; // fees are 15.3 % total.
uint256 tokens = _totalSupply / 1 ether;
payRate = (this.balance - reservedFees);
payRate = payRate / tokens;
}
// This function is called on token transfer and fee payment.
// It checks the next deadline and then updates the deadline and state.
//
// It uses the block time, but the time periods are days and months,
// so it should be pretty safe ¯\_(ツ)_/¯
function _updateState() internal {
// Most of the time, this will just be skipped.
if (now >= endTime)
{
// We are not currently swapping or waiting to swap
if(!swap && !wait)
{
if (extended)
{
// It's been 36 months.
wait = true;
endTime = swapTimeExtended;
WaitStarted(endTime);
}
else if (tier == 10)
{
// Tiers filled
wait = true;
endTime = swapTime;
WaitStarted(endTime);
}
else
{
// Extended to 36 months
endTime = endTimeExtended;
extended = true;
MiningExtended(endTime, swapTime, swapEndTime);
}
}
else if (wait)
{
// It's time to swap.
swap = true;
wait = false;
if (extended)
{
endTime = swapEndTimeExtended;
}
else
{
endTime = swapEndTime;
}
SwapStarted(endTime);
}
}
}
// Standard ERC20 transfer plus state check and token swap logic.
//
// We recommend sending using a method that calculates gas for you.
//
// Here are some estimates (not guaranteed to be accurate):
// It usually costs around 37k gas. It cost more if the state changes.
// State change means around 55k - 65k gas.
// Swapping tokens for ether costs around 46k gas. (around 93k for the first account to swap)
function transfer(address _to, uint256 _value) public returns (bool success) {<FILL_FUNCTION_BODY> }
// Standard ERC20.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
Transfer(_from, _to, _value);
return true;
}
// Standard ERC20.
function balanceOf(address _owner) view public returns (uint256 balance) {
return balances[_owner];
}
// Standard ERC20.
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) view public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
// ********************
// Fee stuff.
// Addresses for fees.
address public foundation = 0x950ec4ef693d90f8519c4213821e462426d30905;
address public owner = 0x78BFCA5E20B0D710EbEF98249f68d9320eE423be;
address public dev = 0x5d2b9f5345e69e2390ce4c26ccc9c2910a097520;
// Pays fees to the foundation, the owner, and the dev.
// It also updates the state. Anyone can call this.
function payFees() public {
// Check state to see if swap needs to happen.
_updateState();
uint256 fees = penalty + (_submitted - submittedFeesPaid) * 1530 / 10000; // fees are 15.3 % total.
submittedFeesPaid = _submitted;
reservedFees = 0;
penalty = 0;
if (fees > 0)
{
foundation.transfer(fees / 2);
owner.transfer(fees / 4);
dev.transfer(fees / 4);
}
}
function changeFoundation (address _receiver) public
{
require(msg.sender == foundation);
foundation = _receiver;
}
function changeOwner (address _receiver) public
{
require(msg.sender == owner);
owner = _receiver;
}
function changeDev (address _receiver) public
{
require(msg.sender == dev);
dev = _receiver;
}
} | contract FUTR {
uint256 constant MAX_UINT256 = 2**256 - 1;
uint256 MAX_SUBMITTED = 500067157619455000000000;
// (no premine)
uint256 _totalSupply = 0;
// The following 2 variables are essentially a lookup table.
// They are not constant because they are memory.
// I came up with this because calculating it was expensive,
// especially so when crossing tiers.
// Sum of each tier by ether submitted.
uint256[] levels = [
8771929824561400000000,
19895525330179400000000,
37350070784724800000000,
64114776667077800000000,
98400490952792100000000,
148400490952792000000000,
218400490952792000000000,
308400490952792000000000,
415067157619459000000000,
500067157619455000000000
];
// Token amounts for each tier.
uint256[] ratios = [
114,
89,
55,
34,
21,
13,
8,
5,
3,
2 ];
// total ether submitted before fees.
uint256 _submitted = 0;
uint256 public tier = 0;
// ERC20 events.
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
// FUTR events.
event Mined(address indexed _miner, uint _value);
event WaitStarted(uint256 endTime);
event SwapStarted(uint256 endTime);
event MiningStart(uint256 end_time, uint256 swap_time, uint256 swap_end_time);
event MiningExtended(uint256 end_time, uint256 swap_time, uint256 swap_end_time);
// Optional ERC20 values.
string public name = "Futereum Token";
uint8 public decimals = 18;
string public symbol = "FUTR";
// Public variables so the curious can check the state.
bool public swap = false;
bool public wait = false;
bool public extended = false;
// Public end time for the current state.
uint256 public endTime;
// These are calculated at mining start.
uint256 swapTime;
uint256 swapEndTime;
uint256 endTimeExtended;
uint256 swapTimeExtended;
uint256 swapEndTimeExtended;
// Pay rate calculated from balance later.
uint256 public payRate = 0;
// Fee variables. Fees are reserved and then withdrawn later.
uint256 submittedFeesPaid = 0;
uint256 penalty = 0;
uint256 reservedFees = 0;
// Storage.
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
// Fallback function mines the tokens.
// Send from a wallet you control.
// DON'T send from an exchange wallet!
// We recommend sending using a method that calculates gas for you.
// Here are some estimates (not guaranteed to be accurate):
// It usually costs around 90k gas. It cost more if you cross a tier.
// Maximum around 190k gas.
function () external payable {
require(msg.sender != address(0) &&
tier != 10 &&
swap == false &&
wait == false);
uint256 issued = mint(msg.sender, msg.value);
Mined(msg.sender, issued);
Transfer(this, msg.sender, issued);
}
// Constructor.
function FUTR() public {
_start();
}
// This gets called by constructor AND after the swap to restart evertying.
function _start() internal
{
swap = false;
wait = false;
extended = false;
endTime = now + 366 days;
swapTime = endTime + 30 days;
swapEndTime = swapTime + 5 days;
endTimeExtended = now + 1096 days;
swapTimeExtended = endTimeExtended + 30 days;
swapEndTimeExtended = swapTimeExtended + 5 days;
submittedFeesPaid = 0;
_submitted = 0;
reservedFees = 0;
payRate = 0;
tier = 0;
MiningStart(endTime, swapTime, swapEndTime);
}
// Restarts everything after swap.
// This is expensive, so we make someone call it and pay for the gas.
// Any holders that miss the swap get to keep their tokens.
// Ether stays in contract, minus 20% penalty fee.
function restart() public {
require(swap && now >= endTime);
penalty = this.balance * 2000 / 10000;
payFees();
_start();
}
// ERC20 standard supply function.
function totalSupply() public constant returns (uint)
{
return _totalSupply;
}
// Mints new tokens when they are mined.
function mint(address _to, uint256 _value) internal returns (uint256)
{
uint256 total = _submitted + _value;
if (total > MAX_SUBMITTED)
{
uint256 refund = total - MAX_SUBMITTED - 1;
_value = _value - refund;
// refund money and continue.
_to.transfer(refund);
}
_submitted += _value;
total -= refund;
uint256 tokens = calculateTokens(total, _value);
balances[_to] += tokens;
_totalSupply += tokens;
return tokens;
}
// Calculates the tokens mined based on the tier.
function calculateTokens(uint256 total, uint256 _value) internal returns (uint256)
{
if (tier == 10)
{
// This just rounds it off to an even number.
return 7400000000;
}
uint256 tokens = 0;
if (total > levels[tier])
{
uint256 remaining = total - levels[tier];
_value -= remaining;
tokens = (_value) * ratios[tier];
tier += 1;
tokens += calculateTokens(total, remaining);
}
else
{
tokens = _value * ratios[tier];
}
return tokens;
}
// This is basically so you don't have to add 1 to the last completed tier.
// You're welcome.
function currentTier() public view returns (uint256) {
if (tier == 10)
{
return 10;
}
else
{
return tier + 1;
}
}
// Ether remaining for tier.
function leftInTier() public view returns (uint256) {
if (tier == 10) {
return 0;
}
else
{
return levels[tier] - _submitted;
}
}
// Total sumbitted for mining.
function submitted() public view returns (uint256) {
return _submitted;
}
// Balance minus oustanding fees.
function balanceMinusFeesOutstanding() public view returns (uint256) {
return this.balance - (penalty + (_submitted - submittedFeesPaid) * 1530 / 10000); // fees are 15.3 % total.
}
// Calculates the amount of ether per token from the balance.
// This is calculated once by the first account to swap.
function calulateRate() internal {
reservedFees = penalty + (_submitted - submittedFeesPaid) * 1530 / 10000; // fees are 15.3 % total.
uint256 tokens = _totalSupply / 1 ether;
payRate = (this.balance - reservedFees);
payRate = payRate / tokens;
}
// This function is called on token transfer and fee payment.
// It checks the next deadline and then updates the deadline and state.
//
// It uses the block time, but the time periods are days and months,
// so it should be pretty safe ¯\_(ツ)_/¯
function _updateState() internal {
// Most of the time, this will just be skipped.
if (now >= endTime)
{
// We are not currently swapping or waiting to swap
if(!swap && !wait)
{
if (extended)
{
// It's been 36 months.
wait = true;
endTime = swapTimeExtended;
WaitStarted(endTime);
}
else if (tier == 10)
{
// Tiers filled
wait = true;
endTime = swapTime;
WaitStarted(endTime);
}
else
{
// Extended to 36 months
endTime = endTimeExtended;
extended = true;
MiningExtended(endTime, swapTime, swapEndTime);
}
}
else if (wait)
{
// It's time to swap.
swap = true;
wait = false;
if (extended)
{
endTime = swapEndTimeExtended;
}
else
{
endTime = swapEndTime;
}
SwapStarted(endTime);
}
}
}
<FILL_FUNCTION>
// Standard ERC20.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
Transfer(_from, _to, _value);
return true;
}
// Standard ERC20.
function balanceOf(address _owner) view public returns (uint256 balance) {
return balances[_owner];
}
// Standard ERC20.
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) view public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
// ********************
// Fee stuff.
// Addresses for fees.
address public foundation = 0x950ec4ef693d90f8519c4213821e462426d30905;
address public owner = 0x78BFCA5E20B0D710EbEF98249f68d9320eE423be;
address public dev = 0x5d2b9f5345e69e2390ce4c26ccc9c2910a097520;
// Pays fees to the foundation, the owner, and the dev.
// It also updates the state. Anyone can call this.
function payFees() public {
// Check state to see if swap needs to happen.
_updateState();
uint256 fees = penalty + (_submitted - submittedFeesPaid) * 1530 / 10000; // fees are 15.3 % total.
submittedFeesPaid = _submitted;
reservedFees = 0;
penalty = 0;
if (fees > 0)
{
foundation.transfer(fees / 2);
owner.transfer(fees / 4);
dev.transfer(fees / 4);
}
}
function changeFoundation (address _receiver) public
{
require(msg.sender == foundation);
foundation = _receiver;
}
function changeOwner (address _receiver) public
{
require(msg.sender == owner);
owner = _receiver;
}
function changeDev (address _receiver) public
{
require(msg.sender == dev);
dev = _receiver;
}
} |
require(balances[msg.sender] >= _value);
// Normal transfers check if time is expired.
_updateState();
// Check if sending in for swap.
if (_to == address(this))
{
// throw if they can't swap yet.
require(swap);
if (payRate == 0)
{
calulateRate(); // Gas to calc the rate paid by first unlucky soul.
}
uint256 amount = _value * payRate;
// Adjust for decimals
amount /= 1 ether;
// Burn tokens.
balances[msg.sender] -= _value;
_totalSupply -= _value;
Transfer(msg.sender, _to, _value);
//send ether
msg.sender.transfer(amount);
} else
{
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
}
return true;
| function transfer(address _to, uint256 _value) public returns (bool success) | // Standard ERC20 transfer plus state check and token swap logic.
//
// We recommend sending using a method that calculates gas for you.
//
// Here are some estimates (not guaranteed to be accurate):
// It usually costs around 37k gas. It cost more if the state changes.
// State change means around 55k - 65k gas.
// Swapping tokens for ether costs around 46k gas. (around 93k for the first account to swap)
function transfer(address _to, uint256 _value) public returns (bool success) |
90476 | FVCBaseToken | _burn | contract FVCBaseToken is ERC20 {
using SafeMath for uint256;
uint256 internal _totalSupply;
mapping(address => uint256) internal _balances;
mapping(address => mapping (address => uint256)) internal _allowed;
modifier validDestination( address _to )
{
require(_to != address(0x0), "Invalid address.");
require(_to != address(this), "Invalid address.");
_;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address _who) public view returns (uint256) {
return _balances[_who];
}
function transfer(address _to, uint256 _value)
public
validDestination(_to)
returns (bool)
{
_balances[msg.sender] = _balances[msg.sender].sub(_value);
_balances[_to] = _balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value)
public
validDestination(_to)
returns (bool)
{
require(_value <= _allowed[_from][msg.sender],"Insufficient allowance.");
_balances[_from] = _balances[_from].sub(_value);
_balances[_to] = _balances[_to].add(_value);
_allowed[_from][msg.sender] = _allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public validDestination(_spender) returns (bool) {
_allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256)
{
return _allowed[_owner][_spender];
}
function _mint(uint256 _value) internal returns (bool)
{
_balances[msg.sender] = _balances[msg.sender].add(_value);
_totalSupply = _totalSupply.add(_value);
emit Transfer(address(0x0), msg.sender, _value);
return true;
}
function _burn(uint _value) internal returns (bool)
{<FILL_FUNCTION_BODY> }
function _burnFrom(address _from, uint256 _value) internal validDestination(_from) returns (bool)
{
require(_value <= _allowed[_from][msg.sender],"Insufficient allowance.");
_balances[_from] = _balances[_from].sub(_value);
_totalSupply = _totalSupply.sub(_value);
_allowed[_from][msg.sender] = _allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, address(0x0), _value);
return true;
}
} | contract FVCBaseToken is ERC20 {
using SafeMath for uint256;
uint256 internal _totalSupply;
mapping(address => uint256) internal _balances;
mapping(address => mapping (address => uint256)) internal _allowed;
modifier validDestination( address _to )
{
require(_to != address(0x0), "Invalid address.");
require(_to != address(this), "Invalid address.");
_;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address _who) public view returns (uint256) {
return _balances[_who];
}
function transfer(address _to, uint256 _value)
public
validDestination(_to)
returns (bool)
{
_balances[msg.sender] = _balances[msg.sender].sub(_value);
_balances[_to] = _balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value)
public
validDestination(_to)
returns (bool)
{
require(_value <= _allowed[_from][msg.sender],"Insufficient allowance.");
_balances[_from] = _balances[_from].sub(_value);
_balances[_to] = _balances[_to].add(_value);
_allowed[_from][msg.sender] = _allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public validDestination(_spender) returns (bool) {
_allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256)
{
return _allowed[_owner][_spender];
}
function _mint(uint256 _value) internal returns (bool)
{
_balances[msg.sender] = _balances[msg.sender].add(_value);
_totalSupply = _totalSupply.add(_value);
emit Transfer(address(0x0), msg.sender, _value);
return true;
}
<FILL_FUNCTION>
function _burnFrom(address _from, uint256 _value) internal validDestination(_from) returns (bool)
{
require(_value <= _allowed[_from][msg.sender],"Insufficient allowance.");
_balances[_from] = _balances[_from].sub(_value);
_totalSupply = _totalSupply.sub(_value);
_allowed[_from][msg.sender] = _allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, address(0x0), _value);
return true;
}
} |
_balances[msg.sender] = _balances[msg.sender].sub(_value);
_totalSupply = _totalSupply.sub(_value);
emit Transfer(msg.sender, address(0x0), _value);
return true;
| function _burn(uint _value) internal returns (bool)
| function _burn(uint _value) internal returns (bool)
|
37626 | TransferFee | setMinTransferFee | contract TransferFee is Ownable, ITST {
address private _feeAccount;
uint256 private _maxTransferFee;
uint256 private _minTransferFee;
uint256 private _transferFeePercentage;
/**
* @dev Constructor, _feeAccount that collects tranfer fee, fee percentange, maximum, minimum amount of wei for trasfer fee.
* @param feeAccount account that collects fee.
* @param minTransferFee Min amount of wei to be charged on trasfer.
* @param minTransferFee Min amount of wei to be charged on trasfer.
* @param transferFeePercentage Percent amount of wei to be charged on trasfer.
*/
constructor (address feeAccount, uint256 maxTransferFee, uint256 minTransferFee, uint256 transferFeePercentage) public {
require(feeAccount != address(0x0), "TransferFee: feeAccount is 0");
require(minTransferFee > 0, "TransferFee: minTransferFee is 0");
require(maxTransferFee > 0, "TransferFee: maxTransferFee is 0");
require(transferFeePercentage > 0, "TransferFee: transferFeePercentage is 0");
// this also handles "minTransferFee should be less than maxTransferFee"
// solhint-disable-next-line max-line-length
require(maxTransferFee > minTransferFee, "TransferFee: maxTransferFee should be greater than minTransferFee");
_feeAccount = feeAccount;
_maxTransferFee = maxTransferFee;
_minTransferFee = minTransferFee;
_transferFeePercentage = transferFeePercentage;
}
/**
* See {ITrasnferFee-setFeeAccount}.
*
* @dev sets `feeAccount` to `_feeAccount` by the caller.
*
* Requirements:
*
* - `feeAccount` cannot be the zero.
*/
function setFeeAccount(address feeAccount) external onlyOwner returns (bool) {
require(feeAccount != address(0x0), "TransferFee: feeAccount is 0");
emit FeeAccountUpdated(_feeAccount, feeAccount);
_feeAccount = feeAccount;
return true;
}
/**
* See {ITrasnferFee-setMaxTransferFee}.
*
* @dev sets `maxTransferFee` to `_maxTransferFee` by the caller.
*
* Requirements:
*
* - `maxTransferFee` cannot be the zero.
* - `maxTransferFee` should be greater than minTransferFee.
*/
function setMaxTransferFee(uint256 maxTransferFee) external onlyOwner returns (bool) {
require(maxTransferFee > 0, "TransferFee: maxTransferFee is 0");
// solhint-disable-next-line max-line-length
require(maxTransferFee > _minTransferFee, "TransferFee: maxTransferFee should be greater than minTransferFee");
emit MaxTransferFeeUpdated(_maxTransferFee, maxTransferFee);
_maxTransferFee = maxTransferFee;
return true;
}
/**
* See {ITrasnferFee-setMinTransferFee}.
*
* @dev sets `minTransferFee` to `_minTransferFee` by the caller.
*
* Requirements:
*
* - `minTransferFee` cannot be the zero.
* - `minTransferFee` should be less than maxTransferFee.
*/
function setMinTransferFee(uint256 minTransferFee) external onlyOwner returns (bool) {<FILL_FUNCTION_BODY> }
/**
* See {ITrasnferFee-setTransferFeePercentage}.
*
* @dev sets `transferFeePercentage` to `_transferFeePercentage` by the caller.
*
* Requirements:
*
* - `transferFeePercentage` cannot be the zero.
* - `transferFeePercentage` should be less than maxTransferFee.
*/
function setTransferFeePercentage(uint256 transferFeePercentage) external onlyOwner returns (bool) {
require(transferFeePercentage > 0, "TransferFee: transferFeePercentage is 0");
emit TransferFeePercentageUpdated(_transferFeePercentage, transferFeePercentage);
_transferFeePercentage = transferFeePercentage;
return true;
}
/**
* @dev See {ITrasnferFee-feeAccount}.
*/
function feeAccount() public view returns (address) {
return _feeAccount;
}
/**
* See {ITrasnferFee-maxTransferFee}.
*/
function maxTransferFee() public view returns (uint256) {
return _maxTransferFee;
}
/**
* See {ITrasnferFee-minTransferFee}.
*/
function minTransferFee() public view returns (uint256) {
return _minTransferFee;
}
/**
* See {ITrasnferFee-transferFeePercentage}.
*/
function transferFeePercentage() public view returns (uint256) {
return _transferFeePercentage;
}
} | contract TransferFee is Ownable, ITST {
address private _feeAccount;
uint256 private _maxTransferFee;
uint256 private _minTransferFee;
uint256 private _transferFeePercentage;
/**
* @dev Constructor, _feeAccount that collects tranfer fee, fee percentange, maximum, minimum amount of wei for trasfer fee.
* @param feeAccount account that collects fee.
* @param minTransferFee Min amount of wei to be charged on trasfer.
* @param minTransferFee Min amount of wei to be charged on trasfer.
* @param transferFeePercentage Percent amount of wei to be charged on trasfer.
*/
constructor (address feeAccount, uint256 maxTransferFee, uint256 minTransferFee, uint256 transferFeePercentage) public {
require(feeAccount != address(0x0), "TransferFee: feeAccount is 0");
require(minTransferFee > 0, "TransferFee: minTransferFee is 0");
require(maxTransferFee > 0, "TransferFee: maxTransferFee is 0");
require(transferFeePercentage > 0, "TransferFee: transferFeePercentage is 0");
// this also handles "minTransferFee should be less than maxTransferFee"
// solhint-disable-next-line max-line-length
require(maxTransferFee > minTransferFee, "TransferFee: maxTransferFee should be greater than minTransferFee");
_feeAccount = feeAccount;
_maxTransferFee = maxTransferFee;
_minTransferFee = minTransferFee;
_transferFeePercentage = transferFeePercentage;
}
/**
* See {ITrasnferFee-setFeeAccount}.
*
* @dev sets `feeAccount` to `_feeAccount` by the caller.
*
* Requirements:
*
* - `feeAccount` cannot be the zero.
*/
function setFeeAccount(address feeAccount) external onlyOwner returns (bool) {
require(feeAccount != address(0x0), "TransferFee: feeAccount is 0");
emit FeeAccountUpdated(_feeAccount, feeAccount);
_feeAccount = feeAccount;
return true;
}
/**
* See {ITrasnferFee-setMaxTransferFee}.
*
* @dev sets `maxTransferFee` to `_maxTransferFee` by the caller.
*
* Requirements:
*
* - `maxTransferFee` cannot be the zero.
* - `maxTransferFee` should be greater than minTransferFee.
*/
function setMaxTransferFee(uint256 maxTransferFee) external onlyOwner returns (bool) {
require(maxTransferFee > 0, "TransferFee: maxTransferFee is 0");
// solhint-disable-next-line max-line-length
require(maxTransferFee > _minTransferFee, "TransferFee: maxTransferFee should be greater than minTransferFee");
emit MaxTransferFeeUpdated(_maxTransferFee, maxTransferFee);
_maxTransferFee = maxTransferFee;
return true;
}
<FILL_FUNCTION>
/**
* See {ITrasnferFee-setTransferFeePercentage}.
*
* @dev sets `transferFeePercentage` to `_transferFeePercentage` by the caller.
*
* Requirements:
*
* - `transferFeePercentage` cannot be the zero.
* - `transferFeePercentage` should be less than maxTransferFee.
*/
function setTransferFeePercentage(uint256 transferFeePercentage) external onlyOwner returns (bool) {
require(transferFeePercentage > 0, "TransferFee: transferFeePercentage is 0");
emit TransferFeePercentageUpdated(_transferFeePercentage, transferFeePercentage);
_transferFeePercentage = transferFeePercentage;
return true;
}
/**
* @dev See {ITrasnferFee-feeAccount}.
*/
function feeAccount() public view returns (address) {
return _feeAccount;
}
/**
* See {ITrasnferFee-maxTransferFee}.
*/
function maxTransferFee() public view returns (uint256) {
return _maxTransferFee;
}
/**
* See {ITrasnferFee-minTransferFee}.
*/
function minTransferFee() public view returns (uint256) {
return _minTransferFee;
}
/**
* See {ITrasnferFee-transferFeePercentage}.
*/
function transferFeePercentage() public view returns (uint256) {
return _transferFeePercentage;
}
} |
require(minTransferFee > 0, "TransferFee: minTransferFee is 0");
// solhint-disable-next-line max-line-length
require(minTransferFee < _maxTransferFee, "TransferFee: minTransferFee should be less than maxTransferFee");
emit MaxTransferFeeUpdated(_minTransferFee, minTransferFee);
_minTransferFee = minTransferFee;
return true;
| function setMinTransferFee(uint256 minTransferFee) external onlyOwner returns (bool) | /**
* See {ITrasnferFee-setMinTransferFee}.
*
* @dev sets `minTransferFee` to `_minTransferFee` by the caller.
*
* Requirements:
*
* - `minTransferFee` cannot be the zero.
* - `minTransferFee` should be less than maxTransferFee.
*/
function setMinTransferFee(uint256 minTransferFee) external onlyOwner returns (bool) |
94030 | WFCC | WFCC | contract WFCC is StandardToken {
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie.
string public symbol; //An identifier: eg SBX
function WFCC() {<FILL_FUNCTION_BODY> }
} | contract WFCC is StandardToken {
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie.
string public symbol; <FILL_FUNCTION>
} |
balances[msg.sender] = 68000000000000000; // Give the creator all initial tokens
totalSupply = 68000000000000000; // Update total supply
name = "world financial crypto coin"; // Set the name for display purposes
decimals = 8; // Amount of decimals for display purposes
symbol = "WFCC"; // Set the symbol for display purposes
| function WFCC() | //An identifier: eg SBX
function WFCC() |
22853 | MintableToken | finishMinting | contract MintableToken is StandardToken, Ownable {
bool public mintingFinished = false;
event MintFinished(address account);
modifier canMint() {
require(!mintingFinished);
_;
}
function finishMinting() onlyOwner canMint public returns(bool) {<FILL_FUNCTION_BODY> }
function mint(address to, uint256 value) public canMint onlyOwner returns (bool) {
_mint(to, value);
return true;
}
} | contract MintableToken is StandardToken, Ownable {
bool public mintingFinished = false;
event MintFinished(address account);
modifier canMint() {
require(!mintingFinished);
_;
}
<FILL_FUNCTION>
function mint(address to, uint256 value) public canMint onlyOwner returns (bool) {
_mint(to, value);
return true;
}
} |
mintingFinished = true;
emit MintFinished(msg.sender);
return true;
| function finishMinting() onlyOwner canMint public returns(bool) | function finishMinting() onlyOwner canMint public returns(bool) |
76174 | Exchase | freeze | contract Exchase is ERC20Burnable {
address payable public owner;
mapping (address => uint256) public freezeOf;
/* This notifies clients about the amount frozen */
event Freeze(address indexed from, uint256 value);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed from, uint256 value);
constructor() ERC20("Exchase", "EXSE") public {
_mint(msg.sender, 200000000e18);
}
// can accept ether
receive() external payable {
}
function freeze(uint256 _value) public returns (bool success) {<FILL_FUNCTION_BODY> }
function unfreeze(uint256 _value) public returns (bool success) {
require(balanceOf(msg.sender) < _value); // Check if the sender has enough
require(_value >= 0);
freezeOf[msg.sender] = freezeOf[msg.sender].sub(_value); // Subtract from the sender
_balances[msg.sender] = balanceOf(msg.sender).add(_value);
Unfreeze(msg.sender, _value);
return true;
}
// transfer balance to owner
function withdrawEther(uint256 amount) public {
require(msg.sender == owner);
owner.transfer(amount);
}
} | contract Exchase is ERC20Burnable {
address payable public owner;
mapping (address => uint256) public freezeOf;
/* This notifies clients about the amount frozen */
event Freeze(address indexed from, uint256 value);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed from, uint256 value);
constructor() ERC20("Exchase", "EXSE") public {
_mint(msg.sender, 200000000e18);
}
// can accept ether
receive() external payable {
}
<FILL_FUNCTION>
function unfreeze(uint256 _value) public returns (bool success) {
require(balanceOf(msg.sender) < _value); // Check if the sender has enough
require(_value >= 0);
freezeOf[msg.sender] = freezeOf[msg.sender].sub(_value); // Subtract from the sender
_balances[msg.sender] = balanceOf(msg.sender).add(_value);
Unfreeze(msg.sender, _value);
return true;
}
// transfer balance to owner
function withdrawEther(uint256 amount) public {
require(msg.sender == owner);
owner.transfer(amount);
}
} |
require(balanceOf(msg.sender) <= _value); // Check if the sender has enough
require(_value >= 0);
_balances[msg.sender] = balanceOf(msg.sender).sub(_value); // Subtract from the sender
freezeOf[msg.sender] = freezeOf[msg.sender].add(_value); // Updates totalSupply
Freeze(msg.sender, _value);
return true;
| function freeze(uint256 _value) public returns (bool success) | function freeze(uint256 _value) public returns (bool success) |
4469 | MintableToken | _mint | contract MintableToken is StandardToken, TokenControl {
event Mint(address indexed to, uint256 amount);
/**
* @dev Mints a specific amount of tokens.
* @param _value The amount of token to be Minted.
*/
function mint(uint256 _value) onlyCOO whenNotPaused public {
_mint(_value);
}
function _mint( uint256 _value) internal {<FILL_FUNCTION_BODY> }
} | contract MintableToken is StandardToken, TokenControl {
event Mint(address indexed to, uint256 amount);
/**
* @dev Mints a specific amount of tokens.
* @param _value The amount of token to be Minted.
*/
function mint(uint256 _value) onlyCOO whenNotPaused public {
_mint(_value);
}
<FILL_FUNCTION>
} |
balances[cfoAddress] = balances[cfoAddress].add(_value);
totalSupply_ = totalSupply_.add(_value);
emit Mint(cfoAddress, _value);
emit Transfer(address(0), cfoAddress, _value);
| function _mint( uint256 _value) internal | function _mint( uint256 _value) internal |
93802 | TmToken | _mint | contract TmToken is Ownable, Pausable, IERC20 {
using SafeMath for uint256;
string private _name = "TM Token";
string private _symbol = "TM";
uint8 private _decimals = 6; // 6 decimals
uint256 private _cap = 10000000000000000; // 10 billion cap, that is 10000000000.000000
uint256 private _totalSupply;
mapping (address => bool) private _minter;
event Mint(address indexed to, uint256 value);
event MinterChanged(address account, bool state);
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
bool private _allowWhitelistRegistration;
mapping(address => address) private _referrer;
mapping(address => uint256) private _refCount;
event TokenSaleWhitelistRegistered(address indexed addr, address indexed refAddr);
event TokenSaleWhitelistTransferred(address indexed previousAddr, address indexed _newAddr);
event TokenSaleWhitelistRegistrationEnabled();
event TokenSaleWhitelistRegistrationDisabled();
uint256 private _whitelistRegistrationValue = 101000000; // 101 Token, 101.000000
uint256[15] private _whitelistRefRewards = [ // 100% Reward
31000000, // 31 Token for Level.1
20000000, // 20 Token for Level.2
10000000, // 10 Token for Level.3
10000000, // 10 Token for Level.4
10000000, // 10 Token for Level.5
5000000, // 5 Token for Level.6
4000000, // 4 Token for Level.7
3000000, // 3 Token for Level.8
2000000, // 2 Token for Level.9
1000000, // 1 Token for Level.10
1000000, // 1 Token for Level.11
1000000, // 1 Token for Level.12
1000000, // 1 Token for Level.13
1000000, // 1 Token for Level.14
1000000 // 1 Token for Level.15
];
event Donate(address indexed account, uint256 amount);
constructor() public {
_minter[msg.sender] = true;
_allowWhitelistRegistration = true;
emit TokenSaleWhitelistRegistrationEnabled();
_referrer[msg.sender] = msg.sender;
emit TokenSaleWhitelistRegistered(msg.sender, msg.sender);
}
function () external payable {
emit Donate(msg.sender, msg.value);
}
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 cap() public view returns (uint256) {
return _cap;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
if (_allowWhitelistRegistration && value == _whitelistRegistrationValue
&& inWhitelist(to) && !inWhitelist(msg.sender) && isNotContract(msg.sender)) {
// Register whitelist for TM Token-Sale
_regWhitelist(msg.sender, to);
return true;
} else {
// Normal Transfer
_transfer(msg.sender, to, value);
return true;
}
}
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
require(_allowed[from][msg.sender] >= value);
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0));
require(spender != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
modifier onlyMinter() {
require(_minter[msg.sender]);
_;
}
function isMinter(address account) public view returns (bool) {
return _minter[account];
}
function setMinterState(address account, bool state) external onlyOwner {
_minter[account] = state;
emit MinterChanged(account, state);
}
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
function _mint(address account, uint256 value) internal {<FILL_FUNCTION_BODY> }
modifier onlyInWhitelist() {
require(_referrer[msg.sender] != address(0));
_;
}
function allowWhitelistRegistration() public view returns (bool) {
return _allowWhitelistRegistration;
}
function inWhitelist(address account) public view returns (bool) {
return _referrer[account] != address(0);
}
function referrer(address account) public view returns (address) {
return _referrer[account];
}
function refCount(address account) public view returns (uint256) {
return _refCount[account];
}
function disableTokenSaleWhitelistRegistration() external onlyOwner {
_allowWhitelistRegistration = false;
emit TokenSaleWhitelistRegistrationDisabled();
}
function _regWhitelist(address account, address refAccount) internal {
_refCount[refAccount] = _refCount[refAccount].add(1);
_referrer[account] = refAccount;
emit TokenSaleWhitelistRegistered(account, refAccount);
// Whitelist Registration Referral Reward
_transfer(msg.sender, address(this), _whitelistRegistrationValue);
address cursor = account;
uint256 remain = _whitelistRegistrationValue;
for(uint i = 0; i < _whitelistRefRewards.length; i++) {
address receiver = _referrer[cursor];
if (cursor != receiver) {
if (_refCount[receiver] > i) {
_transfer(address(this), receiver, _whitelistRefRewards[i]);
remain = remain.sub(_whitelistRefRewards[i]);
}
} else {
_transfer(address(this), refAccount, remain);
break;
}
}
}
function transferWhitelist(address account) external onlyInWhitelist {
require(isNotContract(account));
_refCount[account] = _refCount[msg.sender];
_refCount[msg.sender] = 0;
_referrer[account] = _referrer[msg.sender];
_referrer[msg.sender] = address(0);
emit TokenSaleWhitelistTransferred(msg.sender, account);
}
function isNotContract(address addr) internal view returns (bool) {
uint size;
assembly {
size := extcodesize(addr)
}
return size == 0;
}
function calculateTheRewardOfDirectWhitelistRegistration(address whitelistedAccount) external view returns (uint256 reward) {
if (!inWhitelist(whitelistedAccount)) {
return 0;
}
address cursor = whitelistedAccount;
uint256 remain = _whitelistRegistrationValue;
for(uint i = 1; i < _whitelistRefRewards.length; i++) {
address receiver = _referrer[cursor];
if (cursor != receiver) {
if (_refCount[receiver] > i) {
remain = remain.sub(_whitelistRefRewards[i]);
}
} else {
reward = reward.add(remain);
break;
}
cursor = _referrer[cursor];
}
return reward;
}
} | contract TmToken is Ownable, Pausable, IERC20 {
using SafeMath for uint256;
string private _name = "TM Token";
string private _symbol = "TM";
uint8 private _decimals = 6; // 6 decimals
uint256 private _cap = 10000000000000000; // 10 billion cap, that is 10000000000.000000
uint256 private _totalSupply;
mapping (address => bool) private _minter;
event Mint(address indexed to, uint256 value);
event MinterChanged(address account, bool state);
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
bool private _allowWhitelistRegistration;
mapping(address => address) private _referrer;
mapping(address => uint256) private _refCount;
event TokenSaleWhitelistRegistered(address indexed addr, address indexed refAddr);
event TokenSaleWhitelistTransferred(address indexed previousAddr, address indexed _newAddr);
event TokenSaleWhitelistRegistrationEnabled();
event TokenSaleWhitelistRegistrationDisabled();
uint256 private _whitelistRegistrationValue = 101000000; // 101 Token, 101.000000
uint256[15] private _whitelistRefRewards = [ // 100% Reward
31000000, // 31 Token for Level.1
20000000, // 20 Token for Level.2
10000000, // 10 Token for Level.3
10000000, // 10 Token for Level.4
10000000, // 10 Token for Level.5
5000000, // 5 Token for Level.6
4000000, // 4 Token for Level.7
3000000, // 3 Token for Level.8
2000000, // 2 Token for Level.9
1000000, // 1 Token for Level.10
1000000, // 1 Token for Level.11
1000000, // 1 Token for Level.12
1000000, // 1 Token for Level.13
1000000, // 1 Token for Level.14
1000000 // 1 Token for Level.15
];
event Donate(address indexed account, uint256 amount);
constructor() public {
_minter[msg.sender] = true;
_allowWhitelistRegistration = true;
emit TokenSaleWhitelistRegistrationEnabled();
_referrer[msg.sender] = msg.sender;
emit TokenSaleWhitelistRegistered(msg.sender, msg.sender);
}
function () external payable {
emit Donate(msg.sender, msg.value);
}
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 cap() public view returns (uint256) {
return _cap;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
if (_allowWhitelistRegistration && value == _whitelistRegistrationValue
&& inWhitelist(to) && !inWhitelist(msg.sender) && isNotContract(msg.sender)) {
// Register whitelist for TM Token-Sale
_regWhitelist(msg.sender, to);
return true;
} else {
// Normal Transfer
_transfer(msg.sender, to, value);
return true;
}
}
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
require(_allowed[from][msg.sender] >= value);
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0));
require(spender != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
modifier onlyMinter() {
require(_minter[msg.sender]);
_;
}
function isMinter(address account) public view returns (bool) {
return _minter[account];
}
function setMinterState(address account, bool state) external onlyOwner {
_minter[account] = state;
emit MinterChanged(account, state);
}
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
<FILL_FUNCTION>
modifier onlyInWhitelist() {
require(_referrer[msg.sender] != address(0));
_;
}
function allowWhitelistRegistration() public view returns (bool) {
return _allowWhitelistRegistration;
}
function inWhitelist(address account) public view returns (bool) {
return _referrer[account] != address(0);
}
function referrer(address account) public view returns (address) {
return _referrer[account];
}
function refCount(address account) public view returns (uint256) {
return _refCount[account];
}
function disableTokenSaleWhitelistRegistration() external onlyOwner {
_allowWhitelistRegistration = false;
emit TokenSaleWhitelistRegistrationDisabled();
}
function _regWhitelist(address account, address refAccount) internal {
_refCount[refAccount] = _refCount[refAccount].add(1);
_referrer[account] = refAccount;
emit TokenSaleWhitelistRegistered(account, refAccount);
// Whitelist Registration Referral Reward
_transfer(msg.sender, address(this), _whitelistRegistrationValue);
address cursor = account;
uint256 remain = _whitelistRegistrationValue;
for(uint i = 0; i < _whitelistRefRewards.length; i++) {
address receiver = _referrer[cursor];
if (cursor != receiver) {
if (_refCount[receiver] > i) {
_transfer(address(this), receiver, _whitelistRefRewards[i]);
remain = remain.sub(_whitelistRefRewards[i]);
}
} else {
_transfer(address(this), refAccount, remain);
break;
}
}
}
function transferWhitelist(address account) external onlyInWhitelist {
require(isNotContract(account));
_refCount[account] = _refCount[msg.sender];
_refCount[msg.sender] = 0;
_referrer[account] = _referrer[msg.sender];
_referrer[msg.sender] = address(0);
emit TokenSaleWhitelistTransferred(msg.sender, account);
}
function isNotContract(address addr) internal view returns (bool) {
uint size;
assembly {
size := extcodesize(addr)
}
return size == 0;
}
function calculateTheRewardOfDirectWhitelistRegistration(address whitelistedAccount) external view returns (uint256 reward) {
if (!inWhitelist(whitelistedAccount)) {
return 0;
}
address cursor = whitelistedAccount;
uint256 remain = _whitelistRegistrationValue;
for(uint i = 1; i < _whitelistRefRewards.length; i++) {
address receiver = _referrer[cursor];
if (cursor != receiver) {
if (_refCount[receiver] > i) {
remain = remain.sub(_whitelistRefRewards[i]);
}
} else {
reward = reward.add(remain);
break;
}
cursor = _referrer[cursor];
}
return reward;
}
} |
require(_totalSupply.add(value) <= _cap);
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Mint(account, value);
emit Transfer(address(0), account, value);
| function _mint(address account, uint256 value) internal | function _mint(address account, uint256 value) internal |
64843 | StandardToken | transferFrom | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{<FILL_FUNCTION_BODY> }
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
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)
{
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;
}
} | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
<FILL_FUNCTION>
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
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)
{
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;
}
} |
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
| function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
| function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
|
72551 | 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-12-14 Change Jut duty value (4% -> 0.1%)";
address constant public MCD_JUG = 0xF38d987939084c68a2078Ff6FC8804a994197eBC;
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-12-14 Change Jut duty value (4% -> 0.1%)";
address constant public MCD_JUG = 0xF38d987939084c68a2078Ff6FC8804a994197eBC;
<FILL_FUNCTION>
} |
JugLike(MCD_JUG).drip("ETH-A");
JugLike(MCD_JUG).file("ETH-A", "duty", 1000000000031693947650284507);
JugLike(MCD_JUG).drip("ETH-A");
JugLike(MCD_JUG).drip("WBTC-A");
JugLike(MCD_JUG).file("WBTC-A", "duty", 1000000000031693947650284507);
JugLike(MCD_JUG).drip("WBTC-A");
| function execute() external | function execute() external |
65574 | PlasStartup | _safeTransfer | contract PlasStartup is ERC20, Ownable {
uint256 public startTime;
address public initLpPool;
event Purchase(address indexed _to, uint256 _amountIn);
event Launch(uint256 _timestamp);
modifier afterTime() {
require(block.timestamp - startTime > 7 days, "Timed: time not ended");
_;
}
receive() external payable {
if (msg.value > 0) {
_mint(msg.sender, msg.value);
emit Purchase(msg.sender, msg.value);
}
}
function initialize() public initializer {
Ownable.__Ownable_init();
ERC20.__ERC20_init("PLAS Genesis", "vPLAS");
startTime = block.timestamp;
initLpPool = msg.sender;
}
/// @notice allows for entry into the Genesis Group via ETH. Only callable during Genesis Period.
/// @param to address to send PLAS Genesis tokens to
/// @param value amount of ETH to deposit
function purchase(address to, uint256 value)
external
payable
{
require(msg.value == value, "Genesis: value mismatch");
require(value != 0, "Genesis: no value sent");
_mint(to, value);
emit Purchase(to, value);
}
function launch() external onlyOwner afterTime {
// Complete Genesis
_safeTransferETH(initLpPool);
// solhint-disable-next-line not-rely-on-time
emit Launch(block.timestamp);
}
function _safeTransfer(IERC20 token, address to) internal {<FILL_FUNCTION_BODY> }
function _safeTransferETH(address to) internal {
uint256 value = address(this).balance;
(bool success,) = to.call{value:value}(new bytes(0));
require(success, '!ETH_TRANSFER_FAILED');
}
function setLpPool(address _pool) external onlyOwner {
initLpPool = _pool;
}
// transfer unsupport the token, user mis-transfer.
function governanceRecoverUnsupported(IERC20 _token, address _to) external afterTime onlyOwner {
require(block.timestamp - startTime > 30 days, "Timed: after 30days");
_safeTransfer(_token, _to);
}
} | contract PlasStartup is ERC20, Ownable {
uint256 public startTime;
address public initLpPool;
event Purchase(address indexed _to, uint256 _amountIn);
event Launch(uint256 _timestamp);
modifier afterTime() {
require(block.timestamp - startTime > 7 days, "Timed: time not ended");
_;
}
receive() external payable {
if (msg.value > 0) {
_mint(msg.sender, msg.value);
emit Purchase(msg.sender, msg.value);
}
}
function initialize() public initializer {
Ownable.__Ownable_init();
ERC20.__ERC20_init("PLAS Genesis", "vPLAS");
startTime = block.timestamp;
initLpPool = msg.sender;
}
/// @notice allows for entry into the Genesis Group via ETH. Only callable during Genesis Period.
/// @param to address to send PLAS Genesis tokens to
/// @param value amount of ETH to deposit
function purchase(address to, uint256 value)
external
payable
{
require(msg.value == value, "Genesis: value mismatch");
require(value != 0, "Genesis: no value sent");
_mint(to, value);
emit Purchase(to, value);
}
function launch() external onlyOwner afterTime {
// Complete Genesis
_safeTransferETH(initLpPool);
// solhint-disable-next-line not-rely-on-time
emit Launch(block.timestamp);
}
<FILL_FUNCTION>
function _safeTransferETH(address to) internal {
uint256 value = address(this).balance;
(bool success,) = to.call{value:value}(new bytes(0));
require(success, '!ETH_TRANSFER_FAILED');
}
function setLpPool(address _pool) external onlyOwner {
initLpPool = _pool;
}
// transfer unsupport the token, user mis-transfer.
function governanceRecoverUnsupported(IERC20 _token, address _to) external afterTime onlyOwner {
require(block.timestamp - startTime > 30 days, "Timed: after 30days");
_safeTransfer(_token, _to);
}
} |
uint256 value = token.balanceOf(address(this));
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), '!TRANSFER_FAILED');
| function _safeTransfer(IERC20 token, address to) internal | function _safeTransfer(IERC20 token, address to) internal |
37537 | usingNRE | rt | contract usingNRE {
niguezRandomityEngine internal nre = niguezRandomityEngine(0x031eaE8a8105217ab64359D4361022d0947f4572);
function ra() internal view returns (uint256) {
return nre.ra();
}
function rb() internal view returns (uint256) {
return nre.rb();
}
function rc() internal view returns (uint256) {
return nre.rc();
}
function rd() internal view returns (uint256) {
return nre.rd();
}
function re() internal view returns (uint256) {
return nre.re();
}
function rf() internal view returns (uint256) {
return nre.rf();
}
function rg() internal view returns (uint256) {
return nre.rg();
}
function rh() internal view returns (uint256) {
return nre.rh();
}
function ri() internal view returns (uint256) {
return nre.ri();
}
function rj() internal view returns (uint256) {
return nre.rj();
}
function rk() internal view returns (uint256) {
return nre.rk();
}
function rl() internal view returns (uint256) {
return nre.rl();
}
function rm() internal view returns (uint256) {
return nre.rm();
}
function rn() internal view returns (uint256) {
return nre.rn();
}
function ro() internal view returns (uint256) {
return nre.ro();
}
function rp() internal view returns (uint256) {
return nre.rp();
}
function rq() internal view returns (uint256) {
return nre.rq();
}
function rr() internal view returns (uint256) {
return nre.rr();
}
function rs() internal view returns (uint256) {
return nre.rs();
}
function rt() internal view returns (uint256) {<FILL_FUNCTION_BODY> }
function ru() internal view returns (uint256) {
return nre.ru();
}
function rv() internal view returns (uint256) {
return nre.rv();
}
function rw() internal view returns (uint256) {
return nre.rw();
}
function rx() internal view returns (uint256) {
return nre.rx();
}
} | contract usingNRE {
niguezRandomityEngine internal nre = niguezRandomityEngine(0x031eaE8a8105217ab64359D4361022d0947f4572);
function ra() internal view returns (uint256) {
return nre.ra();
}
function rb() internal view returns (uint256) {
return nre.rb();
}
function rc() internal view returns (uint256) {
return nre.rc();
}
function rd() internal view returns (uint256) {
return nre.rd();
}
function re() internal view returns (uint256) {
return nre.re();
}
function rf() internal view returns (uint256) {
return nre.rf();
}
function rg() internal view returns (uint256) {
return nre.rg();
}
function rh() internal view returns (uint256) {
return nre.rh();
}
function ri() internal view returns (uint256) {
return nre.ri();
}
function rj() internal view returns (uint256) {
return nre.rj();
}
function rk() internal view returns (uint256) {
return nre.rk();
}
function rl() internal view returns (uint256) {
return nre.rl();
}
function rm() internal view returns (uint256) {
return nre.rm();
}
function rn() internal view returns (uint256) {
return nre.rn();
}
function ro() internal view returns (uint256) {
return nre.ro();
}
function rp() internal view returns (uint256) {
return nre.rp();
}
function rq() internal view returns (uint256) {
return nre.rq();
}
function rr() internal view returns (uint256) {
return nre.rr();
}
function rs() internal view returns (uint256) {
return nre.rs();
}
<FILL_FUNCTION>
function ru() internal view returns (uint256) {
return nre.ru();
}
function rv() internal view returns (uint256) {
return nre.rv();
}
function rw() internal view returns (uint256) {
return nre.rw();
}
function rx() internal view returns (uint256) {
return nre.rx();
}
} |
return nre.rt();
| function rt() internal view returns (uint256) | function rt() internal view returns (uint256) |
36729 | StandardToken | approve | contract StandardToken is ERC20 {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @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) {
var _allowance = allowed[_from][msg.sender];
require(_to != address(0));
require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {<FILL_FUNCTION_BODY> }
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
} | contract StandardToken is ERC20 {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @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) {
var _allowance = allowed[_from][msg.sender];
require(_to != address(0));
require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
<FILL_FUNCTION>
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
} |
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
| function approve(address _spender, uint256 _value) public returns (bool) | /**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) |
50986 | ERC20Pausable | approve | contract ERC20Pausable is ERC20, Pausable {
function transfer(
address to,
uint256 value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(to, value);
}
function transferFrom(
address from,
address to,
uint256 value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(from, to, value);
}
function approve(
address spender,
uint256 value
)
public
whenNotPaused
returns (bool)
{<FILL_FUNCTION_BODY> }
function increaseAllowance(
address spender,
uint addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(
address spender,
uint subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseAllowance(spender, subtractedValue);
}
} | contract ERC20Pausable is ERC20, Pausable {
function transfer(
address to,
uint256 value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(to, value);
}
function transferFrom(
address from,
address to,
uint256 value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(from, to, value);
}
<FILL_FUNCTION>
function increaseAllowance(
address spender,
uint addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(
address spender,
uint subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseAllowance(spender, subtractedValue);
}
} |
return super.approve(spender, value);
| function approve(
address spender,
uint256 value
)
public
whenNotPaused
returns (bool)
| function approve(
address spender,
uint256 value
)
public
whenNotPaused
returns (bool)
|
12139 | AdExCore | channelWithdrawExpired | contract AdExCore {
using SafeMath for uint;
using ChannelLibrary for ChannelLibrary.Channel;
// channelId => channelState
mapping (bytes32 => ChannelLibrary.State) public states;
// withdrawn per channel (channelId => uint)
mapping (bytes32 => uint) public withdrawn;
// withdrawn per channel user (channelId => (account => uint))
mapping (bytes32 => mapping (address => uint)) public withdrawnPerUser;
// Events
event LogChannelOpen(bytes32 indexed channelId);
event LogChannelWithdrawExpired(bytes32 indexed channelId, uint amount);
event LogChannelWithdraw(bytes32 indexed channelId, uint amount);
// All functions are public
function channelOpen(ChannelLibrary.Channel memory channel)
public
{
bytes32 channelId = channel.hash();
require(states[channelId] == ChannelLibrary.State.Unknown, "INVALID_STATE");
require(msg.sender == channel.creator, "INVALID_CREATOR");
require(channel.isValid(now), "INVALID_CHANNEL");
states[channelId] = ChannelLibrary.State.Active;
SafeERC20.transferFrom(channel.tokenAddr, msg.sender, address(this), channel.tokenAmount);
emit LogChannelOpen(channelId);
}
function channelWithdrawExpired(ChannelLibrary.Channel memory channel)
public
{<FILL_FUNCTION_BODY> }
function channelWithdraw(ChannelLibrary.Channel memory channel, bytes32 stateRoot, bytes32[3][] memory signatures, bytes32[] memory proof, uint amountInTree)
public
{
bytes32 channelId = channel.hash();
require(states[channelId] == ChannelLibrary.State.Active, "INVALID_STATE");
require(now <= channel.validUntil, "EXPIRED");
bytes32 hashToSign = keccak256(abi.encode(channelId, stateRoot));
require(channel.isSignedBySupermajority(hashToSign, signatures), "NOT_SIGNED_BY_VALIDATORS");
bytes32 balanceLeaf = keccak256(abi.encode(msg.sender, amountInTree));
require(MerkleProof.isContained(balanceLeaf, proof, stateRoot), "BALANCELEAF_NOT_FOUND");
// The user can withdraw their constantly increasing balance at any time (essentially prevent users from double spending)
uint toWithdraw = amountInTree.sub(withdrawnPerUser[channelId][msg.sender]);
withdrawnPerUser[channelId][msg.sender] = amountInTree;
// Ensure that it's not possible to withdraw more than the channel deposit (e.g. malicious validators sign such a state)
withdrawn[channelId] = withdrawn[channelId].add(toWithdraw);
require(withdrawn[channelId] <= channel.tokenAmount, "WITHDRAWING_MORE_THAN_CHANNEL");
SafeERC20.transfer(channel.tokenAddr, msg.sender, toWithdraw);
emit LogChannelWithdraw(channelId, toWithdraw);
}
} | contract AdExCore {
using SafeMath for uint;
using ChannelLibrary for ChannelLibrary.Channel;
// channelId => channelState
mapping (bytes32 => ChannelLibrary.State) public states;
// withdrawn per channel (channelId => uint)
mapping (bytes32 => uint) public withdrawn;
// withdrawn per channel user (channelId => (account => uint))
mapping (bytes32 => mapping (address => uint)) public withdrawnPerUser;
// Events
event LogChannelOpen(bytes32 indexed channelId);
event LogChannelWithdrawExpired(bytes32 indexed channelId, uint amount);
event LogChannelWithdraw(bytes32 indexed channelId, uint amount);
// All functions are public
function channelOpen(ChannelLibrary.Channel memory channel)
public
{
bytes32 channelId = channel.hash();
require(states[channelId] == ChannelLibrary.State.Unknown, "INVALID_STATE");
require(msg.sender == channel.creator, "INVALID_CREATOR");
require(channel.isValid(now), "INVALID_CHANNEL");
states[channelId] = ChannelLibrary.State.Active;
SafeERC20.transferFrom(channel.tokenAddr, msg.sender, address(this), channel.tokenAmount);
emit LogChannelOpen(channelId);
}
<FILL_FUNCTION>
function channelWithdraw(ChannelLibrary.Channel memory channel, bytes32 stateRoot, bytes32[3][] memory signatures, bytes32[] memory proof, uint amountInTree)
public
{
bytes32 channelId = channel.hash();
require(states[channelId] == ChannelLibrary.State.Active, "INVALID_STATE");
require(now <= channel.validUntil, "EXPIRED");
bytes32 hashToSign = keccak256(abi.encode(channelId, stateRoot));
require(channel.isSignedBySupermajority(hashToSign, signatures), "NOT_SIGNED_BY_VALIDATORS");
bytes32 balanceLeaf = keccak256(abi.encode(msg.sender, amountInTree));
require(MerkleProof.isContained(balanceLeaf, proof, stateRoot), "BALANCELEAF_NOT_FOUND");
// The user can withdraw their constantly increasing balance at any time (essentially prevent users from double spending)
uint toWithdraw = amountInTree.sub(withdrawnPerUser[channelId][msg.sender]);
withdrawnPerUser[channelId][msg.sender] = amountInTree;
// Ensure that it's not possible to withdraw more than the channel deposit (e.g. malicious validators sign such a state)
withdrawn[channelId] = withdrawn[channelId].add(toWithdraw);
require(withdrawn[channelId] <= channel.tokenAmount, "WITHDRAWING_MORE_THAN_CHANNEL");
SafeERC20.transfer(channel.tokenAddr, msg.sender, toWithdraw);
emit LogChannelWithdraw(channelId, toWithdraw);
}
} |
bytes32 channelId = channel.hash();
require(states[channelId] == ChannelLibrary.State.Active, "INVALID_STATE");
require(now > channel.validUntil, "NOT_EXPIRED");
require(msg.sender == channel.creator, "INVALID_CREATOR");
uint toWithdraw = channel.tokenAmount.sub(withdrawn[channelId]);
// NOTE: we will not update withdrawn, since a WithdrawExpired does not count towards normal withdrawals
states[channelId] = ChannelLibrary.State.Expired;
SafeERC20.transfer(channel.tokenAddr, msg.sender, toWithdraw);
emit LogChannelWithdrawExpired(channelId, toWithdraw);
| function channelWithdrawExpired(ChannelLibrary.Channel memory channel)
public
| function channelWithdrawExpired(ChannelLibrary.Channel memory channel)
public
|
83237 | BaseUnilotGame | getWinners | contract BaseUnilotGame is Game {
enum State {
ACTIVE,
ENDED,
REVOKING,
REVOKED,
MOVED
}
event PrizeResultCalculated(uint size, uint[] prizes);
State state;
address administrator;
uint bet;
mapping (address => TicketLib.Ticket) internal tickets;
address[] internal ticketIndex;
UnilotPrizeCalculator calculator;
//Modifiers
modifier onlyAdministrator() {
require(msg.sender == administrator);
_;
}
modifier onlyPlayer() {
require(msg.sender != administrator);
_;
}
modifier validBet() {
require(msg.value == bet);
_;
}
modifier activeGame() {
require(state == State.ACTIVE);
_;
}
modifier inactiveGame() {
require(state != State.ACTIVE);
_;
}
modifier finishedGame() {
require(state == State.ENDED);
_;
}
//Private methods
function ()
public
payable
validBet
onlyPlayer
{
play();
}
function play() public payable;
function getState()
public
view
returns(State)
{
return state;
}
function getBet()
public
view
returns (uint)
{
return bet;
}
function getPlayers()
public
constant
returns(address[])
{
return ticketIndex;
}
function getPlayerDetails(address player)
public
view
inactiveGame
returns (bool, bool, uint, uint, uint, uint)
{
TicketLib.Ticket memory ticket = tickets[player];
return (ticket.is_winner, ticket.is_active,
ticket.block_number, ticket.block_time, ticket.num_votes, ticket.prize);
}
function getWinners()
public
view
finishedGame
returns(address[] memory players, uint[] memory prizes)
{<FILL_FUNCTION_BODY> }
function getNumWinners()
public
constant
returns (uint, uint)
{
var(numWinners, numFixedAmountWinners) = calculator.getNumWinners(ticketIndex.length);
return (numWinners, numFixedAmountWinners);
}
function getPrizeAmount()
public
constant
returns (uint result)
{
uint totalAmount = this.balance;
if ( state == State.ENDED ) {
totalAmount = bet * ticketIndex.length;
}
result = calculator.getPrizeAmount(totalAmount);
return result;
}
function getStat()
public
constant
returns ( uint, uint, uint )
{
var (numWinners, numFixedAmountWinners) = getNumWinners();
return (ticketIndex.length, getPrizeAmount(), uint(numWinners + numFixedAmountWinners));
}
function calcaultePrizes()
public
returns(uint[] memory result)
{
var(numWinners, numFixedAmountWinners) = getNumWinners();
uint totalNumWinners = ( numWinners + numFixedAmountWinners );
result = new uint[]( totalNumWinners );
uint[50] memory prizes = calculator.calcaultePrizes(
bet, ticketIndex.length);
for (uint i = 0; i < totalNumWinners; i++) {
result[i] = prizes[i];
}
return result;
}
function revoke()
public
onlyAdministrator
activeGame
{
for (uint i = 0; i < ticketIndex.length; i++) {
tickets[ticketIndex[i]].is_active = false;
ticketIndex[i].transfer(bet);
}
state = State.REVOKED;
}
} | contract BaseUnilotGame is Game {
enum State {
ACTIVE,
ENDED,
REVOKING,
REVOKED,
MOVED
}
event PrizeResultCalculated(uint size, uint[] prizes);
State state;
address administrator;
uint bet;
mapping (address => TicketLib.Ticket) internal tickets;
address[] internal ticketIndex;
UnilotPrizeCalculator calculator;
//Modifiers
modifier onlyAdministrator() {
require(msg.sender == administrator);
_;
}
modifier onlyPlayer() {
require(msg.sender != administrator);
_;
}
modifier validBet() {
require(msg.value == bet);
_;
}
modifier activeGame() {
require(state == State.ACTIVE);
_;
}
modifier inactiveGame() {
require(state != State.ACTIVE);
_;
}
modifier finishedGame() {
require(state == State.ENDED);
_;
}
//Private methods
function ()
public
payable
validBet
onlyPlayer
{
play();
}
function play() public payable;
function getState()
public
view
returns(State)
{
return state;
}
function getBet()
public
view
returns (uint)
{
return bet;
}
function getPlayers()
public
constant
returns(address[])
{
return ticketIndex;
}
function getPlayerDetails(address player)
public
view
inactiveGame
returns (bool, bool, uint, uint, uint, uint)
{
TicketLib.Ticket memory ticket = tickets[player];
return (ticket.is_winner, ticket.is_active,
ticket.block_number, ticket.block_time, ticket.num_votes, ticket.prize);
}
<FILL_FUNCTION>
function getNumWinners()
public
constant
returns (uint, uint)
{
var(numWinners, numFixedAmountWinners) = calculator.getNumWinners(ticketIndex.length);
return (numWinners, numFixedAmountWinners);
}
function getPrizeAmount()
public
constant
returns (uint result)
{
uint totalAmount = this.balance;
if ( state == State.ENDED ) {
totalAmount = bet * ticketIndex.length;
}
result = calculator.getPrizeAmount(totalAmount);
return result;
}
function getStat()
public
constant
returns ( uint, uint, uint )
{
var (numWinners, numFixedAmountWinners) = getNumWinners();
return (ticketIndex.length, getPrizeAmount(), uint(numWinners + numFixedAmountWinners));
}
function calcaultePrizes()
public
returns(uint[] memory result)
{
var(numWinners, numFixedAmountWinners) = getNumWinners();
uint totalNumWinners = ( numWinners + numFixedAmountWinners );
result = new uint[]( totalNumWinners );
uint[50] memory prizes = calculator.calcaultePrizes(
bet, ticketIndex.length);
for (uint i = 0; i < totalNumWinners; i++) {
result[i] = prizes[i];
}
return result;
}
function revoke()
public
onlyAdministrator
activeGame
{
for (uint i = 0; i < ticketIndex.length; i++) {
tickets[ticketIndex[i]].is_active = false;
ticketIndex[i].transfer(bet);
}
state = State.REVOKED;
}
} |
var(numWinners, numFixedAmountWinners) = getNumWinners();
uint totalNumWinners = numWinners + numFixedAmountWinners;
players = new address[](totalNumWinners);
prizes = new uint[](totalNumWinners);
uint index = 0;
for (uint i = 0; i < ticketIndex.length; i++) {
if (tickets[ticketIndex[i]].is_winner == true) {
players[index] = ticketIndex[i];
prizes[index] = tickets[ticketIndex[i]].prize;
index++;
}
}
return (players, prizes);
| function getWinners()
public
view
finishedGame
returns(address[] memory players, uint[] memory prizes)
| function getWinners()
public
view
finishedGame
returns(address[] memory players, uint[] memory prizes)
|
11668 | BballPandas | _beforeTokenTransfer | contract BballPandas is ERC721, ERC721Enumerable, ERC721URIStorage, Ownable {
using SafeMath for uint256;
uint256 public constant pandaPrice = 80000000000000000; //0.08 ETH
uint256 public constant maxPandaPurchase = 20;
uint256 public constant MAX_PANDAS = 10000;
bool public saleIsActive = false;
constructor(string memory name, string memory symbol) ERC721(name, symbol) {
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function _baseURI() internal pure override returns (string memory) {
return "ipfs://QmWxC8nY73zWYfGdrJFAZuZK9dDbNysK1o2HhdF5y5NAWH/";
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{<FILL_FUNCTION_BODY> }
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function toggleSale() public onlyOwner {
saleIsActive = !saleIsActive;
}
function reservePandas() public onlyOwner {
uint256 supply = totalSupply();
uint256 i;
for (i = 0; i < 25; i++) {
_safeMint(msg.sender, supply + i);
}
}
function mintPanda(uint numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint Panda");
require(numberOfTokens <= maxPandaPurchase, "Can only mint a maximum of 20 tokens in a single transaction");
require(totalSupply().add(numberOfTokens) <= MAX_PANDAS, "Purchase would exceed max supply of Pandas");
require(pandaPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
for(uint256 i = 0; i < numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_PANDAS) {
_safeMint(msg.sender, mintIndex);
}
}
}
} | contract BballPandas is ERC721, ERC721Enumerable, ERC721URIStorage, Ownable {
using SafeMath for uint256;
uint256 public constant pandaPrice = 80000000000000000; //0.08 ETH
uint256 public constant maxPandaPurchase = 20;
uint256 public constant MAX_PANDAS = 10000;
bool public saleIsActive = false;
constructor(string memory name, string memory symbol) ERC721(name, symbol) {
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function _baseURI() internal pure override returns (string memory) {
return "ipfs://QmWxC8nY73zWYfGdrJFAZuZK9dDbNysK1o2HhdF5y5NAWH/";
}
<FILL_FUNCTION>
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function toggleSale() public onlyOwner {
saleIsActive = !saleIsActive;
}
function reservePandas() public onlyOwner {
uint256 supply = totalSupply();
uint256 i;
for (i = 0; i < 25; i++) {
_safeMint(msg.sender, supply + i);
}
}
function mintPanda(uint numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint Panda");
require(numberOfTokens <= maxPandaPurchase, "Can only mint a maximum of 20 tokens in a single transaction");
require(totalSupply().add(numberOfTokens) <= MAX_PANDAS, "Purchase would exceed max supply of Pandas");
require(pandaPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
for(uint256 i = 0; i < numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_PANDAS) {
_safeMint(msg.sender, mintIndex);
}
}
}
} |
super._beforeTokenTransfer(from, to, tokenId);
| function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
| function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
|
26634 | ERC20PresetMinterPauser | pause | contract ERC20PresetMinterPauser is
Context,
AccessControl,
ERC20Burnable,
ERC20Pausable
{
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
constructor(string memory name, string memory symbol)
public
ERC20(name, symbol)
{
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
function mint(address to, uint256 amount) public virtual {
require(
hasRole(MINTER_ROLE, _msgSender()),
"ERC20PresetMinterPauser: must have minter role to mint"
);
_mint(to, amount);
}
function pause() public virtual {<FILL_FUNCTION_BODY> }
function unpause() public virtual {
require(
hasRole(PAUSER_ROLE, _msgSender()),
"ERC20PresetMinterPauser: must have pauser role to unpause"
);
_unpause();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
} | contract ERC20PresetMinterPauser is
Context,
AccessControl,
ERC20Burnable,
ERC20Pausable
{
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
constructor(string memory name, string memory symbol)
public
ERC20(name, symbol)
{
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
function mint(address to, uint256 amount) public virtual {
require(
hasRole(MINTER_ROLE, _msgSender()),
"ERC20PresetMinterPauser: must have minter role to mint"
);
_mint(to, amount);
}
<FILL_FUNCTION>
function unpause() public virtual {
require(
hasRole(PAUSER_ROLE, _msgSender()),
"ERC20PresetMinterPauser: must have pauser role to unpause"
);
_unpause();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
} |
require(
hasRole(PAUSER_ROLE, _msgSender()),
"ERC20PresetMinterPauser: must have pauser role to pause"
);
_pause();
| function pause() public virtual | function pause() public virtual |
8481 | StandardToken | approve | contract StandardToken is ERC20, BurnableToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) afterListing public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
if (!staff[_from]) {
require(_value <= checkVestingWithFrozen(_from));
}
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {<FILL_FUNCTION_BODY> }
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
} | contract StandardToken is ERC20, BurnableToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) afterListing public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
if (!staff[_from]) {
require(_value <= checkVestingWithFrozen(_from));
}
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
<FILL_FUNCTION>
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
} |
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
| function approve(address _spender, uint256 _value) public returns (bool) | /**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) |
19223 | LotteryNFT | claimReward | contract LotteryNFT is ERC721, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
mapping (uint256 => uint8[4]) public lotteryInfo;
mapping (uint256 => uint256) public lotteryAmount;
mapping (uint256 => uint256) public issueIndex;
mapping (uint256 => bool) public claimInfo;
constructor() public ERC721("Atari Lottery Ticket", "ATRITK") {}
function newLotteryItem(address player, uint8[4] memory _lotteryNumbers, uint256 _amount, uint256 _issueIndex)
public onlyOwner
returns (uint256)
{
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(player, newItemId);
lotteryInfo[newItemId] = _lotteryNumbers;
lotteryAmount[newItemId] = _amount;
issueIndex[newItemId] = _issueIndex;
return newItemId;
}
function getLotteryNumbers(uint256 tokenId) external view returns (uint8[4] memory) {
return lotteryInfo[tokenId];
}
function getLotteryAmount(uint256 tokenId) external view returns (uint256) {
return lotteryAmount[tokenId];
}
function getLotteryIssueIndex(uint256 tokenId) external view returns (uint256) {
return issueIndex[tokenId];
}
function claimReward(uint256 tokenId) external onlyOwner {<FILL_FUNCTION_BODY> }
function multiClaimReward(uint256[] memory _tokenIds) external onlyOwner {
for (uint i = 0; i < _tokenIds.length; i++) {
claimInfo[_tokenIds[i]] = true;
}
}
function burn(uint256 tokenId) external onlyOwner {
_burn(tokenId);
}
function getClaimStatus(uint256 tokenId) external view returns (bool) {
return claimInfo[tokenId];
}
} | contract LotteryNFT is ERC721, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
mapping (uint256 => uint8[4]) public lotteryInfo;
mapping (uint256 => uint256) public lotteryAmount;
mapping (uint256 => uint256) public issueIndex;
mapping (uint256 => bool) public claimInfo;
constructor() public ERC721("Atari Lottery Ticket", "ATRITK") {}
function newLotteryItem(address player, uint8[4] memory _lotteryNumbers, uint256 _amount, uint256 _issueIndex)
public onlyOwner
returns (uint256)
{
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(player, newItemId);
lotteryInfo[newItemId] = _lotteryNumbers;
lotteryAmount[newItemId] = _amount;
issueIndex[newItemId] = _issueIndex;
return newItemId;
}
function getLotteryNumbers(uint256 tokenId) external view returns (uint8[4] memory) {
return lotteryInfo[tokenId];
}
function getLotteryAmount(uint256 tokenId) external view returns (uint256) {
return lotteryAmount[tokenId];
}
function getLotteryIssueIndex(uint256 tokenId) external view returns (uint256) {
return issueIndex[tokenId];
}
<FILL_FUNCTION>
function multiClaimReward(uint256[] memory _tokenIds) external onlyOwner {
for (uint i = 0; i < _tokenIds.length; i++) {
claimInfo[_tokenIds[i]] = true;
}
}
function burn(uint256 tokenId) external onlyOwner {
_burn(tokenId);
}
function getClaimStatus(uint256 tokenId) external view returns (bool) {
return claimInfo[tokenId];
}
} |
claimInfo[tokenId] = true;
| function claimReward(uint256 tokenId) external onlyOwner | function claimReward(uint256 tokenId) external onlyOwner |
713 | StandardToken | approve | contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) allowed;
uint constant MAX_UINT = 2**256 - 1;
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) {
var _allowance = allowed[_from][msg.sender];
uint fee = (_value.mul(basisPointsRate)).div(10000);
if (fee > maximumFee) {
fee = maximumFee;
}
uint sendAmount = _value.sub(fee);
balances[_to] = balances[_to].add(sendAmount);
balances[owner] = balances[owner].add(fee);
balances[_from] = balances[_from].sub(_value);
if (_allowance < MAX_UINT) {
allowed[_from][msg.sender] = _allowance.sub(_value);
}
Transfer(_from, _to, sendAmount);
Transfer(_from, owner, fee);
}
function approve(address _spender, uint _value) onlyPayloadSize(2 * 32) {<FILL_FUNCTION_BODY> }
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
} | contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) allowed;
uint constant MAX_UINT = 2**256 - 1;
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) {
var _allowance = allowed[_from][msg.sender];
uint fee = (_value.mul(basisPointsRate)).div(10000);
if (fee > maximumFee) {
fee = maximumFee;
}
uint sendAmount = _value.sub(fee);
balances[_to] = balances[_to].add(sendAmount);
balances[owner] = balances[owner].add(fee);
balances[_from] = balances[_from].sub(_value);
if (_allowance < MAX_UINT) {
allowed[_from][msg.sender] = _allowance.sub(_value);
}
Transfer(_from, _to, sendAmount);
Transfer(_from, owner, fee);
}
<FILL_FUNCTION>
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
} |
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
| function approve(address _spender, uint _value) onlyPayloadSize(2 * 32) | function approve(address _spender, uint _value) onlyPayloadSize(2 * 32) |
39579 | HumanTokenAllocator | startFirstStage | contract HumanTokenAllocator {
using SafeMath for uint;
HumanToken public Human;
uint public rateEth = 700; // Rate USD per ETH
uint public tokenPerUsdNumerator = 1;
uint public tokenPerUsdDenominator = 1;
uint public firstStageRaised;
uint public secondStageRaised;
uint public firstStageCap = 7*10**24;
uint public secondStageCap = 32*10**24;
uint public FIFTY_THOUSANDS_LIMIT = 5*10**22;
uint teamPart = 7*10**24;
bool public publicAllocationEnabled;
address public teamFund;
address public owner;
address public oracle; // Oracle address
address public company;
event LogBuyForInvestor(address investor, uint humanValue, string txHash);
event ControllerAdded(address _controller);
event ControllerRemoved(address _controller);
event FirstStageStarted(uint _timestamp);
event SecondStageStarted(uint _timestamp);
event AllocationFinished(uint _timestamp);
event PublicAllocationEnabled(uint _timestamp);
event PublicAllocationDisabled(uint _timestamp);
mapping(address => bool) public isController;
// Allows execution by the owner only
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// Allows execution by the oracle only
modifier onlyOracle {
require(msg.sender == oracle);
_;
}
// Allows execution by the controllers only
modifier onlyControllers {
require(isController[msg.sender]);
_;
}
// Possible statuses
enum Status {
Created,
firstStage,
secondStage,
Finished
}
Status public status = Status.Created;
/**
* @dev Contract constructor function sets outside addresses
*/
function HumanTokenAllocator(
address _owner,
address _oracle,
address _company,
address _teamFund,
address _eventManager
) public {
owner = _owner;
oracle = _oracle;
company = _company;
teamFund = _teamFund;
Human = new HumanToken(address(this), _eventManager);
}
/**
* @dev Fallback function calls buy(address _holder, uint _humanValue) function to issue tokens
*/
function() external payable {
require(publicAllocationEnabled);
uint humanValue = msg.value.mul(rateEth).mul(tokenPerUsdNumerator).div(tokenPerUsdDenominator);
if (status == Status.secondStage) {
require(humanValue >= FIFTY_THOUSANDS_LIMIT);
}
buy(msg.sender, humanValue);
}
/**
* @dev Function to set rate of ETH
* @param _rateEth current ETH rate
*/
function setRate(uint _rateEth) external onlyOracle {
rateEth = _rateEth;
}
/**
* @dev Function to set current token price
* @param _numerator human token per usd numerator
* @param _denominator human token per usd denominator
*/
function setPrice(uint _numerator, uint _denominator) external onlyOracle {
tokenPerUsdNumerator = _numerator;
tokenPerUsdDenominator = _denominator;
}
/**
* @dev Function to issues tokens for investors who made purchases in other cryptocurrencies
* @param _holder address the tokens will be issued to
* @param _humanValue number of Human tokens
* @param _txHash transaction hash of investor's payment
*/
function buyForInvestor(
address _holder,
uint _humanValue,
string _txHash
)
external
onlyControllers {
buy(_holder, _humanValue);
LogBuyForInvestor(_holder, _humanValue, _txHash);
}
/**
* @dev Function to issue tokens for investors who paid in ether
* @param _holder address which the tokens will be issued tokens
* @param _humanValue number of Human tokens
*/
function buy(address _holder, uint _humanValue) internal {
require(status == Status.firstStage || status == Status.secondStage);
if (status == Status.firstStage) {
require(firstStageRaised + _humanValue <= firstStageCap);
firstStageRaised = firstStageRaised.add(_humanValue);
} else {
require(secondStageRaised + _humanValue <= secondStageCap);
secondStageRaised = secondStageRaised.add(_humanValue);
}
Human.mintTokens(_holder, _humanValue);
}
/**
* @dev Function to add an address to the controllers
* @param _controller an address that will be added to managers list
*/
function addController(address _controller) onlyOwner external {
require(!isController[_controller]);
isController[_controller] = true;
ControllerAdded(_controller);
}
/**
* @dev Function to remove an address to the controllers
* @param _controller an address that will be removed from managers list
*/
function removeController(address _controller) onlyOwner external {
require(isController[_controller]);
isController[_controller] = false;
ControllerRemoved(_controller);
}
/**
* @dev Function to start the first stage of human token allocation
* and to issue human token for team fund
*/
function startFirstStage() public onlyOwner {<FILL_FUNCTION_BODY> }
/**
* @dev Function to start the second stage of human token allocation
*/
function startSecondStage() public onlyOwner {
require(status == Status.firstStage);
status = Status.secondStage;
SecondStageStarted(now);
}
/**
* @dev Function to finish human token allocation and to finish token issue
*/
function finish() public onlyOwner {
require (status == Status.secondStage);
status = Status.Finished;
AllocationFinished(now);
}
/**
* @dev Function to enable public token allocation
*/
function enable() public onlyOwner {
publicAllocationEnabled = true;
PublicAllocationEnabled(now);
}
/**
* @dev Function to disable public token allocation
*/
function disable() public onlyOwner {
publicAllocationEnabled = false;
PublicAllocationDisabled(now);
}
/**
* @dev Function to withdraw ether
*/
function withdraw() external onlyOwner {
company.transfer(address(this).balance);
}
/**
* @dev Allows owner to transfer out any accidentally sent ERC20 tokens
* @param tokenAddress token address
* @param tokens transfer amount
*/
function transferAnyTokens(address tokenAddress, uint tokens)
public
onlyOwner
returns (bool success) {
return ERC20(tokenAddress).transfer(owner, tokens);
}
} | contract HumanTokenAllocator {
using SafeMath for uint;
HumanToken public Human;
uint public rateEth = 700; // Rate USD per ETH
uint public tokenPerUsdNumerator = 1;
uint public tokenPerUsdDenominator = 1;
uint public firstStageRaised;
uint public secondStageRaised;
uint public firstStageCap = 7*10**24;
uint public secondStageCap = 32*10**24;
uint public FIFTY_THOUSANDS_LIMIT = 5*10**22;
uint teamPart = 7*10**24;
bool public publicAllocationEnabled;
address public teamFund;
address public owner;
address public oracle; // Oracle address
address public company;
event LogBuyForInvestor(address investor, uint humanValue, string txHash);
event ControllerAdded(address _controller);
event ControllerRemoved(address _controller);
event FirstStageStarted(uint _timestamp);
event SecondStageStarted(uint _timestamp);
event AllocationFinished(uint _timestamp);
event PublicAllocationEnabled(uint _timestamp);
event PublicAllocationDisabled(uint _timestamp);
mapping(address => bool) public isController;
// Allows execution by the owner only
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// Allows execution by the oracle only
modifier onlyOracle {
require(msg.sender == oracle);
_;
}
// Allows execution by the controllers only
modifier onlyControllers {
require(isController[msg.sender]);
_;
}
// Possible statuses
enum Status {
Created,
firstStage,
secondStage,
Finished
}
Status public status = Status.Created;
/**
* @dev Contract constructor function sets outside addresses
*/
function HumanTokenAllocator(
address _owner,
address _oracle,
address _company,
address _teamFund,
address _eventManager
) public {
owner = _owner;
oracle = _oracle;
company = _company;
teamFund = _teamFund;
Human = new HumanToken(address(this), _eventManager);
}
/**
* @dev Fallback function calls buy(address _holder, uint _humanValue) function to issue tokens
*/
function() external payable {
require(publicAllocationEnabled);
uint humanValue = msg.value.mul(rateEth).mul(tokenPerUsdNumerator).div(tokenPerUsdDenominator);
if (status == Status.secondStage) {
require(humanValue >= FIFTY_THOUSANDS_LIMIT);
}
buy(msg.sender, humanValue);
}
/**
* @dev Function to set rate of ETH
* @param _rateEth current ETH rate
*/
function setRate(uint _rateEth) external onlyOracle {
rateEth = _rateEth;
}
/**
* @dev Function to set current token price
* @param _numerator human token per usd numerator
* @param _denominator human token per usd denominator
*/
function setPrice(uint _numerator, uint _denominator) external onlyOracle {
tokenPerUsdNumerator = _numerator;
tokenPerUsdDenominator = _denominator;
}
/**
* @dev Function to issues tokens for investors who made purchases in other cryptocurrencies
* @param _holder address the tokens will be issued to
* @param _humanValue number of Human tokens
* @param _txHash transaction hash of investor's payment
*/
function buyForInvestor(
address _holder,
uint _humanValue,
string _txHash
)
external
onlyControllers {
buy(_holder, _humanValue);
LogBuyForInvestor(_holder, _humanValue, _txHash);
}
/**
* @dev Function to issue tokens for investors who paid in ether
* @param _holder address which the tokens will be issued tokens
* @param _humanValue number of Human tokens
*/
function buy(address _holder, uint _humanValue) internal {
require(status == Status.firstStage || status == Status.secondStage);
if (status == Status.firstStage) {
require(firstStageRaised + _humanValue <= firstStageCap);
firstStageRaised = firstStageRaised.add(_humanValue);
} else {
require(secondStageRaised + _humanValue <= secondStageCap);
secondStageRaised = secondStageRaised.add(_humanValue);
}
Human.mintTokens(_holder, _humanValue);
}
/**
* @dev Function to add an address to the controllers
* @param _controller an address that will be added to managers list
*/
function addController(address _controller) onlyOwner external {
require(!isController[_controller]);
isController[_controller] = true;
ControllerAdded(_controller);
}
/**
* @dev Function to remove an address to the controllers
* @param _controller an address that will be removed from managers list
*/
function removeController(address _controller) onlyOwner external {
require(isController[_controller]);
isController[_controller] = false;
ControllerRemoved(_controller);
}
<FILL_FUNCTION>
/**
* @dev Function to start the second stage of human token allocation
*/
function startSecondStage() public onlyOwner {
require(status == Status.firstStage);
status = Status.secondStage;
SecondStageStarted(now);
}
/**
* @dev Function to finish human token allocation and to finish token issue
*/
function finish() public onlyOwner {
require (status == Status.secondStage);
status = Status.Finished;
AllocationFinished(now);
}
/**
* @dev Function to enable public token allocation
*/
function enable() public onlyOwner {
publicAllocationEnabled = true;
PublicAllocationEnabled(now);
}
/**
* @dev Function to disable public token allocation
*/
function disable() public onlyOwner {
publicAllocationEnabled = false;
PublicAllocationDisabled(now);
}
/**
* @dev Function to withdraw ether
*/
function withdraw() external onlyOwner {
company.transfer(address(this).balance);
}
/**
* @dev Allows owner to transfer out any accidentally sent ERC20 tokens
* @param tokenAddress token address
* @param tokens transfer amount
*/
function transferAnyTokens(address tokenAddress, uint tokens)
public
onlyOwner
returns (bool success) {
return ERC20(tokenAddress).transfer(owner, tokens);
}
} |
require(status == Status.Created);
Human.mintTokens(teamFund, teamPart);
status = Status.firstStage;
FirstStageStarted(now);
| function startFirstStage() public onlyOwner | /**
* @dev Function to start the first stage of human token allocation
* and to issue human token for team fund
*/
function startFirstStage() public onlyOwner |
30220 | AToken | redirectInterestStreamInternal | contract AToken is ERC20, ERC20Detailed {
using WadRayMath for uint256;
uint256 public constant UINT_MAX_VALUE = uint256(-1);
/**
* @dev emitted after the redeem action
* @param _from the address performing the redeem
* @param _value the amount to be redeemed
* @param _fromBalanceIncrease the cumulated balance since the last update of the user
* @param _fromIndex the last index of the user
**/
event Redeem(
address indexed _from,
uint256 _value,
uint256 _fromBalanceIncrease,
uint256 _fromIndex
);
/**
* @dev emitted after the mint action
* @param _from the address performing the mint
* @param _value the amount to be minted
* @param _fromBalanceIncrease the cumulated balance since the last update of the user
* @param _fromIndex the last index of the user
**/
event MintOnDeposit(
address indexed _from,
uint256 _value,
uint256 _fromBalanceIncrease,
uint256 _fromIndex
);
/**
* @dev emitted during the liquidation action, when the liquidator reclaims the underlying
* asset
* @param _from the address from which the tokens are being burned
* @param _value the amount to be burned
* @param _fromBalanceIncrease the cumulated balance since the last update of the user
* @param _fromIndex the last index of the user
**/
event BurnOnLiquidation(
address indexed _from,
uint256 _value,
uint256 _fromBalanceIncrease,
uint256 _fromIndex
);
/**
* @dev emitted during the transfer action
* @param _from the address from which the tokens are being transferred
* @param _to the adress of the destination
* @param _value the amount to be minted
* @param _fromBalanceIncrease the cumulated balance since the last update of the user
* @param _toBalanceIncrease the cumulated balance since the last update of the destination
* @param _fromIndex the last index of the user
* @param _toIndex the last index of the liquidator
**/
event BalanceTransfer(
address indexed _from,
address indexed _to,
uint256 _value,
uint256 _fromBalanceIncrease,
uint256 _toBalanceIncrease,
uint256 _fromIndex,
uint256 _toIndex
);
/**
* @dev emitted when the accumulation of the interest
* by an user is redirected to another user
* @param _from the address from which the interest is being redirected
* @param _to the adress of the destination
* @param _fromBalanceIncrease the cumulated balance since the last update of the user
* @param _fromIndex the last index of the user
**/
event InterestStreamRedirected(
address indexed _from,
address indexed _to,
uint256 _redirectedBalance,
uint256 _fromBalanceIncrease,
uint256 _fromIndex
);
/**
* @dev emitted when the redirected balance of an user is being updated
* @param _targetAddress the address of which the balance is being updated
* @param _targetBalanceIncrease the cumulated balance since the last update of the target
* @param _targetIndex the last index of the user
* @param _redirectedBalanceAdded the redirected balance being added
* @param _redirectedBalanceRemoved the redirected balance being removed
**/
event RedirectedBalanceUpdated(
address indexed _targetAddress,
uint256 _targetBalanceIncrease,
uint256 _targetIndex,
uint256 _redirectedBalanceAdded,
uint256 _redirectedBalanceRemoved
);
event InterestRedirectionAllowanceChanged(
address indexed _from,
address indexed _to
);
address public underlyingAssetAddress;
mapping (address => uint256) private userIndexes;
mapping (address => address) private interestRedirectionAddresses;
mapping (address => uint256) private redirectedBalances;
mapping (address => address) private interestRedirectionAllowances;
LendingPoolAddressesProvider private addressesProvider;
LendingPoolCore private core;
LendingPool private pool;
LendingPoolDataProvider private dataProvider;
modifier onlyLendingPool {
require(
msg.sender == address(pool),
"The caller of this function must be a lending pool"
);
_;
}
modifier whenTransferAllowed(address _from, uint256 _amount) {
require(isTransferAllowed(_from, _amount), "Transfer cannot be allowed.");
_;
}
constructor(
LendingPoolAddressesProvider _addressesProvider,
address _underlyingAsset,
uint8 _underlyingAssetDecimals,
string memory _name,
string memory _symbol
) public ERC20Detailed(_name, _symbol, _underlyingAssetDecimals) {
addressesProvider = _addressesProvider;
core = LendingPoolCore(addressesProvider.getLendingPoolCore());
pool = LendingPool(addressesProvider.getLendingPool());
dataProvider = LendingPoolDataProvider(addressesProvider.getLendingPoolDataProvider());
underlyingAssetAddress = _underlyingAsset;
}
/**
* @notice ERC20 implementation internal function backing transfer() and transferFrom()
* @dev validates the transfer before allowing it. NOTE: This is not standard ERC20 behavior
**/
function _transfer(address _from, address _to, uint256 _amount) internal whenTransferAllowed(_from, _amount) {
executeTransferInternal(_from, _to, _amount);
}
/**
* @dev redirects the interest generated to a target address.
* when the interest is redirected, the user balance is added to
* the recepient redirected balance.
* @param _to the address to which the interest will be redirected
**/
function redirectInterestStream(address _to) external {
redirectInterestStreamInternal(msg.sender, _to);
}
/**
* @dev redirects the interest generated by _from to a target address.
* when the interest is redirected, the user balance is added to
* the recepient redirected balance. The caller needs to have allowance on
* the interest redirection to be able to execute the function.
* @param _from the address of the user whom interest is being redirected
* @param _to the address to which the interest will be redirected
**/
function redirectInterestStreamOf(address _from, address _to) external {
require(
msg.sender == interestRedirectionAllowances[_from],
"Caller is not allowed to redirect the interest of the user"
);
redirectInterestStreamInternal(_from,_to);
}
/**
* @dev gives allowance to an address to execute the interest redirection
* on behalf of the caller.
* @param _to the address to which the interest will be redirected. Pass address(0) to reset
* the allowance.
**/
function allowInterestRedirectionTo(address _to) external {
require(_to != msg.sender, "User cannot give allowance to himself");
interestRedirectionAllowances[msg.sender] = _to;
emit InterestRedirectionAllowanceChanged(
msg.sender,
_to
);
}
/**
* @dev redeems aToken for the underlying asset
* @param _amount the amount being redeemed
**/
function redeem(uint256 _amount) external {
require(_amount > 0, "Amount to redeem needs to be > 0");
//cumulates the balance of the user
(,
uint256 currentBalance,
uint256 balanceIncrease,
uint256 index) = cumulateBalanceInternal(msg.sender);
uint256 amountToRedeem = _amount;
//if amount is equal to uint(-1), the user wants to redeem everything
if(_amount == UINT_MAX_VALUE){
amountToRedeem = currentBalance;
}
require(amountToRedeem <= currentBalance, "User cannot redeem more than the available balance");
//check that the user is allowed to redeem the amount
require(isTransferAllowed(msg.sender, amountToRedeem), "Transfer cannot be allowed.");
//if the user is redirecting his interest towards someone else,
//we update the redirected balance of the redirection address by adding the accrued interest,
//and removing the amount to redeem
updateRedirectedBalanceOfRedirectionAddressInternal(msg.sender, balanceIncrease, amountToRedeem);
// burns tokens equivalent to the amount requested
_burn(msg.sender, amountToRedeem);
bool userIndexReset = false;
//reset the user data if the remaining balance is 0
if(currentBalance.sub(amountToRedeem) == 0){
userIndexReset = resetDataOnZeroBalanceInternal(msg.sender);
}
// executes redeem of the underlying asset
pool.redeemUnderlying(
underlyingAssetAddress,
msg.sender,
amountToRedeem,
currentBalance.sub(amountToRedeem)
);
emit Redeem(msg.sender, amountToRedeem, balanceIncrease, userIndexReset ? 0 : index);
}
/**
* @dev mints token in the event of users depositing the underlying asset into the lending pool
* only lending pools can call this function
* @param _account the address receiving the minted tokens
* @param _amount the amount of tokens to mint
*/
function mintOnDeposit(address _account, uint256 _amount) external onlyLendingPool {
//cumulates the balance of the user
(,
,
uint256 balanceIncrease,
uint256 index) = cumulateBalanceInternal(_account);
//if the user is redirecting his interest towards someone else,
//we update the redirected balance of the redirection address by adding the accrued interest
//and the amount deposited
updateRedirectedBalanceOfRedirectionAddressInternal(_account, balanceIncrease.add(_amount), 0);
//mint an equivalent amount of tokens to cover the new deposit
_mint(_account, _amount);
emit MintOnDeposit(_account, _amount, balanceIncrease, index);
}
/**
* @dev burns token in the event of a borrow being liquidated, in case the liquidators reclaims the underlying asset
* Transfer of the liquidated asset is executed by the lending pool contract.
* only lending pools can call this function
* @param _account the address from which burn the aTokens
* @param _value the amount to burn
**/
function burnOnLiquidation(address _account, uint256 _value) external onlyLendingPool {
//cumulates the balance of the user being liquidated
(,uint256 accountBalance,uint256 balanceIncrease,uint256 index) = cumulateBalanceInternal(_account);
//adds the accrued interest and substracts the burned amount to
//the redirected balance
updateRedirectedBalanceOfRedirectionAddressInternal(_account, balanceIncrease, _value);
//burns the requested amount of tokens
_burn(_account, _value);
bool userIndexReset = false;
//reset the user data if the remaining balance is 0
if(accountBalance.sub(_value) == 0){
userIndexReset = resetDataOnZeroBalanceInternal(_account);
}
emit BurnOnLiquidation(_account, _value, balanceIncrease, userIndexReset ? 0 : index);
}
/**
* @dev transfers tokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken
* only lending pools can call this function
* @param _from the address from which transfer the aTokens
* @param _to the destination address
* @param _value the amount to transfer
**/
function transferOnLiquidation(address _from, address _to, uint256 _value) external onlyLendingPool {
//being a normal transfer, the Transfer() and BalanceTransfer() are emitted
//so no need to emit a specific event here
executeTransferInternal(_from, _to, _value);
}
/**
* @dev calculates the balance of the user, which is the
* principal balance + interest generated by the principal balance + interest generated by the redirected balance
* @param _user the user for which the balance is being calculated
* @return the total balance of the user
**/
function balanceOf(address _user) public view returns(uint256) {
//current principal balance of the user
uint256 currentPrincipalBalance = super.balanceOf(_user);
//balance redirected by other users to _user for interest rate accrual
uint256 redirectedBalance = redirectedBalances[_user];
if(currentPrincipalBalance == 0 && redirectedBalance == 0){
return 0;
}
//if the _user is not redirecting the interest to anybody, accrues
//the interest for himself
if(interestRedirectionAddresses[_user] == address(0)){
//accruing for himself means that both the principal balance and
//the redirected balance partecipate in the interest
return calculateCumulatedBalanceInternal(
_user,
currentPrincipalBalance.add(redirectedBalance)
)
.sub(redirectedBalance);
}
else {
//if the user redirected the interest, then only the redirected
//balance generates interest. In that case, the interest generated
//by the redirected balance is added to the current principal balance.
return currentPrincipalBalance.add(
calculateCumulatedBalanceInternal(
_user,
redirectedBalance
)
.sub(redirectedBalance)
);
}
}
/**
* @dev returns the principal balance of the user. The principal balance is the last
* updated stored balance, which does not consider the perpetually accruing interest.
* @param _user the address of the user
* @return the principal balance of the user
**/
function principalBalanceOf(address _user) external view returns(uint256) {
return super.balanceOf(_user);
}
/**
* @dev calculates the total supply of the specific aToken
* since the balance of every single user increases over time, the total supply
* does that too.
* @return the current total supply
**/
function totalSupply() public view returns(uint256) {
uint256 currentSupplyPrincipal = super.totalSupply();
if(currentSupplyPrincipal == 0){
return 0;
}
return currentSupplyPrincipal
.wadToRay()
.rayMul(core.getReserveNormalizedIncome(underlyingAssetAddress))
.rayToWad();
}
/**
* @dev Used to validate transfers before actually executing them.
* @param _user address of the user to check
* @param _amount the amount to check
* @return true if the _user can transfer _amount, false otherwise
**/
function isTransferAllowed(address _user, uint256 _amount) public view returns (bool) {
return dataProvider.balanceDecreaseAllowed(underlyingAssetAddress, _user, _amount);
}
/**
* @dev returns the last index of the user, used to calculate the balance of the user
* @param _user address of the user
* @return the last user index
**/
function getUserIndex(address _user) external view returns(uint256) {
return userIndexes[_user];
}
/**
* @dev returns the address to which the interest is redirected
* @param _user address of the user
* @return 0 if there is no redirection, an address otherwise
**/
function getInterestRedirectionAddress(address _user) external view returns(address) {
return interestRedirectionAddresses[_user];
}
/**
* @dev returns the redirected balance of the user. The redirected balance is the balance
* redirected by other accounts to the user, that is accrueing interest for him.
* @param _user address of the user
* @return the total redirected balance
**/
function getRedirectedBalance(address _user) external view returns(uint256) {
return redirectedBalances[_user];
}
/**
* @dev accumulates the accrued interest of the user to the principal balance
* @param _user the address of the user for which the interest is being accumulated
* @return the previous principal balance, the new principal balance, the balance increase
* and the new user index
**/
function cumulateBalanceInternal(address _user)
internal
returns(uint256, uint256, uint256, uint256) {
uint256 previousPrincipalBalance = super.balanceOf(_user);
//calculate the accrued interest since the last accumulation
uint256 balanceIncrease = balanceOf(_user).sub(previousPrincipalBalance);
//mints an amount of tokens equivalent to the amount accumulated
_mint(_user, balanceIncrease);
//updates the user index
uint256 index = userIndexes[_user] = core.getReserveNormalizedIncome(underlyingAssetAddress);
return (
previousPrincipalBalance,
previousPrincipalBalance.add(balanceIncrease),
balanceIncrease,
index
);
}
/**
* @dev updates the redirected balance of the user. If the user is not redirecting his
* interest, nothing is executed.
* @param _user the address of the user for which the interest is being accumulated
* @param _balanceToAdd the amount to add to the redirected balance
* @param _balanceToRemove the amount to remove from the redirected balance
**/
function updateRedirectedBalanceOfRedirectionAddressInternal(
address _user,
uint256 _balanceToAdd,
uint256 _balanceToRemove
) internal {
address redirectionAddress = interestRedirectionAddresses[_user];
//if there isn't any redirection, nothing to be done
if(redirectionAddress == address(0)){
return;
}
//compound balances of the redirected address
(,,uint256 balanceIncrease, uint256 index) = cumulateBalanceInternal(redirectionAddress);
//updating the redirected balance
redirectedBalances[redirectionAddress] = redirectedBalances[redirectionAddress]
.add(_balanceToAdd)
.sub(_balanceToRemove);
//if the interest of redirectionAddress is also being redirected, we need to update
//the redirected balance of the redirection target by adding the balance increase
address targetOfRedirectionAddress = interestRedirectionAddresses[redirectionAddress];
if(targetOfRedirectionAddress != address(0)){
redirectedBalances[targetOfRedirectionAddress] = redirectedBalances[targetOfRedirectionAddress].add(balanceIncrease);
}
emit RedirectedBalanceUpdated(
redirectionAddress,
balanceIncrease,
index,
_balanceToAdd,
_balanceToRemove
);
}
/**
* @dev calculate the interest accrued by _user on a specific balance
* @param _user the address of the user for which the interest is being accumulated
* @param _balance the balance on which the interest is calculated
* @return the interest rate accrued
**/
function calculateCumulatedBalanceInternal(
address _user,
uint256 _balance
) internal view returns (uint256) {
return _balance
.wadToRay()
.rayMul(core.getReserveNormalizedIncome(underlyingAssetAddress))
.rayDiv(userIndexes[_user])
.rayToWad();
}
/**
* @dev executes the transfer of aTokens, invoked by both _transfer() and
* transferOnLiquidation()
* @param _from the address from which transfer the aTokens
* @param _to the destination address
* @param _value the amount to transfer
**/
function executeTransferInternal(
address _from,
address _to,
uint256 _value
) internal {
require(_value > 0, "Transferred amount needs to be greater than zero");
//cumulate the balance of the sender
(,
uint256 fromBalance,
uint256 fromBalanceIncrease,
uint256 fromIndex
) = cumulateBalanceInternal(_from);
//cumulate the balance of the receiver
(,
,
uint256 toBalanceIncrease,
uint256 toIndex
) = cumulateBalanceInternal(_to);
//if the sender is redirecting his interest towards someone else,
//adds to the redirected balance the accrued interest and removes the amount
//being transferred
updateRedirectedBalanceOfRedirectionAddressInternal(_from, fromBalanceIncrease, _value);
//if the receiver is redirecting his interest towards someone else,
//adds to the redirected balance the accrued interest and the amount
//being transferred
updateRedirectedBalanceOfRedirectionAddressInternal(_to, toBalanceIncrease.add(_value), 0);
//performs the transfer
super._transfer(_from, _to, _value);
bool fromIndexReset = false;
//reset the user data if the remaining balance is 0
if(fromBalance.sub(_value) == 0){
fromIndexReset = resetDataOnZeroBalanceInternal(_from);
}
emit BalanceTransfer(
_from,
_to,
_value,
fromBalanceIncrease,
toBalanceIncrease,
fromIndexReset ? 0 : fromIndex,
toIndex
);
}
/**
* @dev executes the redirection of the interest from one address to another.
* immediately after redirection, the destination address will start to accrue interest.
* @param _from the address from which transfer the aTokens
* @param _to the destination address
**/
function redirectInterestStreamInternal(
address _from,
address _to
) internal {<FILL_FUNCTION_BODY> }
/**
* @dev function to reset the interest stream redirection and the user index, if the
* user has no balance left.
* @param _user the address of the user
* @return true if the user index has also been reset, false otherwise. useful to emit the proper user index value
**/
function resetDataOnZeroBalanceInternal(address _user) internal returns(bool) {
//if the user has 0 principal balance, the interest stream redirection gets reset
interestRedirectionAddresses[_user] = address(0);
//emits a InterestStreamRedirected event to notify that the redirection has been reset
emit InterestStreamRedirected(_user, address(0),0,0,0);
//if the redirected balance is also 0, we clear up the user index
if(redirectedBalances[_user] == 0){
userIndexes[_user] = 0;
return true;
}
else{
return false;
}
}
} | contract AToken is ERC20, ERC20Detailed {
using WadRayMath for uint256;
uint256 public constant UINT_MAX_VALUE = uint256(-1);
/**
* @dev emitted after the redeem action
* @param _from the address performing the redeem
* @param _value the amount to be redeemed
* @param _fromBalanceIncrease the cumulated balance since the last update of the user
* @param _fromIndex the last index of the user
**/
event Redeem(
address indexed _from,
uint256 _value,
uint256 _fromBalanceIncrease,
uint256 _fromIndex
);
/**
* @dev emitted after the mint action
* @param _from the address performing the mint
* @param _value the amount to be minted
* @param _fromBalanceIncrease the cumulated balance since the last update of the user
* @param _fromIndex the last index of the user
**/
event MintOnDeposit(
address indexed _from,
uint256 _value,
uint256 _fromBalanceIncrease,
uint256 _fromIndex
);
/**
* @dev emitted during the liquidation action, when the liquidator reclaims the underlying
* asset
* @param _from the address from which the tokens are being burned
* @param _value the amount to be burned
* @param _fromBalanceIncrease the cumulated balance since the last update of the user
* @param _fromIndex the last index of the user
**/
event BurnOnLiquidation(
address indexed _from,
uint256 _value,
uint256 _fromBalanceIncrease,
uint256 _fromIndex
);
/**
* @dev emitted during the transfer action
* @param _from the address from which the tokens are being transferred
* @param _to the adress of the destination
* @param _value the amount to be minted
* @param _fromBalanceIncrease the cumulated balance since the last update of the user
* @param _toBalanceIncrease the cumulated balance since the last update of the destination
* @param _fromIndex the last index of the user
* @param _toIndex the last index of the liquidator
**/
event BalanceTransfer(
address indexed _from,
address indexed _to,
uint256 _value,
uint256 _fromBalanceIncrease,
uint256 _toBalanceIncrease,
uint256 _fromIndex,
uint256 _toIndex
);
/**
* @dev emitted when the accumulation of the interest
* by an user is redirected to another user
* @param _from the address from which the interest is being redirected
* @param _to the adress of the destination
* @param _fromBalanceIncrease the cumulated balance since the last update of the user
* @param _fromIndex the last index of the user
**/
event InterestStreamRedirected(
address indexed _from,
address indexed _to,
uint256 _redirectedBalance,
uint256 _fromBalanceIncrease,
uint256 _fromIndex
);
/**
* @dev emitted when the redirected balance of an user is being updated
* @param _targetAddress the address of which the balance is being updated
* @param _targetBalanceIncrease the cumulated balance since the last update of the target
* @param _targetIndex the last index of the user
* @param _redirectedBalanceAdded the redirected balance being added
* @param _redirectedBalanceRemoved the redirected balance being removed
**/
event RedirectedBalanceUpdated(
address indexed _targetAddress,
uint256 _targetBalanceIncrease,
uint256 _targetIndex,
uint256 _redirectedBalanceAdded,
uint256 _redirectedBalanceRemoved
);
event InterestRedirectionAllowanceChanged(
address indexed _from,
address indexed _to
);
address public underlyingAssetAddress;
mapping (address => uint256) private userIndexes;
mapping (address => address) private interestRedirectionAddresses;
mapping (address => uint256) private redirectedBalances;
mapping (address => address) private interestRedirectionAllowances;
LendingPoolAddressesProvider private addressesProvider;
LendingPoolCore private core;
LendingPool private pool;
LendingPoolDataProvider private dataProvider;
modifier onlyLendingPool {
require(
msg.sender == address(pool),
"The caller of this function must be a lending pool"
);
_;
}
modifier whenTransferAllowed(address _from, uint256 _amount) {
require(isTransferAllowed(_from, _amount), "Transfer cannot be allowed.");
_;
}
constructor(
LendingPoolAddressesProvider _addressesProvider,
address _underlyingAsset,
uint8 _underlyingAssetDecimals,
string memory _name,
string memory _symbol
) public ERC20Detailed(_name, _symbol, _underlyingAssetDecimals) {
addressesProvider = _addressesProvider;
core = LendingPoolCore(addressesProvider.getLendingPoolCore());
pool = LendingPool(addressesProvider.getLendingPool());
dataProvider = LendingPoolDataProvider(addressesProvider.getLendingPoolDataProvider());
underlyingAssetAddress = _underlyingAsset;
}
/**
* @notice ERC20 implementation internal function backing transfer() and transferFrom()
* @dev validates the transfer before allowing it. NOTE: This is not standard ERC20 behavior
**/
function _transfer(address _from, address _to, uint256 _amount) internal whenTransferAllowed(_from, _amount) {
executeTransferInternal(_from, _to, _amount);
}
/**
* @dev redirects the interest generated to a target address.
* when the interest is redirected, the user balance is added to
* the recepient redirected balance.
* @param _to the address to which the interest will be redirected
**/
function redirectInterestStream(address _to) external {
redirectInterestStreamInternal(msg.sender, _to);
}
/**
* @dev redirects the interest generated by _from to a target address.
* when the interest is redirected, the user balance is added to
* the recepient redirected balance. The caller needs to have allowance on
* the interest redirection to be able to execute the function.
* @param _from the address of the user whom interest is being redirected
* @param _to the address to which the interest will be redirected
**/
function redirectInterestStreamOf(address _from, address _to) external {
require(
msg.sender == interestRedirectionAllowances[_from],
"Caller is not allowed to redirect the interest of the user"
);
redirectInterestStreamInternal(_from,_to);
}
/**
* @dev gives allowance to an address to execute the interest redirection
* on behalf of the caller.
* @param _to the address to which the interest will be redirected. Pass address(0) to reset
* the allowance.
**/
function allowInterestRedirectionTo(address _to) external {
require(_to != msg.sender, "User cannot give allowance to himself");
interestRedirectionAllowances[msg.sender] = _to;
emit InterestRedirectionAllowanceChanged(
msg.sender,
_to
);
}
/**
* @dev redeems aToken for the underlying asset
* @param _amount the amount being redeemed
**/
function redeem(uint256 _amount) external {
require(_amount > 0, "Amount to redeem needs to be > 0");
//cumulates the balance of the user
(,
uint256 currentBalance,
uint256 balanceIncrease,
uint256 index) = cumulateBalanceInternal(msg.sender);
uint256 amountToRedeem = _amount;
//if amount is equal to uint(-1), the user wants to redeem everything
if(_amount == UINT_MAX_VALUE){
amountToRedeem = currentBalance;
}
require(amountToRedeem <= currentBalance, "User cannot redeem more than the available balance");
//check that the user is allowed to redeem the amount
require(isTransferAllowed(msg.sender, amountToRedeem), "Transfer cannot be allowed.");
//if the user is redirecting his interest towards someone else,
//we update the redirected balance of the redirection address by adding the accrued interest,
//and removing the amount to redeem
updateRedirectedBalanceOfRedirectionAddressInternal(msg.sender, balanceIncrease, amountToRedeem);
// burns tokens equivalent to the amount requested
_burn(msg.sender, amountToRedeem);
bool userIndexReset = false;
//reset the user data if the remaining balance is 0
if(currentBalance.sub(amountToRedeem) == 0){
userIndexReset = resetDataOnZeroBalanceInternal(msg.sender);
}
// executes redeem of the underlying asset
pool.redeemUnderlying(
underlyingAssetAddress,
msg.sender,
amountToRedeem,
currentBalance.sub(amountToRedeem)
);
emit Redeem(msg.sender, amountToRedeem, balanceIncrease, userIndexReset ? 0 : index);
}
/**
* @dev mints token in the event of users depositing the underlying asset into the lending pool
* only lending pools can call this function
* @param _account the address receiving the minted tokens
* @param _amount the amount of tokens to mint
*/
function mintOnDeposit(address _account, uint256 _amount) external onlyLendingPool {
//cumulates the balance of the user
(,
,
uint256 balanceIncrease,
uint256 index) = cumulateBalanceInternal(_account);
//if the user is redirecting his interest towards someone else,
//we update the redirected balance of the redirection address by adding the accrued interest
//and the amount deposited
updateRedirectedBalanceOfRedirectionAddressInternal(_account, balanceIncrease.add(_amount), 0);
//mint an equivalent amount of tokens to cover the new deposit
_mint(_account, _amount);
emit MintOnDeposit(_account, _amount, balanceIncrease, index);
}
/**
* @dev burns token in the event of a borrow being liquidated, in case the liquidators reclaims the underlying asset
* Transfer of the liquidated asset is executed by the lending pool contract.
* only lending pools can call this function
* @param _account the address from which burn the aTokens
* @param _value the amount to burn
**/
function burnOnLiquidation(address _account, uint256 _value) external onlyLendingPool {
//cumulates the balance of the user being liquidated
(,uint256 accountBalance,uint256 balanceIncrease,uint256 index) = cumulateBalanceInternal(_account);
//adds the accrued interest and substracts the burned amount to
//the redirected balance
updateRedirectedBalanceOfRedirectionAddressInternal(_account, balanceIncrease, _value);
//burns the requested amount of tokens
_burn(_account, _value);
bool userIndexReset = false;
//reset the user data if the remaining balance is 0
if(accountBalance.sub(_value) == 0){
userIndexReset = resetDataOnZeroBalanceInternal(_account);
}
emit BurnOnLiquidation(_account, _value, balanceIncrease, userIndexReset ? 0 : index);
}
/**
* @dev transfers tokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken
* only lending pools can call this function
* @param _from the address from which transfer the aTokens
* @param _to the destination address
* @param _value the amount to transfer
**/
function transferOnLiquidation(address _from, address _to, uint256 _value) external onlyLendingPool {
//being a normal transfer, the Transfer() and BalanceTransfer() are emitted
//so no need to emit a specific event here
executeTransferInternal(_from, _to, _value);
}
/**
* @dev calculates the balance of the user, which is the
* principal balance + interest generated by the principal balance + interest generated by the redirected balance
* @param _user the user for which the balance is being calculated
* @return the total balance of the user
**/
function balanceOf(address _user) public view returns(uint256) {
//current principal balance of the user
uint256 currentPrincipalBalance = super.balanceOf(_user);
//balance redirected by other users to _user for interest rate accrual
uint256 redirectedBalance = redirectedBalances[_user];
if(currentPrincipalBalance == 0 && redirectedBalance == 0){
return 0;
}
//if the _user is not redirecting the interest to anybody, accrues
//the interest for himself
if(interestRedirectionAddresses[_user] == address(0)){
//accruing for himself means that both the principal balance and
//the redirected balance partecipate in the interest
return calculateCumulatedBalanceInternal(
_user,
currentPrincipalBalance.add(redirectedBalance)
)
.sub(redirectedBalance);
}
else {
//if the user redirected the interest, then only the redirected
//balance generates interest. In that case, the interest generated
//by the redirected balance is added to the current principal balance.
return currentPrincipalBalance.add(
calculateCumulatedBalanceInternal(
_user,
redirectedBalance
)
.sub(redirectedBalance)
);
}
}
/**
* @dev returns the principal balance of the user. The principal balance is the last
* updated stored balance, which does not consider the perpetually accruing interest.
* @param _user the address of the user
* @return the principal balance of the user
**/
function principalBalanceOf(address _user) external view returns(uint256) {
return super.balanceOf(_user);
}
/**
* @dev calculates the total supply of the specific aToken
* since the balance of every single user increases over time, the total supply
* does that too.
* @return the current total supply
**/
function totalSupply() public view returns(uint256) {
uint256 currentSupplyPrincipal = super.totalSupply();
if(currentSupplyPrincipal == 0){
return 0;
}
return currentSupplyPrincipal
.wadToRay()
.rayMul(core.getReserveNormalizedIncome(underlyingAssetAddress))
.rayToWad();
}
/**
* @dev Used to validate transfers before actually executing them.
* @param _user address of the user to check
* @param _amount the amount to check
* @return true if the _user can transfer _amount, false otherwise
**/
function isTransferAllowed(address _user, uint256 _amount) public view returns (bool) {
return dataProvider.balanceDecreaseAllowed(underlyingAssetAddress, _user, _amount);
}
/**
* @dev returns the last index of the user, used to calculate the balance of the user
* @param _user address of the user
* @return the last user index
**/
function getUserIndex(address _user) external view returns(uint256) {
return userIndexes[_user];
}
/**
* @dev returns the address to which the interest is redirected
* @param _user address of the user
* @return 0 if there is no redirection, an address otherwise
**/
function getInterestRedirectionAddress(address _user) external view returns(address) {
return interestRedirectionAddresses[_user];
}
/**
* @dev returns the redirected balance of the user. The redirected balance is the balance
* redirected by other accounts to the user, that is accrueing interest for him.
* @param _user address of the user
* @return the total redirected balance
**/
function getRedirectedBalance(address _user) external view returns(uint256) {
return redirectedBalances[_user];
}
/**
* @dev accumulates the accrued interest of the user to the principal balance
* @param _user the address of the user for which the interest is being accumulated
* @return the previous principal balance, the new principal balance, the balance increase
* and the new user index
**/
function cumulateBalanceInternal(address _user)
internal
returns(uint256, uint256, uint256, uint256) {
uint256 previousPrincipalBalance = super.balanceOf(_user);
//calculate the accrued interest since the last accumulation
uint256 balanceIncrease = balanceOf(_user).sub(previousPrincipalBalance);
//mints an amount of tokens equivalent to the amount accumulated
_mint(_user, balanceIncrease);
//updates the user index
uint256 index = userIndexes[_user] = core.getReserveNormalizedIncome(underlyingAssetAddress);
return (
previousPrincipalBalance,
previousPrincipalBalance.add(balanceIncrease),
balanceIncrease,
index
);
}
/**
* @dev updates the redirected balance of the user. If the user is not redirecting his
* interest, nothing is executed.
* @param _user the address of the user for which the interest is being accumulated
* @param _balanceToAdd the amount to add to the redirected balance
* @param _balanceToRemove the amount to remove from the redirected balance
**/
function updateRedirectedBalanceOfRedirectionAddressInternal(
address _user,
uint256 _balanceToAdd,
uint256 _balanceToRemove
) internal {
address redirectionAddress = interestRedirectionAddresses[_user];
//if there isn't any redirection, nothing to be done
if(redirectionAddress == address(0)){
return;
}
//compound balances of the redirected address
(,,uint256 balanceIncrease, uint256 index) = cumulateBalanceInternal(redirectionAddress);
//updating the redirected balance
redirectedBalances[redirectionAddress] = redirectedBalances[redirectionAddress]
.add(_balanceToAdd)
.sub(_balanceToRemove);
//if the interest of redirectionAddress is also being redirected, we need to update
//the redirected balance of the redirection target by adding the balance increase
address targetOfRedirectionAddress = interestRedirectionAddresses[redirectionAddress];
if(targetOfRedirectionAddress != address(0)){
redirectedBalances[targetOfRedirectionAddress] = redirectedBalances[targetOfRedirectionAddress].add(balanceIncrease);
}
emit RedirectedBalanceUpdated(
redirectionAddress,
balanceIncrease,
index,
_balanceToAdd,
_balanceToRemove
);
}
/**
* @dev calculate the interest accrued by _user on a specific balance
* @param _user the address of the user for which the interest is being accumulated
* @param _balance the balance on which the interest is calculated
* @return the interest rate accrued
**/
function calculateCumulatedBalanceInternal(
address _user,
uint256 _balance
) internal view returns (uint256) {
return _balance
.wadToRay()
.rayMul(core.getReserveNormalizedIncome(underlyingAssetAddress))
.rayDiv(userIndexes[_user])
.rayToWad();
}
/**
* @dev executes the transfer of aTokens, invoked by both _transfer() and
* transferOnLiquidation()
* @param _from the address from which transfer the aTokens
* @param _to the destination address
* @param _value the amount to transfer
**/
function executeTransferInternal(
address _from,
address _to,
uint256 _value
) internal {
require(_value > 0, "Transferred amount needs to be greater than zero");
//cumulate the balance of the sender
(,
uint256 fromBalance,
uint256 fromBalanceIncrease,
uint256 fromIndex
) = cumulateBalanceInternal(_from);
//cumulate the balance of the receiver
(,
,
uint256 toBalanceIncrease,
uint256 toIndex
) = cumulateBalanceInternal(_to);
//if the sender is redirecting his interest towards someone else,
//adds to the redirected balance the accrued interest and removes the amount
//being transferred
updateRedirectedBalanceOfRedirectionAddressInternal(_from, fromBalanceIncrease, _value);
//if the receiver is redirecting his interest towards someone else,
//adds to the redirected balance the accrued interest and the amount
//being transferred
updateRedirectedBalanceOfRedirectionAddressInternal(_to, toBalanceIncrease.add(_value), 0);
//performs the transfer
super._transfer(_from, _to, _value);
bool fromIndexReset = false;
//reset the user data if the remaining balance is 0
if(fromBalance.sub(_value) == 0){
fromIndexReset = resetDataOnZeroBalanceInternal(_from);
}
emit BalanceTransfer(
_from,
_to,
_value,
fromBalanceIncrease,
toBalanceIncrease,
fromIndexReset ? 0 : fromIndex,
toIndex
);
}
<FILL_FUNCTION>
/**
* @dev function to reset the interest stream redirection and the user index, if the
* user has no balance left.
* @param _user the address of the user
* @return true if the user index has also been reset, false otherwise. useful to emit the proper user index value
**/
function resetDataOnZeroBalanceInternal(address _user) internal returns(bool) {
//if the user has 0 principal balance, the interest stream redirection gets reset
interestRedirectionAddresses[_user] = address(0);
//emits a InterestStreamRedirected event to notify that the redirection has been reset
emit InterestStreamRedirected(_user, address(0),0,0,0);
//if the redirected balance is also 0, we clear up the user index
if(redirectedBalances[_user] == 0){
userIndexes[_user] = 0;
return true;
}
else{
return false;
}
}
} |
address currentRedirectionAddress = interestRedirectionAddresses[_from];
require(_to != currentRedirectionAddress, "Interest is already redirected to the user");
//accumulates the accrued interest to the principal
(uint256 previousPrincipalBalance,
uint256 fromBalance,
uint256 balanceIncrease,
uint256 fromIndex) = cumulateBalanceInternal(_from);
require(fromBalance > 0, "Interest stream can only be redirected if there is a valid balance");
//if the user is already redirecting the interest to someone, before changing
//the redirection address we substract the redirected balance of the previous
//recipient
if(currentRedirectionAddress != address(0)){
updateRedirectedBalanceOfRedirectionAddressInternal(_from,0, previousPrincipalBalance);
}
//if the user is redirecting the interest back to himself,
//we simply set to 0 the interest redirection address
if(_to == _from) {
interestRedirectionAddresses[_from] = address(0);
emit InterestStreamRedirected(
_from,
address(0),
fromBalance,
balanceIncrease,
fromIndex
);
return;
}
//first set the redirection address to the new recipient
interestRedirectionAddresses[_from] = _to;
//adds the user balance to the redirected balance of the destination
updateRedirectedBalanceOfRedirectionAddressInternal(_from,fromBalance,0);
emit InterestStreamRedirected(
_from,
_to,
fromBalance,
balanceIncrease,
fromIndex
);
| function redirectInterestStreamInternal(
address _from,
address _to
) internal | /**
* @dev executes the redirection of the interest from one address to another.
* immediately after redirection, the destination address will start to accrue interest.
* @param _from the address from which transfer the aTokens
* @param _to the destination address
**/
function redirectInterestStreamInternal(
address _from,
address _to
) internal |
88985 | EmergencyToggle | null | contract EmergencyToggle is Ownable{
// pause the entire contract if true
bool public emergencyFlag;
// constructor
constructor () public{<FILL_FUNCTION_BODY> }
/**
* @dev onlyHotOwner can can pause the usage of issue,redeem, transfer functions
*/
function emergencyToggle() external onlyHotOwner {
emergencyFlag = !emergencyFlag;
}
} | contract EmergencyToggle is Ownable{
// pause the entire contract if true
bool public emergencyFlag;
<FILL_FUNCTION>
/**
* @dev onlyHotOwner can can pause the usage of issue,redeem, transfer functions
*/
function emergencyToggle() external onlyHotOwner {
emergencyFlag = !emergencyFlag;
}
} |
emergencyFlag = false;
| constructor () public | // constructor
constructor () public |
7335 | PlanetSale | available | contract PlanetSale is Ownable
{
// PlanetSold: _planet has been sold
//
event PlanetSold(uint32 indexed prefix, uint32 indexed planet);
// azimuth: points state data store
//
Azimuth public azimuth;
// price: ether per planet, in wei
//
uint256 public price;
// constructor(): configure the points data store and initial sale price
//
constructor(Azimuth _azimuth, uint256 _price)
public
{
require(0 < _price);
azimuth = _azimuth;
setPrice(_price);
}
//
// Buyer operations
//
// available(): returns true if the _planet is available for purchase
//
function available(uint32 _planet)
public
view
returns (bool result)
{<FILL_FUNCTION_BODY> }
// purchase(): pay the :price, acquire ownership of the _planet
//
// discovery of available planets can be done off-chain
//
function purchase(uint32 _planet)
external
payable
{
require( // caller must pay exactly the price of a planet
//
(msg.value == price) &&
//
// the planet must be available for purchase
//
available(_planet) );
// spawn the planet to us, then immediately transfer to the caller
//
// spawning to the caller would give the point's prefix's owner
// a window of opportunity to cancel the transfer
//
Ecliptic ecliptic = Ecliptic(azimuth.owner());
ecliptic.spawn(_planet, this);
ecliptic.transferPoint(_planet, msg.sender, false);
emit PlanetSold(azimuth.getPrefix(_planet), _planet);
}
//
// Seller operations
//
// setPrice(): configure the price in wei per planet
//
function setPrice(uint256 _price)
public
onlyOwner
{
require(0 < _price);
price = _price;
}
// withdraw(): withdraw ether funds held by this contract to _target
//
function withdraw(address _target)
external
onlyOwner
{
require(0x0 != _target);
_target.transfer(address(this).balance);
}
// close(): end the sale by destroying this contract and transferring
// remaining funds to _target
//
function close(address _target)
external
onlyOwner
{
require(0x0 != _target);
selfdestruct(_target);
}
} | contract PlanetSale is Ownable
{
// PlanetSold: _planet has been sold
//
event PlanetSold(uint32 indexed prefix, uint32 indexed planet);
// azimuth: points state data store
//
Azimuth public azimuth;
// price: ether per planet, in wei
//
uint256 public price;
// constructor(): configure the points data store and initial sale price
//
constructor(Azimuth _azimuth, uint256 _price)
public
{
require(0 < _price);
azimuth = _azimuth;
setPrice(_price);
}
<FILL_FUNCTION>
// purchase(): pay the :price, acquire ownership of the _planet
//
// discovery of available planets can be done off-chain
//
function purchase(uint32 _planet)
external
payable
{
require( // caller must pay exactly the price of a planet
//
(msg.value == price) &&
//
// the planet must be available for purchase
//
available(_planet) );
// spawn the planet to us, then immediately transfer to the caller
//
// spawning to the caller would give the point's prefix's owner
// a window of opportunity to cancel the transfer
//
Ecliptic ecliptic = Ecliptic(azimuth.owner());
ecliptic.spawn(_planet, this);
ecliptic.transferPoint(_planet, msg.sender, false);
emit PlanetSold(azimuth.getPrefix(_planet), _planet);
}
//
// Seller operations
//
// setPrice(): configure the price in wei per planet
//
function setPrice(uint256 _price)
public
onlyOwner
{
require(0 < _price);
price = _price;
}
// withdraw(): withdraw ether funds held by this contract to _target
//
function withdraw(address _target)
external
onlyOwner
{
require(0x0 != _target);
_target.transfer(address(this).balance);
}
// close(): end the sale by destroying this contract and transferring
// remaining funds to _target
//
function close(address _target)
external
onlyOwner
{
require(0x0 != _target);
selfdestruct(_target);
}
} |
uint16 prefix = azimuth.getPrefix(_planet);
return ( // planet must not have an owner yet
//
azimuth.isOwner(_planet, 0x0) &&
//
// this contract must be allowed to spawn for the prefix
//
azimuth.isSpawnProxy(prefix, this) &&
//
// prefix must be linked
//
azimuth.hasBeenLinked(prefix) );
| function available(uint32 _planet)
public
view
returns (bool result)
| //
// Buyer operations
//
// available(): returns true if the _planet is available for purchase
//
function available(uint32 _planet)
public
view
returns (bool result)
|
36599 | darkhbtcStrategydeFortubev1 | withdraw | contract darkhbtcStrategydeFortubev1 {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address constant public want = address(0x0316EB71485b0Ab14103307bf65a021042c6d380); //hbtc
address constant public output = address(0x1FCdcE58959f536621d76f5b7FfB955baa5A672F); //for
address constant public unirouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address constant public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // used for for <> weth <> usdc route
address constant public dark = address(0x3108ccFd96816F9E663baA0E8c5951D229E8C6da);
address constant public fortube = address(0xdE7B3b2Fe0E7b4925107615A5b199a4EB40D9ca9);// main contract
address constant public fortube_reward = address(0xF8Df2E6E46AC00Cdf3616C4E35278b7704289d82); // reward contract
uint public strategyfee = 100;
uint public fee = 300;
uint public burnfee = 500;
uint public callfee = 100;
uint constant public max = 1000;
uint public withdrawalFee = 0;
uint constant public withdrawalMax = 10000;
address public governance;
address public strategyDev;
address public controller;
address public burnAddress = 0xB6af2DabCEBC7d30E440714A33E5BD45CEEd103a;
address public darkUnipool = 0x4332b546635Ef22F71bD354c1EFd238c2602Dd8d;
string public getName;
address[] public swap2DARKRouting;
address[] public swap2TokenRouting;
constructor() public {
governance = msg.sender;
controller = 0xff56f173b473350E1387EE327F92d7C3ec1cd676;
getName = string(
abi.encodePacked("dark:Strategy:",
abi.encodePacked(IERC20(want).name(),"The Force Token"
)
));
swap2DARKRouting = [output,weth,dark];
swap2TokenRouting = [output,weth,want];
doApprove();
strategyDev = tx.origin;
}
function doApprove () public{
IERC20(output).safeApprove(unirouter, 0);
IERC20(output).safeApprove(unirouter, uint(-1));
}
function deposit() public {
uint _want = IERC20(want).balanceOf(address(this));
address _controller = For(fortube).controller();
if (_want > 0) {
// IERC20(want).safeApprove(_controller, 0);
IERC20(want).safeApprove(_controller, _want);
For(fortube).deposit(want,_want);
}
}
// Controller only function for creating additional rewards from dust
function withdraw(IERC20 _asset) external returns (uint balance) {<FILL_FUNCTION_BODY> }
// Withdraw partial funds, normally used with a vault withdrawal
function withdraw(uint _amount) external {
require(msg.sender == controller, "!controller");
uint _balance = IERC20(want).balanceOf(address(this));
if (_balance < _amount) {
_amount = _withdrawSome(_amount.sub(_balance));
_amount = _amount.add(_balance);
}
uint _fee = 0;
if (withdrawalFee>0){
_fee = _amount.mul(withdrawalFee).div(withdrawalMax);
IERC20(want).safeTransfer(Controller(controller).rewards(), _fee);
}
address _vault = Controller(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want).safeTransfer(_vault, _amount.sub(_fee));
}
// Withdraw all funds, normally used when migrating strategies
function withdrawAll() external returns (uint balance) {
require(msg.sender == controller || msg.sender == governance,"!governance");
_withdrawAll();
balance = IERC20(want).balanceOf(address(this));
address _vault = Controller(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want).safeTransfer(_vault, balance);
}
function _withdrawAll() internal {
address _controller = For(fortube).controller();
IFToken fToken = IFToken(IBankController(_controller).getFTokeAddress(want));
uint b = fToken.balanceOf(address(this));
For(fortube).withdraw(want,b);
}
function harvest() public {
require(!Address.isContract(msg.sender),"!contract");
ForReward(fortube_reward).claimReward();
doswap();
dosplit();// market buy dark
deposit();
}
function doswap() internal {
uint256 _2token = IERC20(output).balanceOf(address(this)).mul(50).div(100); //50%
uint256 _2dark = IERC20(output).balanceOf(address(this)).mul(50).div(100); //50%
UniswapRouter(unirouter).swapExactTokensForTokens(_2token, 0, swap2TokenRouting, address(this), now.add(1800));
UniswapRouter(unirouter).swapExactTokensForTokens(_2dark, 0, swap2DARKRouting, address(this), now.add(1800));
}
function dosplit() internal{
uint b = IERC20(dark).balanceOf(address(this));
uint _fee = b.mul(fee).div(max);
uint _callfee = b.mul(callfee).div(max);
uint _burnfee = b.mul(burnfee).div(max);
// IERC20(dark).safeTransfer(Controller(controller).rewards(), _fee);
IERC20(dark).safeTransfer(darkUnipool, _fee); // darkUnipool 3%
IERC20(dark).safeTransfer(msg.sender, _callfee); //call fee 1%
// IERC20(dark).safeTransfer(burnAddress, _burnfee);
IERC20(dark).safeTransfer(darkUnipool, _burnfee); //darkUnipool 5%
if (strategyfee >0){
uint _strategyfee = b.mul(strategyfee).div(max); // darkUnipool 1%
// IERC20(dark).safeTransfer(strategyDev, _strategyfee);
IERC20(dark).safeTransfer(darkUnipool, _strategyfee);
}
}
function _withdrawSome(uint256 _amount) internal returns (uint) {
For(fortube).withdrawUnderlying(want,_amount);
return _amount;
}
function balanceOfWant() public view returns (uint) {
return IERC20(want).balanceOf(address(this));
}
function balanceOfPool() public view returns (uint) {
address _controller = For(fortube).controller();
IFToken fToken = IFToken(IBankController(_controller).getFTokeAddress(want));
return fToken.calcBalanceOfUnderlying(address(this));
}
function balanceOf() public view returns (uint) {
return balanceOfWant()
.add(balanceOfPool());
}
function setGovernance(address _governance) external {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setController(address _controller) external {
require(msg.sender == governance, "!governance");
controller = _controller;
}
function setFee(uint256 _fee) external{
require(msg.sender == governance, "!governance");
fee = _fee;
}
function setStrategyFee(uint256 _fee) external{
require(msg.sender == governance, "!governance");
strategyfee = _fee;
}
function setCallFee(uint256 _fee) external{
require(msg.sender == governance, "!governance");
callfee = _fee;
}
function setBurnFee(uint256 _fee) external{
require(msg.sender == governance, "!governance");
burnfee = _fee;
}
function setBurnAddress(address _burnAddress) public{
require(msg.sender == governance, "!governance");
burnAddress = _burnAddress;
}
function setWithdrawalFee(uint _withdrawalFee) external {
require(msg.sender == governance, "!governance");
require(_withdrawalFee <=100,"fee >= 1%"); //max:1%
withdrawalFee = _withdrawalFee;
}
} | contract darkhbtcStrategydeFortubev1 {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address constant public want = address(0x0316EB71485b0Ab14103307bf65a021042c6d380); //hbtc
address constant public output = address(0x1FCdcE58959f536621d76f5b7FfB955baa5A672F); //for
address constant public unirouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address constant public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // used for for <> weth <> usdc route
address constant public dark = address(0x3108ccFd96816F9E663baA0E8c5951D229E8C6da);
address constant public fortube = address(0xdE7B3b2Fe0E7b4925107615A5b199a4EB40D9ca9);// main contract
address constant public fortube_reward = address(0xF8Df2E6E46AC00Cdf3616C4E35278b7704289d82); // reward contract
uint public strategyfee = 100;
uint public fee = 300;
uint public burnfee = 500;
uint public callfee = 100;
uint constant public max = 1000;
uint public withdrawalFee = 0;
uint constant public withdrawalMax = 10000;
address public governance;
address public strategyDev;
address public controller;
address public burnAddress = 0xB6af2DabCEBC7d30E440714A33E5BD45CEEd103a;
address public darkUnipool = 0x4332b546635Ef22F71bD354c1EFd238c2602Dd8d;
string public getName;
address[] public swap2DARKRouting;
address[] public swap2TokenRouting;
constructor() public {
governance = msg.sender;
controller = 0xff56f173b473350E1387EE327F92d7C3ec1cd676;
getName = string(
abi.encodePacked("dark:Strategy:",
abi.encodePacked(IERC20(want).name(),"The Force Token"
)
));
swap2DARKRouting = [output,weth,dark];
swap2TokenRouting = [output,weth,want];
doApprove();
strategyDev = tx.origin;
}
function doApprove () public{
IERC20(output).safeApprove(unirouter, 0);
IERC20(output).safeApprove(unirouter, uint(-1));
}
function deposit() public {
uint _want = IERC20(want).balanceOf(address(this));
address _controller = For(fortube).controller();
if (_want > 0) {
// IERC20(want).safeApprove(_controller, 0);
IERC20(want).safeApprove(_controller, _want);
For(fortube).deposit(want,_want);
}
}
<FILL_FUNCTION>
// Withdraw partial funds, normally used with a vault withdrawal
function withdraw(uint _amount) external {
require(msg.sender == controller, "!controller");
uint _balance = IERC20(want).balanceOf(address(this));
if (_balance < _amount) {
_amount = _withdrawSome(_amount.sub(_balance));
_amount = _amount.add(_balance);
}
uint _fee = 0;
if (withdrawalFee>0){
_fee = _amount.mul(withdrawalFee).div(withdrawalMax);
IERC20(want).safeTransfer(Controller(controller).rewards(), _fee);
}
address _vault = Controller(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want).safeTransfer(_vault, _amount.sub(_fee));
}
// Withdraw all funds, normally used when migrating strategies
function withdrawAll() external returns (uint balance) {
require(msg.sender == controller || msg.sender == governance,"!governance");
_withdrawAll();
balance = IERC20(want).balanceOf(address(this));
address _vault = Controller(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want).safeTransfer(_vault, balance);
}
function _withdrawAll() internal {
address _controller = For(fortube).controller();
IFToken fToken = IFToken(IBankController(_controller).getFTokeAddress(want));
uint b = fToken.balanceOf(address(this));
For(fortube).withdraw(want,b);
}
function harvest() public {
require(!Address.isContract(msg.sender),"!contract");
ForReward(fortube_reward).claimReward();
doswap();
dosplit();// market buy dark
deposit();
}
function doswap() internal {
uint256 _2token = IERC20(output).balanceOf(address(this)).mul(50).div(100); //50%
uint256 _2dark = IERC20(output).balanceOf(address(this)).mul(50).div(100); //50%
UniswapRouter(unirouter).swapExactTokensForTokens(_2token, 0, swap2TokenRouting, address(this), now.add(1800));
UniswapRouter(unirouter).swapExactTokensForTokens(_2dark, 0, swap2DARKRouting, address(this), now.add(1800));
}
function dosplit() internal{
uint b = IERC20(dark).balanceOf(address(this));
uint _fee = b.mul(fee).div(max);
uint _callfee = b.mul(callfee).div(max);
uint _burnfee = b.mul(burnfee).div(max);
// IERC20(dark).safeTransfer(Controller(controller).rewards(), _fee);
IERC20(dark).safeTransfer(darkUnipool, _fee); // darkUnipool 3%
IERC20(dark).safeTransfer(msg.sender, _callfee); //call fee 1%
// IERC20(dark).safeTransfer(burnAddress, _burnfee);
IERC20(dark).safeTransfer(darkUnipool, _burnfee); //darkUnipool 5%
if (strategyfee >0){
uint _strategyfee = b.mul(strategyfee).div(max); // darkUnipool 1%
// IERC20(dark).safeTransfer(strategyDev, _strategyfee);
IERC20(dark).safeTransfer(darkUnipool, _strategyfee);
}
}
function _withdrawSome(uint256 _amount) internal returns (uint) {
For(fortube).withdrawUnderlying(want,_amount);
return _amount;
}
function balanceOfWant() public view returns (uint) {
return IERC20(want).balanceOf(address(this));
}
function balanceOfPool() public view returns (uint) {
address _controller = For(fortube).controller();
IFToken fToken = IFToken(IBankController(_controller).getFTokeAddress(want));
return fToken.calcBalanceOfUnderlying(address(this));
}
function balanceOf() public view returns (uint) {
return balanceOfWant()
.add(balanceOfPool());
}
function setGovernance(address _governance) external {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setController(address _controller) external {
require(msg.sender == governance, "!governance");
controller = _controller;
}
function setFee(uint256 _fee) external{
require(msg.sender == governance, "!governance");
fee = _fee;
}
function setStrategyFee(uint256 _fee) external{
require(msg.sender == governance, "!governance");
strategyfee = _fee;
}
function setCallFee(uint256 _fee) external{
require(msg.sender == governance, "!governance");
callfee = _fee;
}
function setBurnFee(uint256 _fee) external{
require(msg.sender == governance, "!governance");
burnfee = _fee;
}
function setBurnAddress(address _burnAddress) public{
require(msg.sender == governance, "!governance");
burnAddress = _burnAddress;
}
function setWithdrawalFee(uint _withdrawalFee) external {
require(msg.sender == governance, "!governance");
require(_withdrawalFee <=100,"fee >= 1%"); //max:1%
withdrawalFee = _withdrawalFee;
}
} |
require(msg.sender == controller, "!controller");
require(want != address(_asset), "want");
balance = _asset.balanceOf(address(this));
_asset.safeTransfer(controller, balance);
| function withdraw(IERC20 _asset) external returns (uint balance) | // Controller only function for creating additional rewards from dust
function withdraw(IERC20 _asset) external returns (uint balance) |
19879 | CPT | approveAndCall | contract CPT is StandardToken {
function () {
throw;
}
/* Public variables of the token */
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
function CPT(
) {
balances[msg.sender] = 1000000000000000000000000000;
totalSupply = 1000000000000000000000000000;
name = "Cryptoprivacytoken";
decimals = 18;
symbol = "CPT";
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {<FILL_FUNCTION_BODY> }
} | contract CPT is StandardToken {
function () {
throw;
}
/* Public variables of the token */
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
function CPT(
) {
balances[msg.sender] = 1000000000000000000000000000;
totalSupply = 1000000000000000000000000000;
name = "Cryptoprivacytoken";
decimals = 18;
symbol = "CPT";
}
<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) |
75454 | Lunchbox | null | contract Lunchbox is ERC20, ERC20Burnable {
constructor() ERC20("Lunchbox", "LUNCH") {<FILL_FUNCTION_BODY> }
} | contract Lunchbox is ERC20, ERC20Burnable {
<FILL_FUNCTION>
} |
_mint(msg.sender, 21000000 * 10 ** decimals());
| constructor() ERC20("Lunchbox", "LUNCH") | constructor() ERC20("Lunchbox", "LUNCH") |
31897 | Pausable | setStatus | contract Pausable is Destructible {
bool public paused;
event NewStatus (bool isPaused);
modifier whenNotPaused () {
if (paused) revert();
_;
}
modifier whenPaused () {
if (!paused) revert();
_;
}
function setStatus (bool isPaused) public onlyOwner {<FILL_FUNCTION_BODY> }
} | contract Pausable is Destructible {
bool public paused;
event NewStatus (bool isPaused);
modifier whenNotPaused () {
if (paused) revert();
_;
}
modifier whenPaused () {
if (!paused) revert();
_;
}
<FILL_FUNCTION>
} |
paused = isPaused;
emit NewStatus(isPaused);
| function setStatus (bool isPaused) public onlyOwner | function setStatus (bool isPaused) public onlyOwner |